Python Alsaaudio录音和回放

Python Alsaaudio录音和回放,python,audio,pyalsaaudio,Python,Audio,Pyalsaaudio,我只是在用python在raspberry pi上玩声音输入和输出。 我的计划是读取麦克风的输入,对其进行操作,然后播放被操作的音频。当时我试图阅读和播放音频。 读取似乎有效,因为我在最后一步将读取的数据写入了一个wave文件,而wave文件似乎很好。 但播放的只是噪音。 播放wave文件也很有效,所以耳机很好。 我想我的设置或输出格式可能有问题。 守则: import alsaaudio as audio import time import audioop #Input & Ou

我只是在用python在raspberry pi上玩声音输入和输出。 我的计划是读取麦克风的输入,对其进行操作,然后播放被操作的音频。当时我试图阅读和播放音频。 读取似乎有效,因为我在最后一步将读取的数据写入了一个wave文件,而wave文件似乎很好。 但播放的只是噪音。 播放wave文件也很有效,所以耳机很好。 我想我的设置或输出格式可能有问题。 守则:

import alsaaudio as audio
import time
import audioop


#Input & Output Settings
periodsize = 1024
audioformat = audio.PCM_FORMAT_FLOAT_LE
channels = 16
framerate=8000

#Input Device
inp = audio.PCM(audio.PCM_CAPTURE,audio.PCM_NONBLOCK,device='hw:1,0')
inp.setchannels(channels)
inp.setrate(framerate)
inp.setformat(audioformat)
inp.setperiodsize(periodsize)

#Output Device
out = audio.PCM(audio.PCM_PLAYBACK,device='hw:0,0')
out.setchannels(channels)
out.setrate(framerate)
out.setformat(audioformat)
out.setperiodsize(periodsize)


#Reading the Input
allData = bytearray()
count = 0
while True:
    #reading the input into one long bytearray
    l,data = inp.read()
    for b in data:
        allData.append(b)

    #Just an ending condition
    count += 1
    if count == 4000:
        break

    time.sleep(.001)


#splitting the bytearray into period sized chunks
list1 = [allData[i:i+periodsize] for i in range(0, len(allData), periodsize)]

#Writing the output
for arr in list1:
    # I tested writing the arr's to a wave file at this point
    # and the wave file was fine
    out.write(arr)

编辑:也许我应该提到,我正在使用python 3,我刚刚找到了答案
audioformat=audio.PCM\u FORMAT\u FLOAT\u LE
此格式不是我的耳机所使用的格式(只是复制并粘贴了它,没有经过仔细考虑)。 通过在控制台中运行
扬声器测试
,我了解了我的麦克风格式(以及其他信息)

由于my speakers格式为S16_LE,因此代码可与
audioformat=audio.PCM_format_S16_LE

配合使用,考虑对链的接收器部分至少使用plughw(支持重采样/转换的alsa子系统):

#输出设备
out=audio.PCM(audio.PCM_播放,设备='plughw:0,0')

这将有助于协商采样率和数据格式

periodsize最好基于1/倍的采样率进行估计,如:

periodsize=帧率/8
(8=8000 KHz采样率的次数)

睡眠时间最好估计为玩游戏所需时间的一半:


sleeptime=1.0/16
(1.0-是秒,对于8000 KHz采样率,16=2*次)

应该不需要打开16个通道。如果设置
channel=1
,行为是否会发生变化?仅使用1个通道进行了尝试,不幸的是,它仍然是相同的。也许我应该提到,我正在使用python 3(将编辑问题),您可以使用aplay/arecord检查支持的设备参数——转储hw参数,并尝试使用aplay从控制台直接播放wave文件。