The program realizes the function of playing ok.wav under Linux. The program first calls the Fstat function to obtain file-related information (primarily file size information). Allocates the specified memory space through the malloc function and reads the online.wav into memory, then opens the sound card device file, sets the sound card parameters, and then calls the Write function to complete the playback of the file.
A brief example of the code is as follows:
#include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <stdio.h> #include <linux/soundcard.h> #define Audio_device "/DEV/DSP"// Different sounds have different playback parameters, these parameters can be obtained by using the file command # sample_size//there ' re, kinds of bits,8 bits and Bits#define sample_rate 8 //sampling rateint Play_sound (char *filename) {struct stat stat_buf; unsigned char * buf = NULL; int handler,fd; int result; int arg,status; Open a sound file and read the file into memory Fd=open (filename,o_rdonly); if (fd<0) return-1; if (Fstat (fd,&stat_buf)) {close (FD); return-1; } if (!stat_buf.st_size) {close (FD); return-1; } buf=malloc (Stat_buf.st_size); if (!BUF) {close (FD); return-1; } if (read (fd,buf,stat_buf.st_size) <0) {free (BUF); Close (FD); return-1; }//Open the sound card device and set the sound card playback parameters, these parameters must be consistent with the sound file parameters Handler=open (audio_device,o_wronly); if (handler==-1) {perror ("Open Audio_device fail "); return-1; } arg=sample_rate; Status=ioctl (HANDLER,SOUND_PCM_WRITE_RATE,&ARG); if (status==-1) {perror ("error from sound_pcm_write_rate ioctl"); return-1; } arg=sample_size; Status=ioctl (HANDLER,SOUND_PCM_WRITE_BITS,&ARG); if (status==-1) {perror ("error from sound_pcm_write_bits ioctl"); return-1; } result=write (Handler,buf,stat_buf.st_size); if (result==-1) {perror ("Fail to play the sound!"); return-1; } free (BUF); Close (FD); Close (handler); return result;} void Main (void) {Play_sound ("/root/online.wav");}
Linux under Audio Programming-output audio file