Linux下音頻編程-輸出音頻文件


程序實現了在Linux下播放Ok.wav的功能。程序首先調用fstat函數獲得文件相關信息(主要是文件大小信息)。通過malloc函數分配指定的內存空間,並將online.wav讀入內存;然后,打開聲卡設備文件,設置聲卡參數;再調用write函數完成文件的播放。

簡要的實例,代碼如下:

#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"

//不同的聲音有着不同的播放參數,這些參數可以使用file命令獲得

#define Sample_Size 16 //there're two kinds of bits,8 bits and 16 bits
#define Sample_Rate 8000 //sampling rate

int play_sound(char *filename){
    struct stat stat_buf;
    unsigned char * buf = NULL;
    int handler,fd;
    int result;
    int arg,status;
   
    //打開聲音文件,將文件讀入內存
    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;
   }

   //打開聲卡設備,並設置聲卡播放參數,這些參數必須與聲音文件參數一致
   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");
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM