Allegro sound not working (playing wav file)

843 views Asked by At

I'm making a game for a school project and I have a sound effect that is supposed to play whenever a laser is fired. There was a brief period of time when it worked fine, but it has since stopped. After it stopped I changed the code a bit as I wanted to store the file in a datafile.

Initializing sound in Allegro

install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, NULL);

This is the code for loading and playing the sound

//Loading sound file from datafile
DATAFILE *laserShot = NULL;
laserShot = load_datafile_object("asteroids.dat", "laser_Shot");

//Error checking
if (laserShot->dat == NULL) {
    allegro_message("Error loading laser_Shot.wav");
}
else {
    //Playing sound for shot
    play_sample((SAMPLE*) laserShot->dat, 255, 127, 1000, 0);
}

//Freeing memory
unload_datafile_object(laserShot);

The sound itself is very short if that is of any importance, less than a second. The sound would also be trying to play multiple times in quick succession, but there's actually more of a break now than when it was originally working so I don't think that makes a difference.

Is there something I'm getting blatantly wrong?

2

There are 2 answers

0
Gapope On BEST ANSWER

Turns out I was just making a stupid mistake, I was calling the unloading function in the same function that I was playing the sound file; there was not enough time to play the sound file before the file was unloaded so while technically there was no error to be picked up by the compiler or to cause a crash, the code was trying to play a sound it had already forgotten. Removing the call for unloading allows the sound to play.

0
Michal Horanský On

At first, make sure all parameters are set, which aren't if you call just install_sound. You should also call this:

 set_config_int("sound", "quality", 1);

Third parameter refers to used quality of sound. This should mean highest quality, if you want another type, you should search in allegro libs reference.

Second, you should allocate voice. Voice is basically space in memory for playing samples. By default, allegro 4 can allocate 255 different voices, but real number can be far more less because of hardware. You do it like this:

int laser_voice = allocate_voice("sample.wav");

Now you can set parameters, like volume, pan, sweep and playmode. For example, if you want to play looped sample in same frequency and volume like source, you should do this:

voice_set_volume(   laser_voice, 200);
voice_set_pan(      laser_voice, 127);
voice_set_playmode( laser_voice, PLAYMODE_LOOP);

For other options, you should visit references.

Now, to play sample, you just call

voice_start(laser_voice);

Then you can stop it, replay it, change parameters or change sample by reallocate_voice. That's all. At end of code, you deallocate it by

deallocate_voice(laser_voice);