Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can the python wave module accept StringIO object

Tags:

python

audio

wave

i'm trying to use the wave module to read wav files in python.

whats not typical of my applications is that I'm NOT using a file or a filename to read the wav file, but instead i have the wav file in a buffer.

And here's what i'm doing

import StringIO

buffer = StringIO.StringIO()
buffer.output(wav_buffer)

file = wave.open(buffer, 'r')

but i'm getting a EOFError when i run it...

  File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/wave.py", line 493, in open
return Wave_read(f)
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/wave.py", line 163, in __init__
self.initfp(f)
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/wave.py", line 128, in initfp
self._file = Chunk(file, bigendian = 0)
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/chunk.py", line 63, in __init__
raise EOFError

i know the StringIO stuff works for creation of wav file and i tried the following and it works

import StringIO


buffer = StringIO.StringIO()
audio_out = wave.open(buffer, 'w')
audio_out.setframerate(m.getRate())
audio_out.setsampwidth(2)
audio_out.setcomptype('NONE', 'not compressed')
audio_out.setnchannels(1)

audio_out.writeframes(raw_audio)
audio_out.close()
buffer.flush()

# these lines do not work...
# buffer.output(wav_buffer)
# file = wave.open(buffer, 'r')

# this file plays out fine in VLC
file = open(FILE_NAME + ".wav", 'w')
file.write(buffer.getvalue())
file.close()
buffer.close()
like image 450
user368005 Avatar asked Oct 14 '22 04:10

user368005


2 Answers

try this:

import StringIO

buffer = StringIO.StringIO(wav_buffer)
file = wave.open(buffer, 'r')
like image 105
unbeli Avatar answered Nov 15 '22 05:11

unbeli


buffer = StringIO.StringIO()
buffer.output(wav_buffer)

A StringIO doesn't work like that. It's not a pipe that's connected to itself: when you read(), you don't receive data that you previously passed to write(). (Never mind output() which I'm guessing is a mispaste as there is no such method.)

Instead it acts as a separate read-pipe and write-pipe. The content that read() will return is passed in with the constructor:

buffer = StringIO.StringIO(wav_buffer)
file = wave.open(buffer, 'rb')

And any content collected from write() is readable through getvalue().

(I used binary read mode because this is what's happening, though the wave module will silently convert r mode to rb anyway.)

like image 20
bobince Avatar answered Nov 15 '22 04:11

bobince