Alsaaudio录音和回放

Alsaaudio record and playback

我只是在使用 python 在 raspberry pi 上玩弄声音输入和输出。 我的计划是读取麦克风的输入,操纵它并播放操纵的音频。此刻我试图阅读和播放音频。 读取似乎有效,因为我在最后一步将读取的数据写入 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_FORMAT_FLOAT_LE 这种格式不是我的耳机使用的格式(只是不加思索地复制并粘贴了它)。 我在控制台中通过 运行 speaker-test 了解了我的麦克风格式(和其他信息)。

因为我的扬声器格式是 S16_LE 代码可以很好地与 audioformat = audio.PCM_FORMAT_S16_LE

考虑至少对链的接收器部分使用 plughw(支持 resampling/conversion 的 alsa 子系统):

#Output Device out = audio.PCM(audio.PCM_PLAYBACK,device='plughw:0,0')

这应该有助于协商采样率和数据格式。

periodsize 最好根据采样率的 1/倍来估计,例如:

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

而睡眠时间最好估计为播放所需时间的一半 periodsize:

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