# Python program pa_wave.py (AHG, 2024) import os, pyaudio, sys, wave # # check commandline argument for audio file if len(sys.argv) > 2: sys.exit("Error: too many arguments") if len(sys.argv) < 2: afl = 'voice.wav' # default audio file else: afl = sys.argv[1] # # initialize PyAudio and data stream p = pyaudio.PyAudio() # PortAudio interface wf = wave.open(afl, 'rb') # open audio file chs = wf.getnchannels() swi = wf.getsampwidth() fmt = p.get_format_from_width(swi) fra = wf.getnframes() rat = wf.getframerate() dur = fra / float(rat) stream = p.open( # open stream object rate = rat, channels = chs, format = fmt, output = True, output_device_index = None # PyAudio device index (can direct the output to # USB soundcard or headphones), None for default ) # # clear the screen and print info os.system('clear') print(__file__) print("playing", afl) if chs==1: print("1 audio channel (mono)") if chs==2: print("2 audio channels (stereo)") print("audio sample width:",swi,"bytes") print("number of audio frames:",fra) print("frame rate:",rat,"per s") print("duration:",round(dur,1),"s") # # play by writing audio data to stream chk = 4096 # 4096 samples per data frame dat = wf.readframes(chk) # read data while dat: stream.write(dat) dat = wf.readframes(chk) # # final cleanup wf.close() stream.close() p.terminate()