如何在Raspberry Pi上使用c ++ / libao / alsa通过USB声卡播放音频?

时间:2017-06-06 16:24:35

标签: c++ linux raspberry-pi arm

我从aplay -l, lsusb获得以下内容:

pi@raspberrypi:~ $ aplay -l
**** List of PLAYBACK Hardware Devices ****
card 0: ALSA [bcm2835 ALSA], device 0: bcm2835 ALSA [bcm2835 ALSA]
  Subdevices: 8/8
  Subdevice #0: subdevice #0
  Subdevice #1: subdevice #1
  Subdevice #2: subdevice #2
  Subdevice #3: subdevice #3
  Subdevice #4: subdevice #4
  Subdevice #5: subdevice #5
  Subdevice #6: subdevice #6
  Subdevice #7: subdevice #7
card 0: ALSA [bcm2835 ALSA], device 1: bcm2835 ALSA [bcm2835 IEC958/HDMI]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 1: Device [USB PnP Sound Device], device 0: USB Audio [USB Audio]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 2: Device_1 [USB PnP Sound Device], device 0: USB Audio [USB Audio]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
pi@raspberrypi:~ $ lsusb
Bus 001 Device 005: ID 046d:c31c Logitech, Inc. Keyboard K120 for Business
Bus 001 Device 008: ID 0d8c:013c C-Media Electronics, Inc. CM108 Audio Controller
Bus 001 Device 007: ID 0d8c:013c C-Media Electronics, Inc. CM108 Audio Controller
Bus 001 Device 006: ID 05e3:0606 Genesys Logic, Inc. USB 2.0 Hub / D-Link DUB-H4 USB 2.0 Hub
Bus 001 Device 004: ID 1bcf:0005 Sunplus Innovation Technology Inc. 
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter
Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp. 
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

我想通过带有libao的CM108音频控制器播放我的MP3。我试过这些:

ao_initialize();
ao_option aoption;
ao_option *poption;
poption = &aoption;
poption->key = (char*)"dev";
poption->value = (char*)"hw:0";
dev = ao_open_live(driver, &format, poption); 
    while (mpg123_read(mh, buffer, buffer_size, &done) == MPG123_OK)
        ao_play(dev, (char *)buffer, done);

声音通过Pi成功播放。据我所知,hw:0是Pi的声卡。如果我想通过第一个或第二个CM108音频控制器播放,我应该使用什么而不是hw:0?我已经尝试过hw:1和hw:2但它不起作用。

1 个答案:

答案 0 :(得分:0)

尝试按照以下步骤启用音频录制和播放,从usb-sound适配器开始,首先使用alsa进行rpi。有了这个,您可以测试您的USB声音适配器是否正常作为输入和输出模块。我没有在C ++代码中使用上述库的用例之前进行测试,很快就会试一试。请参考" hw:1"稍后在你的C ++代码中工作。

步骤: 1.1)创建/编辑文件.asoundrc

$vim .asoundrc

如果文件不存在,请创建它;

$ touch .asoundrc

$vim .asoundrc 
pcm.!default {
        type asym
        playback.pcm "hw:1,0"
        capture.pcm "hw:1,0"
}

ctl.!default {
        type hw
        card 1
}

1.2)编辑文件alsa.conf中的以下行;

$sudo vim /usr/share/alsa/alsa.conf
defaults.ctl.card 0
defaults.pcm.card 0

$sudo vim /usr/share/alsa/alsa.conf
defaults.ctl.card 1
defaults.pcm.card 1

1.3)使用alsamixer实用程序

更改音频电平/设置
$alsamixer

1.4)录制音频的命令

$arecord -D plughw:1 -f S16_LE -r 48000 -d 5 ./testSound.wav

1.5)播放录制音频的命令

$aplay --device=plughw:1,0 ./testSound.wav