0

我正在尝试修改生成方波的方法

它可以产生8个不同脉冲宽度的脉冲,每个脉冲延迟0.3ms。我已经看到 sampleBuffer 负责生成脉冲信号,但我不确定如何为这种特定模式创建脉冲函数。请告诉我 AudioTrack.h 中是否有用于生成脉冲的库函数?

以下是我的代码

产生方波

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;
    }
}
4

1 回答 1

1

这是我对几乎相同问题的解决方案。
在我的例子中,我创建了宽度为 1ms 的脉冲,我用填充值修改了 +/-0.5ms。所以根据fillValue我生成一个0.5-1.5ms脉冲宽度的方波。

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;
    }
}
于 2014-05-02T12:15:10.573 回答