gpt4 book ai didi

python - 如何在输入流中播放声音

转载 作者:太空宇宙 更新时间:2023-11-04 11:08:59 26 4
gpt4 key购买 nike

我想知道是否可以将声音直接播放到 python 的输入中。我正在使用 linux,并且我正在使用 OSS、ALSA 和 Pulseaudio

最佳答案

你绝对可以用 python 播放(和生成)声音

下面是生成正弦波的示例代码,打开默认的 Alsa 播放设备并通过它播放正弦波

#!/usr/bin/env python3
import math
import struct
import alsaaudio
from itertools import *

def sine_wave(frequency=440.0, framerate=44100, amplitude=0.5):
"""Stolen from here: http://zacharydenton.com/generate-audio-with-python/"""
period = int(framerate / frequency)
if amplitude > 1.0: amplitude = 1.0
if amplitude < 0.0: amplitude = 0.0
lookup_table = [float(amplitude) * math.sin(2.0*math.pi*float(frequency)*(float(i%period)/float(framerate))) for i in range(period)]
return (lookup_table[i%period] for i in count(0))

sound_out = alsaaudio.PCM() # open default sound output
sound_out.setchannels(1) # use only one channel of audio (aka mono)
sound_out.setrate(44100) # how many samples per second
sound_out.setformat(alsaaudio.PCM_FORMAT_FLOAT_LE) # sample format

for sample in sine_wave():
# alsa only eats binnary data
b = struct.pack("<f", sample) # convert python float to binary float
sound_out.write(b)

或者你可以将麦克风环回你的扬声器

#!/usr/bin/env python3
import struct
import alsaaudio

sound_out = alsaaudio.PCM() # open default sound output
sound_out.setchannels(1) # use only one channel of audio (aka mono)
sound_out.setperiodsize(5) # buffer size, default is 32

sound_in = alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE) # default recording device
sound_in.setchannels(1) # use only one channel of audio (aka mono)
sound_in.setperiodsize(5) # buffer size, default is 32

while True:
sample_lenght, sample = sound_in.read()
sound_out.write(sample)

可以在 python alsaaudio 库中找到更多示例 http://pyalsaaudio.sourceforge.net/libalsaaudio.html

关于python - 如何在输入流中播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24074684/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com