1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
"""PyAudio Example: Play a wave file (callback version)."""
import wave
import time
import sys
import pyaudio
if len(sys.argv) < 2:
print(f'Plays a wave file. Usage: {sys.argv[0]} filename.wav')
sys.exit(-1)
with wave.open(sys.argv[1], 'rb') as wf:
# Define callback for playback (1)
def callback(in_data, frame_count, time_info, status):
data = wf.readframes(frame_count)
# If len(data) is less than requested frame_count, PyAudio automatically
# assumes the stream is finished, and the stream stops.
return (data, pyaudio.paContinue)
# Instantiate PyAudio and initialize PortAudio system resources (2)
p = pyaudio.PyAudio()
# 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)
# Wait for stream to finish (4)
while stream.is_active():
time.sleep(0.1)
# Close the stream (5)
stream.close()
# Release PortAudio system resources (6)
p.terminate()
|