我在运行以下代码时遇到问题:
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'
我无法弄清楚这个,你能帮我吗?
将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
#...