Alsaaudio唱片和播放

2024-10-01 09:25:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是在用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)

编辑:也许我应该提到,我使用的是python3


Tags: 文件theimportinputoutwaveaudiopcm
2条回答

我刚找到答案。audioformat = audio.PCM_FORMAT_FLOAT_LE这个格式不是我耳机使用的格式(只是不经考虑就复制粘贴的)。 我通过在控制台中运行speaker-test找到了我的麦克风格式(和其他信息)。在

由于我的speakers格式是S16\u LE,所以代码可以很好地与audioformat = audio.PCM_FORMAT_S16_LE配合使用

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

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

这将有助于协商采样率以及数据格式。在

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

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

睡眠时间最好估计为播放周期所需时间的一半大小:

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

相关问题 更多 >