回撥模式音訊 IO

"""PyAudio Example: Play a wave file (callback version)."""

import pyaudio
import wave
import time
import sys

if len(sys.argv) < 2:
    print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
    sys.exit(-1)

wf = wave.open(sys.argv[1], 'rb')

# instantiate PyAudio (1)
p = pyaudio.PyAudio()

# define callback (2)
def callback(in_data, frame_count, time_info, status):
    data = wf.readframes(frame_count)
    return (data, pyaudio.paContinue)

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

# start the stream (4)
stream.start_stream()

# wait for stream to finish (5)
while stream.is_active():
    time.sleep(0.1)

# stop stream (6)
stream.stop_stream()
stream.close()
wf.close()

# close PyAudio (7)
p.terminate()

在回撥模式下,只要需要新的音訊資料(播放)和/或有新的(錄製的)音訊資料可用,PyAudio 就會呼叫指定的回撥函式(2)。請注意,PyAudio 在單獨的執行緒中呼叫回撥函式。該函式具有以下簽名 callback(<input_data>, <frame_count>, <time_info>, <status_flag>),並且必須返回包含 frame_count 幀音訊資料的元組和表示是否有更多幀要播放/記錄的標誌。

使用 pyaudio.Stream.start_stream() (4) 開始處理音訊流,它將重複呼叫回撥函式,直到該函式返回 pyaudio.paComplete

為了保持流活動,主執行緒不能終止,例如,通過休眠(5)。