0

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?

1 Answer 1

2

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
    #...
Sign up to request clarification or add additional context in comments.

6 Comments

what do you mean ?
@Sheng What are you referring to?
@Sheng This is the source code, I added the relevant code to the question to show the process. You are using writeframes() which call writeframesraw() which use the variable self._file. When you call close() self._file is set to None.
So I need to find wave.py?
@Sheng No, all you need to do is move wav_file.close() outside the loop. See the first code block in my answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.