Loading

python wave 库 读取 BytesIO 对象的注意事项

程序中遇到需要使用临时文件时,常使用内存中的 io.BytesIO() 代替实体二进制文件,以避免磁盘IO,同时免去了考虑文件名的麻烦。

file = io.BytesIO()
file.write(content)
content = file.getvalue()

如上所示,取值时通常使用 getvalue() 而不是 read(),若使用 read() 读取数据,需要先 file.seek(0) 使指针回到起点。

wave 模块默认是同时支持 文件路径 和 BytesIO 对象的,但当输入是 BytesIO 时,wave 并没有自动先 seek(0),故

使用 wave.open(wav_file, 'rb') 之前,需要先 seek(0):

if isinstence(wav_file, io.BytesIO):
    wav_file.seek(0)
with wave.open(wav_file, 'rb') as wf:
    ......
    ......
posted @ 2018-10-28 04:38  dylanchu  阅读(1047)  评论(0编辑  收藏  举报