Search code examples
ioscore-audiopcmpulseaudio

generating the square wave with pulses


I am trying to modify the method of generating the square wave that

it can generate eight pulses with different pulse width with 0.3ms delay each per a period. I have seen that sampleBuffer is responsible for generating the pulse signals but i am not sure how to create a function of the pulse for such specific pattern. Would you please tell me whether there is a library function at AudioTrack.h for generating the pulse ?

The below is my code for

generating the square wave

void generateSquare(SInt16 *sampleBuffer, int numFrames, float sampleRate, float frequency, float amp) {
    if(amp>1) amp=1;
    if(amp<0) amp=0;
    amp = amp*SHRT_MAX;
    float samplesPerCycle = sampleRate/frequency;
    for(int i = 0; i < numFrames; i++) {

        if(fmodf(squareIndex, samplesPerCycle)/samplesPerCycle > 0.5) {
            sampleBuffer[i] = amp;
        } else {
            sampleBuffer[i] = -1*amp;
        }

        squareIndex = squareIndex+1;

        if(squareIndex >= samplesPerCycle) squareIndex-=samplesPerCycle;
    }
}

Solution

  • Here is my solution for nearly the same problem.
    In my case I create pulse with 1ms width, which I modify with the fill value by +/-0.5ms. So according to fillValue I generate a square wave with 0.5-1.5ms pulse width.

    int squareIndex = 0;
    void generateSquare(SInt16 *sampleBuffer, int numFrames, float sampleRate, float fillValue, float amp) {
        // Fill value = pulse width value in frames
        // fillValue = [-20, 20];
    
        if(amp>1) amp=1;
        if(amp<0) amp=0;
    
        if(fillValue > 20) fillValue = 20;
        if(fillValue < -20) fillValue = -20;
    
        amp = amp*SHRT_MAX;
        float samplesPerCycle = sampleRate/50;
    
        //Sample / Cycle = 882
        //1ms = 41 frame -> 0.5ms = 20(.5)frame
        //In your case 0.3ms = 12(.3) frame
    
        #pragma mark - PWM
        for(int i = 0; i < numFrames; i++) {
    
            //if(fmodf(squareIndex, samplesPerCycle)/samplesPerCycle < 0.05) {
            if(squareIndex < 41 + fillValue) {
    
                sampleBuffer[i] = 1*SHRT_MAX;
            } else {
                sampleBuffer[i] = 0;
            }
    
            squareIndex = squareIndex+1;
    
            if(squareIndex >= samplesPerCycle) squareIndex-=samplesPerCycle;
        }
    }