python - python wave模块可以接受StringIO对象吗

标签 python audio wave

我正在尝试使用 wave在 python 中读取 wav 文件的模块。

我的应用程序的不典型之处在于我不是使用文件或文件名来读取 wav 文件,而是将 wav 文件放在缓冲区中。

这就是我正在做的

import StringIO

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

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

但是当我运行它时我得到了一个EOFError...

  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

我知道 StringIO 的东西可以用于创建 wav 文件,我尝试了以下方法并且它有效

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()

最佳答案

试试这个:

import StringIO

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

关于python - python wave模块可以接受StringIO对象吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3051747/

相关文章:

python - 如何选择数据框的一部分并将其转换为 pandas 中的数组?

c++ - 用 FFMPEG 解码 pcm_s16le?

python - 如何从内存中播放 Wav 声音样本

python - NLTK 中具有非对称填充的 Ngram

python - PyVISA 超时错误——通过 RS232 (USB) 与 Agilent 34970A 通信

python - Flask + Gunicorn + Nginx + Supervisor 非默认端口号

c# - 使用 C# 直接从硬件获取声音

java - java中的wav振幅(立体声或更多 channel )

python - 使用 scipy 构建 wav 文件并将其写入磁盘

c# - 16 位 11025 单声道 WAVE 数据中的一个样本值