无法在Raspberry pi上更改PyAudio中的卡片索引

时间:2017-11-21 00:15:42

标签: python audio raspberry-pi audio-recording pyaudio

我已将USB连接到RPi并知道它有效,因为我可以使用以下命令通过麦克风录制音频:

arecord test.wav -D sysdefault:CARD=1

现在我想编写一个可以从usb设备流式传输数据的Python程序。我编写了以下代码(在.open()中设置input_device_index = 1):

import pyaudio
import numpy as np

RATE = 44100
CHUNK = 1024

p = pyaudio.PyAudio()

stream = p.open(format=pyaudio.paInt16, channels=1, rate=RATE, input=True, input_device_index=1, frames_per_buffer=CHUNK)

while (True):
    data = np.fromstring(stream.read(CHUNK),dtype=np.int16)

stream.stop_stream()
stream.close()
p.terminate()

当我运行代码时,我得到以下错误:

"ALSA lib confmisc.c:1281:(snd_func_refer) Unable to find definition 'cards.bcm2835.pcm.front.0:CARD=0'
ALSA lib conf.c:4528:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory
ALSA lib conf.c:5007:(snd_config_expand) Evaluate error: No such file or directory
ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM front
ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
ALSA lib confmisc.c:1281:(snd_func_refer) Unable to find definition 'cards.bcm2835.pcm.surround51.0:CARD=0'  
.........  
a failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 2818
Traceback (most recent call last):
  File "RealTimePlaybackTest.py", line 9, in <module>
    stream = p.open(format=pyaudio.paInt16, channels=1, rate=RATE, input=True, input_device_index=1, frames_per_buffer=CHUNK)
  File "build/bdist.linux-armv7l/egg/pyaudio.py", line 750, in open
  File "build/bdist.linux-armv7l/egg/pyaudio.py", line 441, in __init__
IOError: [Errno -9998] Invalid number of channels

“整个错误发生在this gist中 这让我感到困惑,因为即使我在代码中设置了索引= 1,错误也表明CARD = 0。我怎样才能更改CARD = 1?

2 个答案:

答案 0 :(得分:1)

我找到了解决方案。卡号与索引号不同。我需要运行以下代码来获取索引号:

import pyaudio
p = pyaudio.PyAudio()
for i in range(p.get_device_count()):
  dev = p.get_device_info_by_index(i)
  print((i,dev['name'],dev['maxInputChannels']))

答案 1 :(得分:0)

您可以使用

获取所有捕获设备的卡号和设备号
arecord -l

我的 USB 麦克风列表为

card 1: Device [USB PnP Sound Device], device 0: USB Audio [USB Audio]

卡片指定于

/usr/share/alsa/alsa.conf

所以对于卡 1 上的捕获设备,我设置了这个

defaults.ctl.card 1
defaults.pcm.card 1

正如您所指出的,在打开流的调用中指定了设备编号; p.open(input_device_index=0).