Linux C OSS音频编程


在linux下也可以写一个类似麦克风和喇叭这样的应用程序,只要打开/dev/dsp这个设备驱动,对该设备read读操作相当于录音,对这个设备write写操作相当于放音。

对于以下出现的一些参数我就不多说了,百度很多,大家可以自行查找,关于音频编程还有很多,alsa和OSS混合编程是目前用得最多的,如果对这方面有兴趣的可以深入研究。

以下是当时我在学习这方面知识的时候写的一个测试程序:

测试的结果就是当对着麦克风说话时,喇叭会放出声音,前提是你的linux系统需要安装/dev/dsp这个驱动。

按照这个原理,你应该有能力可以写一个类似千千静听这样的MP3播放器的软件了!去试试吧!

#include <stdio.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
//  /usr/include/linux/videodev2.h   //v4l2接口
//  /usr/include/linux/soundcard.h   //声卡
#include <linux/soundcard.h>		

#define    SIZE    44100*2*2*5

int main(void)
{
	int fd ; 
	fd = open("/dev/dsp" , O_RDWR);
	if(-1 == fd )
	{
		perror("Open SoundCard Fail ... \n");
		return -1 ; 
	}
	//speex  声音压缩库
	//ALSA   声音解码库 	
	//读取声卡参数
	//rate  采样率   channels  声道    bits  量化位数
	int rate , channels , bits ; 
	char buffer[SIZE] = {0};
	
	
	//将声卡配置成MP3标准
	//采样率
	rate = 44100 ; 
	//通道数
	channels = 2 ; 
	//量化位数
	bits = 16 ; 

	if(ioctl(fd , SOUND_PCM_WRITE_RATE , &rate) < 0)
		perror("write soundcard rate fail");

	if(ioctl(fd , SOUND_PCM_WRITE_CHANNELS, &channels) < 0)
		perror("write soundcard channels fail");

	if(ioctl(fd , SOUND_PCM_WRITE_BITS ,&bits ) < 0)
		perror("write soundcard bits fail");

	//读取参数	
	if(ioctl(fd ,  SOUND_PCM_READ_RATE , &rate) <0)
		perror("read soundcard rate fail");

	if(ioctl(fd ,  SOUND_PCM_READ_CHANNELS, &channels) <0)
		perror("read soundcard channels fail");

	if(ioctl(fd ,  SOUND_PCM_READ_BITS , &bits) <0)
		perror("read soundcard bits fail");

	
	printf("rate:%d  channels:%d  bits:%d \n" , 
	rate , channels , bits );


	int ret ; 

	while(1)
	{
		printf("recording ... \n");
		ret = read(fd , buffer , SIZE);
		printf("playing ... \n");
		write(fd , buffer , ret);

	}

	close(fd);


	return 0 ;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值