iOS Audio Unit - Creating Stereo Sine Waves

此生再无相见时 提交于 2019-12-04 07:01:09

The OP seems to have solved his problem, but I thought posting an explicit answer would be helpful to the rest of us.

I had the same question of wanting to direct the tones to left and right channels independently. It's easiest to describe in terms of Matt Gallagher's now-standard An iOS tone generator (an introduction to AudioUnits).

The first change to make is to set (following @jwkerr) streamFormat.mChannelsPerFrame = 2; (instead of streamFormat.mChannelsPerFrame = 1;) in the createToneUnit method. Once that is done and you have two channels/buffers in each frame, you need to fill the left and right buffers independently in RenderTone():

// Set the left and right buffers independently
Float32 tmp;
Float32 *buffer0 = (Float32 *)ioData->mBuffers[0].mData;
Float32 *buffer1 = (Float32 *)ioData->mBuffers[1].mData;

// Generate the samples
for (UInt32 frame = 0; frame < inNumberFrames; frame++) {
    tmp = sin(theta) * amplitude;

    if (channelLR[0]) buffer0[frame] = tmp; else buffer0[frame] = 0;
    if (channelLR[1]) buffer1[frame] = tmp; else buffer1[frame] = 0;

    theta += theta_increment;
    if (theta > 2.0 * M_PI) theta -= 2.0 * M_PI;
}

Of course channelLR[2] is a bool array whose elements you set to indicate whether the respective channel is audible. Notice that the program needs to explicitly set the frames of silent channels to zero, otherwise you get some funny tones out.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!