如何在Python中将16位PCM数据转换为浮点数?
我刚开始学习Python和树莓派,正在做一个项目,需要把一些比特流嵌入到一个wav文件里。最开始我打开了这个wav文件,发现它是一个双声道、16位的wav文件。为了修改这些采样值,我需要把它们转换成浮点数。我试过写代码,但运行的时候出现了错误,提示“name struct”没有定义。而且我还尝试把数据转换成整数,因为我不知道怎么把它转换成浮点数。如果有人能帮我修正这个程序或者推荐其他代码,那就太好了。谢谢!
from struct import unpack
import numpy as np
import wave
wavfile = wave.open('/home/pi/desktop/codes/mysong.wav','r')
number_of_frames = wavfile.getnframes()
no_channels = wavfile.getnchannels()
raw_data = wavfile.readframes(number_of_frames)
total_samples = number_of_frames * no_channels
fmt = "%ih" % total_samples
integer_data = struct.unpack(fmt,raw_data)
1 个回答
0
正如@jonrsharpe所说,你可以选择以下两种方式:
# if using from ... import ...
from struct import unpack
...
# then change this to
integer_data = unpack(fmt,raw_data)
...
# if using import ...
import struct
...
# then this will work fine
integer_data = struct.unpack(fmt,raw_data)
但是不要把不同的导入方式混在一起使用。