I created this program to record and save a sound.wav file. When I play the recording using sd.play() method it plays completely fine but when I go to the file path and then play it with Windows Media Player or VLC, it comes out to be completely silent. Please somebody help me with this.
import wave
import sounddevice as sd
fs = 44100
obj = wave.open('sound.wav', 'w')
obj.setnchannels(1) # mono
obj.setsampwidth(2)
obj.setframerate(fs)
sd.default.samplerate = fs
sd.default.channels = 2
interval = 10
myrecording = sd.rec(int(interval * fs))
obj.writeframesraw(myrecording)
sd.wait()
sd.play(myrecording, fs)
sd.wait()
And also why does the file comes out to be of 40 seconds when the time interval given by me is 10 seconds?
I guess the issue is that the WAV header (metadata) is not properly set. The header information of the WAV file does not match the actual audio data when played with media players like Windows Media Player or VLC. You can try the following code:
import wave
import sounddevice as sd
fs = 44100
interval = 10
# Record the audio
myrecording = sd.rec(int(interval * fs), samplerate=fs, channels=1, blocking=True)
# Save the recording to a WAV file
with wave.open('sound.wav', 'wb') as obj:
obj.setnchannels(1)
obj.setsampwidth(2)
obj.setframerate(fs)
obj.writeframes(myrecording.tobytes())
# Play the recording
sd.play(myrecording, fs)
sd.wait()