Search code examples
python-3.xpydub

Unable to properly increment variable and convert to .wav to .mp3


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

Solution

  • SOLUTION: Updated my while loop and changed the conversion method

    i = 0
    
    while not os.path.exists("output.wav"):
        i += 1
        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{0}.wav'.format(i), fs, myrecording )  # Save as WAV file
        print("recording has finished")
    
        datadir = str(Path(r"FilePathtoFolderWhereAudioFileIs"))
        filetopen = datadir + "/" + 'output{0}.wav'.format(i)
    
        sound = pydub.AudioSegment.from_wav(r"FilePathtoFolderWhereAudioFileIs""" + "\\output{0}.wav".format(i))
        sound.export(r"FilePathtoFolderWhereAudioFileIs""" + "\\output{0}.mp3".format(i), format="mp3")
        print("Converted wav to mp3")
    
        time.sleep(3)