最近使用树莓派的音频播放音频文件(需要外接声卡),自己在网上找一些alsa编程的代码用起来比较复杂,可以是自己设置的原因把,播放时有时会出现杂音。不过这两天看到了一个开源软件mplayer,它的slave模式,可以让你在通过FIFO文件控制它的播放停止和其他功能。这样你就可以通过程序控制mplayer了,甚至可以在它的基础上开发新的软件。这里用的是C语言。今天先立个搞,明天再更。
#include#include #include #include #include #include #include #define FIFO "/tmp/myfifo"int main(){ char * path = "./test.mp3"; if(mkfifo("/tmp/myfifo",0777)) printf("fifo create error\n"); if(!fork()) { system("mplayer -slave -quiet -input file=/tmp/myfifo ./test.mp3"); exit(0); } else { sleep(10); int fd = open(FIFO, O_WRONLY); write(fd, "pause\n",strlen("pause\n")); close(fd); } printf("end!\n"); return 0;}
很多需求下非阻塞open可能会用到的:
int fd = open(FIFO, O_WRONLY|O_NONBLOCK);
指定播放的声卡设备。
card 1, device 0:
mplayer -ao alsa:device=hw=1.0 test.mp3
aplay -l 查看声卡设备。
➜ music aplay -l
**** PLAYBACK 硬體裝置清單 ****card 0: PCH [HDA Intel PCH], device 0: CX20590 Analog [CX20590 Analog] 子设备: 1/1 子设备 #0: subdevice #0card 0: PCH [HDA Intel PCH], device 3: HDMI 0 [HDMI 0] 子设备: 1/1 子设备 #0: subdevice #0card 1: Device [USB Audio Device], device 0: USB Audio [USB Audio] 子设备: 0/1 子设备 #0: subdevice #0设置指定声卡的音量,
amixer -c 1 sset "Speaker",0 60%
1:是指声卡 编号 - - 1 aplay -l 能看到。
”Speaker“ 这个名字可以在alsamixer中看到。0不知道是啥意思。