简体   繁体   English

如何将16位PCM数据转换为python中的float?

[英]How to convert 16 bit PCM data into float in python?

I'm new to python and Raspberry pi. 我是python和Raspberry pi的新手。 I'm involved in a project, where I have to embed a bit stream to a wav file. 我参与了一个项目,在该项目中,我必须将一点流嵌入到wav文件中。 At first I opened the wav file and it is a 2 channel, 16 bit wav file. 首先,我打开了wav文件,它是一个2通道16位wav文件。 In order to change the sample values I should convert these sample values into float. 为了更改样本值,我应该将这些样本值转换为float。 I tried a code. 我尝试了一个代码。 But when I run the module, it gives errors as "name struct" isn't defined. 但是,当我运行模块时,由于未定义“名称结构”,因此会出现错误。 And also here I have tried to convert data into integers, since i don't know how to convert into float.If someone can help me to correct this program or suggest another code, then it will be a great help. 另外在这里我尝试将数据转换为整数,因为我不知道如何转换为float。如果有人可以帮助我更正此程序或建议其他代码,那将是很大的帮助。 Thank you. 谢谢。

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)

As @jonrsharpe said, you either : 正如@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)

But do not mix & match the imports together. 但是不要将进口混在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM