python - Alsaaudio录制和播放

标签 python audio pyalsaaudio

我只是在玩python在树莓派上输入和输出声音。
我的计划是读取麦克风的输入,对其进行操作,然后播放所操纵的音频。此刻,我尝试读取和播放音频。
读取似乎有效,因为我在最后一步将读取的数据写入了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_FORMAT_FLOAT_LE这种格式不是我的耳机使用的格式(只需复制并粘贴即可,无需三思而后行)。
我通过在控制台中运行speaker-test来了解我的麦克风格式(以及其他信息)。

由于我的扬声器格式为S16_LE,因此该代码可以与audioformat = audio.PCM_FORMAT_S16_LE一起正常使用

关于python - Alsaaudio录制和播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44095151/

相关文章:

Python alsaaudio 捕捉声音

python-3.x - alsaaudio 库不工作

python - MS SQL + Python (IronPython) 超时

python - 使用 `ode` 方法的 scipy 的 'vode' 求解器给出一个空数组结果

python - with 语句 - Python 2.5 的反向移植

java - 在 Eclipse IDE 中播放音频文件;但不是 JAR 文件

python - ALSA 库 conf.c :4528:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory

python - 如何使用python从mp3文件中提取原始数据?

html - 播放声音的最有效方法(一页中有许多播放按钮)