问题描述
好,所以我一直在使用python尝试创建波形图像,并且正在使用song = wave.open()
和song.readframes(1)
从.wav
文件中获取原始数据,该返回的结果是:
Ok so I've been using python to try create a waveform image and I'm getting the raw data from the .wav
file using song = wave.open()
and song.readframes(1)
, which returns :
b'\x00\x00\x00\x00\x00\x00'
我想知道的是如何将其拆分为三个单独的字节,例如b'\x00\x00'
,b'\x00\x00'
,b'\x00\x00'
,因为每个帧的宽度为3个字节,所以我需要每个单独字节的值才能形成波形.我相信这就是我需要这样做的方式.
What I want to know is how I split this into three separate bytes, e.g. b'\x00\x00'
, b'\x00\x00'
, b'\x00\x00'
because each frame is 3 bytes wide so I need the value of each individual byte to be able to make a wave form. I believe that's how I need to do it anyway.
推荐答案
您可以在byte
对象上使用切片:
You can use slicing on byte
objects:
>>> value = b'\x00\x01\x00\x02\x00\x03'
>>> value[:2]
b'\x00\x01'
>>> value[2:4]
b'\x00\x02'
>>> value[-2:]
b'\x00\x03'
但是,在处理这些框架时,您可能还想了解 memoryview()
对象;这些使您可以将字节解释为C数据类型,而无需进行任何额外的工作,只需在基础字节上投射视图"即可:
When handling these frames, however, you probably also want to know about memoryview()
objects; these let you interpret the bytes as C datatypes without any extra work on your part, simply by casting a 'view' on the underlying bytes:
>>> mv = memoryview(value).cast('H')
>>> mv[0], mv[1], mv[2]
256, 512, 768
mv
对象现在是一个内存视图,将每2个字节解释为一个无符号的short;因此它现在的长度为3,并且每个索引都是基于基础字节的整数值.
The mv
object is now a memory view interpreting every 2 bytes as an unsigned short; so it now has length 3 and each index is an integer value, based on the underlying bytes.
这篇关于如何在python中将字节字符串拆分为单独的字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!