分享

Linux下声卡编程(播放指定音频文件)

 renhl252 2014-12-23

root@ubuntu:/home/naviwork/dsp# file /usr/lib/openoffice/basis3.2/share/gallery/sounds/wallewal.wav
/usr/lib/openoffice/basis3.2/share/gallery/sounds/wallewal.wav: RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, mono 11025 Hz
root@ubuntu:/home/naviwork/dsp# ./a.out /usr/lib/openoffice/basis3.2/share/gallery/sounds/wallewal.wav 16 11025
samplebits = 16 samplerate = 11025

===============================================================
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<stdlib.h>
#include<stdio.h>
#include <stropts.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, int samplebits, int samplerate){
    struct stat stat_buf;
    unsigned char * buf = NULL;
    int handler,fd;
    int result;
    int arg,status;
    
    printf("samplebits = %d samplerate = %d\n", samplebits, samplerate);
   
    //打开声音文件,将文件读入内存
    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=(unsigned char *)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=samplerate;
   status=ioctl(handler,SOUND_PCM_WRITE_RATE,&arg);
   if(status==-1){
      perror("error from SOUND_PCM_WRITE_RATE ioctl");
      return -1;
   }

   arg=samplebits;
   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;
}

int main(int argc, char *argv[])
{
   play_sound(argv[1], atoi(argv[2]), atoi(argv[3]));
return 0;
}


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多