【问题标题】:struct.error: unpack requires a buffer of 48000 bytesstruct.error: unpack 需要 48000 字节的缓冲区
【发布时间】:2022-10-24 03:33:43
【问题描述】:

这是我得到的错误 struct.error: unpack 需要 48000 字节的缓冲区 无论如何我可以解决这个问题而不必改变我试图绘制这个的方式?

import wave
import struct
import matplotlib.pyplot as plt
import numpy as np

infile = "trumpet.wav"
wav_file = wave.open(infile, "r")
nchannels = wav_file.getnchannels()
nframes = wav_file.getnframes()
sampwidth = wav_file.getsampwidth()
data = wav_file.readframes(nframes)
wav_file.close()
dtype_map = {1: np.int8, 2: np.int16, 3: "special", 4: np.int32}
if sampwidth not in dtype_map:
    raise ValueError("sampwidth %d unknown" % sampwidth)
if sampwidth == 3:
    xs = np.fromstring(data, dtype=np.int8).astype(np.int32)
    ys = (xs[2::3] * 256 + xs[1::3]) * 256 + xs[0::3]
else:
    ys = np.frombuffer(data, dtype=dtype_map[sampwidth])
# if it's in stereo, just pull out the first channel
if nchannels == 2:
    ys = ys[::2]

#plot full signal
num_samples = 48000
data = struct.unpack('{n}h'.format(n=num_samples), data)
data = np.array(data)
plt.subplot(1,1,1)
plt.plot(data[:300])
plt.title('Entire signal')
plt.show()

【问题讨论】:

    标签: python struct


    【解决方案1】:

    没关系,我想通了。我需要让我的 num_samples 是数据长度的一半。

    frame_rate = 48000.0
    infile = "trumpet.wav"
    num_samples = 770246
    wav_file = wave.open(infile, 'r')
    data = wav_file.readframes(num_samples)
    wav_file.close()
    data = struct.unpack('{n}h'.format(n=num_samples), data)
    data = np.array(data)
    data = np.array(data)
    plt.subplot(1,1,1)
    plt.plot(data[:100000])
    plt.title('Entire signal')
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-06
      • 2020-10-24
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      • 2015-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多