Sheng
Sheng

Reputation: 13

python `wave`: AttributeError: 'NoneType' object has no attribute 'write' in Python

I'm having a trouble running the following code:

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()

The error I'm getting is as follow:

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

I'm unable to figure this one out, can you please help me?

Upvotes: 0

Views: 3146

Answers (1)

Guy
Guy

Reputation: 50899

Move wav_file.close() out of the loop

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

wav_file.close()

writeframes() has _file.write internally, but you are closing the file, setting it to None. From wave.py

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

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

def close(self):
    self._file = None
    #...

Upvotes: 2

Related Questions