python`wave`:AttributeError:'NoneType'对象在Python中没有属性'write'

问题描述 投票:-1回答:1

我在运行以下代码时遇到麻烦:

import numpy as np
import wave
import struct

amplitude = 30000
frequency = 100
duration = 3
fs = 44100
num_samples = duration * fs

num_channels = 1
sampwidth = 2
num_frames = num_samples
comptype = "NONE"
compname = "not compressed"

t = np.linspace(0, duration, num_samples, endpoint = False)
x = amplitude * np.cos(2*np.pi * frequency * t )

wav_file = wave.open("One_Life.wav",'w')
wav_file.setparams((num_channels, sampwidth,fs,num_frames,comptype,compname))
for s in x:
  wav_file.writeframes(struct.pack('h',int(s)))

  wav_file.close()

我遇到的错误如下:

AttributeError: 'NoneType' object has no attribute 'write'

我无法弄清楚这一点,您能帮我吗?

python
1个回答
1
投票

wav_file.close()移出循环

for s in x:
    wav_file.writeframes(struct.pack('h',int(s)))

wav_file.close()

writeframes()内部具有_file.write,但是您正在关闭文件,将其设置为None。来自wave.py

def writeframes(self, data):
    self.writeframesraw(data)
    #...

def writeframesraw(self, data):
    #...
    self._file.write(data)
    #...

def close(self):
    self._file = None
    #...
© www.soinside.com 2019 - 2024. All rights reserved.