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.
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
You may try it 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 );
}
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.