Sound & thread

Hi !

I am trying to play sound and the function must be called from a separate thread.
Here, it’s the code of my function:


int Play_Sound (void* data){
Mix_Chunk *wav;
wav = Mix_LoadWAV(“shak.wav”);
if(!wav) {
printf(“Mix_LoadWAV:-%s\n”, Mix_GetError());
// handle error
}
phaserChannel = Mix_PlayChannel(-1, wav, -1);
SDL_Delay (3000);
}


If I call this function directly from the main program, it’s works.

But, if I call this function in a separate thread like:
thread1 = SDL_CreateThread (Play_Sound, NULL);
I have the error (from the function):
Mix_LoadWAV:-Mix_LoadWAV_RW with NULL src

Any help will be greatly appreciated !
Thanks !

Talie

as a general rule don’t do anything not specifically declared thread
safe in a thread. this includes library functions, possibly very
common ones.

i don’t know if SDL_Mixer has any thread safe parts but most of the
main sdl library is not.

if you get the FastEvents library
http://www.gameprogrammer.com/fastevents/fastevents1.html

you can use the FastEvent functions in threads( or some of them anyway )

then use your thread to send an SDL_USEREVENT with the name of the wav

add code to your main loop to detect such events and to do

Mix_Chunk *wav;
wav = Mix_LoadWAV(“shak.wav”);
if(!wav) {
printf(“Mix_LoadWAV:-%s\n”, Mix_GetError());
// handle error
}
phaserChannel = Mix_PlayChannel(-1, wav, -1);

or whatever
i think SDL_Delay( x ) won’t work as you intend here

basically threads are complicated :slight_smile:

but more to the point, there is an easier way to do what you are
doing( playing a sound every 3 seconds?)

set a callback function.

i never used one but i saw an example once and it looked a bit crazy
but it works.
look up the wiki under timer functions

I am trying to play sound and the function must be called from a separate thread.

For what it’s worth, SDL_mixer does all its heavy processing in a
seperate thread already, so you don’t need to spin a thread to keep the
audio seperate. Unless there’s another reason to keep a seperate thread,
just call Mix_LoadWAV and Mix_PlayChannel from the main thread.

I don’t see any reason your code wouldn’t work, though, unless fopen()
is failing from another thread (Mix_LoadWav() eventually calls fopen(),
and would give that error message if it fails). If it’s a C runtime
conflict (which has been known to happen on Windows), you can load the
file into memory yourself and use a memory rwops to feed it to SDL_mixer.

–ryan.

as a follow up on my post, i was very wrong…

this is in the SDL_Mixer docs i have

“t is also a BAD idea to call SDL_mixer and SDL audio functions from a
callback. Callbacks include Effects functions and other SDL_mixer
audio hooks.”