I am trying to create a new file recording every time this program runs and also convert those .wav files to .mp3. When I run this, it only creates a output.wav
and output0.mp3
file and then when I run it again, no further files are created. Also the output0.mp3
that was converted is 0KB and cannot be played.
I do not get an error but it seems its not grabbing the output.wav
properly that was originally created. I am running Python 3.7.
import os
import sounddevice as sd
from scipy.io.wavfile import write
from pydub import AudioSegment #for converting WAV to MP3
fs = 44100 # Sample rate
seconds = 3 # Duration of recording
myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2)
sd.wait() # Wait until recording is finished
write('output.wav', fs, myrecording ) # Save as WAV file
#Increments file name by 1 so it writes a new file every time it runs
i = 0
while os.path.exists("output%s.wav" % i):
i += 1
# files for converting WAV to Mp3
src = ("output%s.wav" % i)
dst = ("output%s.mp3" % i)
# convert wav to mp3
sound = AudioSegment.from_mp3(src)
sound.export(dst, format="wav")
writefile = open("output%s.mp3" % i, "w")
EDIT:
Updated while
loop to:
#Increments file name by 1 so it writes a new file every time it runs
i = 0
while os.path.exists("output%s.wav" % i):
# files for converting WAV to Mp3
src = ("output%s.wav" % i)
dst = ("output%s.mp3" % i)
# convert wav to mp3
sound = AudioSegment.from_mp3(src)
sound.export(dst, format="wav")
write("output%s.mp3" % i, "w")
i += 1