Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python正确解码.wav_Python_Audio_Int_Byte_Wave - Fatal编程技术网

如何使用Python正确解码.wav

如何使用Python正确解码.wav,python,audio,int,byte,wave,Python,Audio,Int,Byte,Wave,我正在编写波形音频文件的基本频率分析,但在从波形帧转换为整数时遇到了麻烦 以下是我的代码的相关部分: import wave track = wave.open('/some_path/my_audio.wav', 'r') byt_depth = track.getsampwidth() #Byte depth of the file in BYTES frame_rate = track.getframerate() buf_size = 512 def byt_sum (word):

我正在编写波形音频文件的基本频率分析,但在从波形帧转换为整数时遇到了麻烦

以下是我的代码的相关部分:

import wave
track = wave.open('/some_path/my_audio.wav', 'r')

byt_depth = track.getsampwidth() #Byte depth of the file in BYTES
frame_rate = track.getframerate()
buf_size = 512

def byt_sum (word):
#convert a string of n bytes into an int in [0;8**n-1]
    return sum( (256**k)*word[k] for k in range(len(word)) )

raw_buf = track.readframes(buf_size)
'''
One frame is a string of n bytes, where n = byt_depth.
For instance, with a 24bits-encoded file, track.readframe(1) could be:
b'\xff\xfe\xfe'.
raw_buf[n] returns an int in [0;255]
'''

sample_buf = [byt_sum(raw_buf[byt_depth*k:byt_depth*(k+1)])
              - 2**(8*byt_depth-1) for k in range(buf_size)]
问题是:当我为单个正弦信号绘制
sample\u buf
时,我得到 . 我搞不懂为什么信号和udpside重叠

有什么想法吗


旁白:因为我是法国人,所以我的英语很犹豫。如果有严重错误,请随意编辑。

这可能是因为需要使用无符号值来表示16位样本。看

尝试将32767添加到每个样本中

您还应该使用python对缓冲区进行解码

import struct
buff_size = 512
# 'H' is for unsigned 16 bit integer, try 'h' also
sample_buff = struct.unpack('H'*buf_size, raw_buf)

最简单的方法是使用一个为您解码的库。有可用的,我最喜欢的是模块:


嗯,它确实适用于16位编码的音频,但在理想情况下,这个脚本应该适用于任意字节深度。(我不熟悉
struct
模块,如何替换24位int的
h
)。无论如何谢谢你@S_错误:要了解它(如果您还没有),只需导入struct并在解释器中请求帮助(struct)。支持除24位以外的所有深度,即sampwidth=3。但这不是问题,你把它解压成32位。用额外的零('\x00')填充样本,并通过移位8位从struct.unpack()打包后的整数中删除零。您使用什么资源生成损坏信号的图形?
import soundfile as sf
signal, samplerate = sf.read('/some_path/my_audio.wav')