我正在为我的程序处理音频,需要实现一个简单的监视器回放。
为了进行“实时”处理,所有的pydub.AudioSegments在被送到机器上之前都会被切成20毫秒的块。最后,数据段被发送到一个简单的deque,这个简单的pydub.AudioSegment正在被充满20ms的数据,直到它有300ms的价值。
@tasks.loop(seconds=0.01)
async def fill(self):
if source is None:
print("NOPE")
return
if len(deque) < size:
try:
segment = next(self.source.audio_segment_generator
deque.append(segment)
except StopIteration:
print("source depleted")deque正在被弹出到一个不和谐的机器人上,它需要20ms的音频字节。
一切都完美无瑕,但是我也需要一个简单的本地播放,如果需要,可以直接向扬声器播放音频。
如下所示:还假设它在自己的线程上运行:
from pydub.playback import play
def play_from_deque(deque):
while True:
if is_playing_monitor:
play(deque.pop())我写了一个快速简单的测试,看看pydub.play()是否会在20ms的片段上被重复调用:
mp3 = requests.get("http://www.hochmuth.com/mp3/Haydn_Adagio.mp3")
segment = AudioSegment.from_file(io.BytesIO(mp3.content), format='mp3').set_frame_rate(40800)
sliced_segments = segment[::20]
for slice in sliced_segments:
play(slice)但音频变得非常断断续续,几乎无法辨认。
经过一些谷歌搜索后,有人提到了import sounddevice as sd,但到目前为止,我还没有能够让它工作。可以使用segment.raw_data访问原始字节,因此音频也可以从字节播放。
有什么我应该研究的技巧或python库吗?
发布于 2021-01-05 05:27:28
我自己想出来了,如果有人有类似的问题,下面是代码:
我让它通过以下方式工作:
import io
import requests
import pyaudio
from pydub import AudioSegment
mp3 = requests.get("http://www.hochmuth.com/mp3/Haydn_Adagio.mp3")
segment = AudioSegment.from_file(io.BytesIO(mp3.content), format='mp3').set_frame_rate(40800)
sliced_segments = segment[::20]
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(segment.sample_width),
channels=segment.channels,
rate=segment.frame_rate,
output=True)
while True:
try:
for slice in sliced_segments:
stream.write(slice.raw_data)
finally:
stream.stop_stream()
stream.close()
p.terminate()https://stackoverflow.com/questions/65568510
复制相似问题