0
votes

I have tried several ways to play sound using either MediaFoundation or the simple PlaySound method. Both of these seem to expect a .WAV file. I can't play sound from a WAVE file since I'm getting the data from internet and discarding it right once it is played. I need it to be efficient and fast and done directly from a memory buffer. MediaFoundations code to playback audio is very long and requires several steps. While PlaySound is simple but it doesn't play my sound from memory buffer. I've also tried SDL_mixer but I can't seem to set the sound buffer directly instead of relying on SDL_LoadWav. Here's my PlaySound code taken from here Load wavs into memory then play sounds asynchronously using Win32 API:

unsigned char* sounddata;
hr = pSoundBuffer->Lock(&sounddata, NULL, &soundlength);
PlaySound((LPCWSTR) sounddata, GetModuleHandle(NULL), SND_MEMORY);

Here's my SDL_mixer code:

SDL_Init(SDL_INIT_AUDIO);
Mix_OpenAudio(22050, AUDIO_S16, 2, NULL);
Mix_Chunk* sound = new Mix_Chunk();
sound->allocated = 1;
sound->abuf = sounddata;
sound->alen = soundlength;
sound->volume = 128;
Mix_PlayChannel(-1, sound, 0);

With SDL_mixer I'm just getting random noise. So my question is how to play sound simply from memory buffer either by using SDL_mixer or the PlaySound function. Are there any other alternatives (other then MediaFoundation)?

1
Have you verified that the sound data is the correct format (16 bit stereo, not 8 bit) and that the sound bytes for the 16 bit data are in the correct order (probably low byte first)?1201ProgramAlarm
@1201ProgramAlarm I'll check that. Also, does the data need to be encasulated into a WAVE file with a header and everything or does SDL_mixer take raw data directly.user123
Even if I set AUDIO_S8 with 1 or 2 channels it doesn't work better.user123

1 Answers

2
votes

According to this page (emphasis mine):

The SND_MEMORY flag indicates that the lpszSoundName parameter is a pointer to an in-memory image of the WAVE file.

In other words, you need to prepend a WAV file header to the raw data (otherwise, how else would PlaySound know how long the data was, as well as its sample rate etc?).

The format of a WAV file header is widely documented, e.g. here.