Reputation: 2387
I currently have a 2 channel wav file. I would like to have the ability to play one channel at a time. Using the examples from the PyAudio website where you read in a chunk of data through the wave module and then write to stream, I am unsure whether I need to somehow read in one channel of data and write to a one channel stream, or if there is some other solution. Thanks for the help.
Upvotes: 1
Views: 2780
Reputation: 11547
I propose you alter the stream and overwrite the channel that you do not want to hear, with data from the channel you want to hear. Normally, channels are interleaved, so the following should do the trick.
import pyaudio
import wave
import sys
chunk = 1024
def convert(data, sampleSize = 4, channel = 0):
for i in range(0, len(data), 2*sampleSize):
for j in range(0, sampleSize):
data[i + j + sampleSize * channel] = data[i + j + sampleSize * (1 - channel)]
if len(sys.argv) < 2:
print "Plays a wave file.\n\n" +\
"Usage: %s filename.wav" % sys.argv[0]
sys.exit(-1)
wf = wave.open(sys.argv[1], 'rb')
p = pyaudio.PyAudio()
# open stream
stream = p.open(format =
p.get_format_from_width(wf.getsampwidth()),
channels = wf.getnchannels(),
rate = wf.getframerate(),
output = True)
# read data
data = wf.readframes(chunk)
convert(data)
# play stream
while data != '':
stream.write(data)
data = wf.readframes(chunk)
convert(data)
stream.close()
p.terminate()
Upvotes: 2