#
# AudioPlayer
#   Play audio files using pyaudio
# Taken from PyAudio documentation and adapted to a class by Bryan Clair
#
import pyaudio
import wave
import sys

class AudioPlayer:
	"""A class that uses pyaudio to play sounds."""
	def __init__(self):
		self._p = pyaudio.PyAudio()
	def __del__(self):
		self._p.terminate()

	def play(self,wf):
		"""Play a waveform.
		Only tested for wf created with wave.open()"""
		chunk = 1024		
		
		# open stream
		stream = self._p.open(format =
		                self._p.get_format_from_width(wf.getsampwidth()),
		                channels = wf.getnchannels(),
		                rate = wf.getframerate(),
		                output = True)
		
		# read data
		data = wf.readframes(chunk)
		
		# play stream
		while data != '':
		    stream.write(data)
		    data = wf.readframes(chunk)
		
		stream.close()

def AudioPlayerPlayWAV(filename):
	"""This function plays a WAV file, but there is some overhead involved.
	For multiple sounds, create an AudioPlayer and use play()."""
	p = AudioPlayer()
	wf = wave.open(filename,'rb')
	p.play(wf)
