在pyAudio中播放音频文件的功能,无需再次导入资源?

2024-05-21 01:22:45 发布

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

我需要做一个函数,当调用一个特定的歌曲必须播放。在

代码如下:

import pyaudio  
import wave

chunk = 1024
p = pyaudio.PyAudio() 

beat = wave.open(r"D:/Escritorio/beat.wav","rb") 
stream = p.open(format = p.get_format_from_width(beat.getsampwidth()),  
                channels = beat.getnchannels(),  
                rate = beat.getframerate(),  
                output = True)  

def play_song(b, s, c):
    data = b.readframes(c)
    while data != '':
        s.write(data)
        data = b.readframes(c)
    b.rewind()
    s.stop_stream()

for _ in range(10):
    #Should play the audio file 10 times, but nothing happens
    play_song(beat, stream, chunk)

如果我把beatstream定义放在函数中,它工作得很好,但是每次迭代之间的时间必须尽可能短,这样做会造成大约0.1秒的延迟,这对于这个目的来说实际上是相当糟糕的。在


Tags: 函数代码importformatplaydatastreamsong
1条回答
网友
1楼 · 发布于 2024-05-21 01:22:45

这里的答案是使用回调,它异步播放音频。在

def callback(in_data, frame_count, time_info, status):
    data = beat.readframes(frame_count)
    return (data, pyaudio.paContinue)

#open stream  
stream = p.open(format = p.get_format_from_width(beat.getsampwidth()),  
                channels = beat.getnchannels(),  
                rate = beat.getframerate(),  
                output = True,
                stream_callback=callback)  

def play_song():
    stream.start_stream()
    while stream.is_active():
        True
    stream.stop_stream()
    beat.rewind()

相关问题 更多 >