您的位置:首页 > 运维架构 > Linux

linux 下音频的录制与播放测试例子

2016-01-06 21:19 721 查看
main.c文件

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "sndtools.h"
int main(int argc, char const *argv[])
{
char *buf;
int dwSize;
if(!OpenSnd()){//打开声音设备
printf("Open sound device error!\\n");
exit(-1);
}
//SetFormat(FMT16BITS, FMT8K, WAVOUTDEV);
SetFormat(FMT16BITS, FMT8K);
//SetChannel(MONO, WAVOUTDEV);
SetChannel(MONO);
buf = (char *)malloc(320);
if(buf == NULL) exit(-1);

int i;
printf("begin...\n");
for(i = 0; i <1000; i++){
dwSize = Record(buf, 640); //录音
dwSize = Play(buf, dwSize);//播放
}
printf("close...\n");
CloseSnd();
return 0;
}


sndtools.c文件
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <string.h>
#define VAR_STATIC
#include "sndtools.h"
int devfd = 0;

//打开音响设备,如果成功返回1,否则返回0。
int OpenSnd(void)
{
if(devfd > 0)
close(devfd);
devfd = open(DEV_NAME, O_RDWR);
if(devfd < 0)
return 0;
return 1;
}

/*
* 设置录制播放格式
* 如果成功返回1,否则返回0。
* bits -- FMT8BITS(8bits), FMT16BITS(16bits)
* hz -- FMT8K(8000HZ), FMT16K(16000HZ), FMT22K(22000HZ), FMT44K(44000HZ)
*/
// SetFormat(FMT16BITS, FMT8K);
int SetFormat(int bits, int hz)
{
int tmp = bits;
if( -1 == ioctl(devfd, SNDCTL_DSP_SETFMT, &tmp)){
printf("Set fmt to s16_little faile\r\n");
return 0;
}

tmp = hz;
if( -1 == ioctl(devfd, SNDCTL_DSP_SPEED, &tmp)){
printf("Set speed to %d\r\n", hz);
return 0;
}
return 1;
}

/*
* 声卡设置通道
* 如果成功返回1,否则返回0。
* chn -- MONO, STERO
*/
//MONO
int SetChannel(int chn)
{
int tmp = chn;
if(-1 == ioctl(devfd, SNDCTL_DSP_CHANNELS, &tmp)){
printf("Set Audio Channel faile\r\n");
return 0;
}
return 1;
}

/*
* 记录
* 返回读取的字节数量。
*/

int Record(char *buf, int size){
return read(devfd, buf, size);
}

/*
* 回放
* 返回的字节数量写。
*/
int Play(char *buf, int size){
return write(devfd, buf, size);
}

//关闭声音设备,如果成功返回1,否则返回0。
int CloseSnd(void)
{
close(devfd);
devfd = 0;
return 1;
}



sndtools.h文件
#ifndef SNDTOOLS_H
#define SNDTOOLS_H
#include <linux/soundcard.h>
#define FMT8BITS AFMT_S8_LE
#define FMT16BITS AFMT_S16_LE
#define DEV_NAME "/dev/dsp"
#define FMT8K 8000
#define FMT16K 16000
#define FMT22K 22000
#define FMT44K 44000
#define MONO 1
#define STERO 2

#ifndef VAR_STATIC
extern int devfd;
extern int CapMask;
#endif

#define DEBUG() //printf("Time=[%s] FILE=[%s] LINE=[%d]\n",__TIME__,__FILE__,__LINE__);
#define ERR_EXIT(m) (perror(m),exit(EXIT_FAILURE))

//打开声音设备,如果打开成功返回1
//否则返回0
int OpenSnd(void);
//关闭声音设备
int CloseSnd(void);
//记录或回放设置格式,如果成功返回1
//否则返回0
int SetFormat(int bits, int hz);
//设置记录或回放通道,如果成功返回1
//返回1
int SetChannel(int chn);
//记录
int Record(char *buf, int size);
//播放
int Play(char *buf, int size);
#endif



makefile文件
OBJS = main.o sndtools.o
TARGET = out
CC = gcc

$(TARGET):$(OBJS)
$(CC) -O2 -o $(TARGET) $(OBJS)
clean:
-$(RM) $(TARGET)
-$(RM) $(OBJS)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  linux 编程 音频