CSC231 How to play a wav file in C
--D. Thiebaut 21:04, 2 December 2008 (UTC)
Playing a wav file in C
Under Ubuntu, the utility aplay is available. Not necessarily under Fedora, so this recipe will work for your project under Ubuntu. (Note: if you are working on a Mac, use the utility afplay instead. It does not use the same switches as aplay, and will play a wav file directly.)
Assuming that you have a wav audio file (this recipe works only with wav files), say, daffyduck1.wav, you can play it under ubuntu with the following command:
aplay -c 1 -t wav -q duffyduck1.wav
Note: this is a good way to test if the file is playable on your system. I have found that not all wav files are equal, and some will play with aplay while others won't.
You may try the aplay command with duffyduck1.wav!
So, all you have to do in C is to use the function system(), which is included in stdlib.h, and pass it the command as if you were to type it on the command line.
Modify the driver.c program so that it includes the function playSound() as shown below:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int playSound( char *filename ) {
char command[256];
int status;
/* create command to execute */
sprintf( command, "aplay -c 1 -q -t wav %s", filename );
/* play sound */
status = system( command );
return status;
}
int main( int argc, char *argv[] ) {
if ( argc < 2 ) {
printf("Syntax: playSound filename.wav\n\n" );
exit( 1 );
}
/* play the wav file 3 times in a row */
playSound( argv[1] );
playSound( argv[1] );
playSound( argv[1] );
return 0;
}
The program above expects the name of a wav file on the command line (argv[1]) and passes it to the function playSound() which includes the file name in the command aplay -c 1 -q -t wav filename.wav which will play the file.