Nasir
Nasir

Reputation: 27

Understanding why sound channels swap when looping sound

I am writing a custom audio mixer in C++ which uses signed 16-bit PCM, 44100hz sample rate and 2 channels.

The problem that I'm facing is that whenever I need to loop sounds (that is, whenever I reach the end of the PCM buffer), I reset to the beginning by setting the sample index to 0, but, I noticed when playing a stereo sound with only 1 channel audible, the sound channels get swapped for some reason upon loop. The left samples actually play on the right, and right is on the left. They constantly swap every time it loops!

Code:

// this is called continuously in the audio thread:
if (BuffersPlaying() < MAX_SOUND_BUFFERS /* 2 */)
 for (size_t i = 0; i < NUM_SAMPLES_PER_BUFFER /* 1024 */ * NUM_CHANNELS; ++i)
 {
     int mixedSamples = 0;
     for (size_t k = 0; k < sounds.size(); ++k)
     {
         Sound* sound = sounds[k];
         if (!sound->playing)
             continue;

         uint pcmSize = waveBuffers[sound->waveIndex].size / sizeof(int16);
         int16* pcmData = waveBuffers[sound->waveIndex].data;

         if (sound->sampleIndex < (int)pcmSize)
         {
             mixedSamples += (int)(pcmData[sound->sampleIndex] * soundsVolume);
             sound->sampleIndex++;
         }
         else if (sound->loop)
         {
             sound->sampleIndex = 0;

             mixedSamples += (int)(pcmData[sound->sampleIndex] * soundsVolume);
         }
         else
         {
             sound->playing = false;
             sound->sampleIndex = 0;
         }
     }
     soundBuffers[currentBuffer][i] = (int16)std::clamp((int)(mixedSamples * audioVolume), -32768, 32767);
}
QueueCurrentBuffer(); // uploads the current audio buffers for the audio API to play
currentBuffer++;
currentBuffer %= MAX_SOUND_BUFFERS;

However, I noticed that in else if (sound->loop), if I set sound->sampleIndex to NUM_CHANNELS - 1 rather than 0, this actually fixes it, but I don't understand why. Why is this?

I am using XAudio2 to play back the sound buffers.

Upvotes: 1

Views: 62

Answers (0)

Related Questions