Search code examples
pythonfileaudiopathmp3

Save audio file to desired path


I have a lot of text-to-speech audio files that I need to save but often, the files get lost. Currently I'm using

    import gtts
    from playsound import playsound
   
    def say(speech):
        tts = gtts.gTTS(speech)
        tts.save("audio.mp3")
        playsound("audio.mp3")

Is there any way that I can save the mp3 to wherever I desire?


Solution

  • You can just paste content of new audio file into another file like below:

    import gtts
    from playsound import playsound
    
    def say(speech):
        tts = gtts.gTTS(speech)
        tts.save("audio.mp3")
        playsound("audio.mp3")
    
        # PLACE CONTENT INTO NEW FILE => S T A R T
        main_file =  open("audio.mp3", "rb").read()
        dest_file = open('path/to_your/file_name.mp3', 'wb+')
        dest_file.write(main_file)
        dest_file.close()
        # PLACE CONTENT INTO NEW FILE => E N D
    

    or

    import gtts
    from playsound import playsound
    import shutil
    
    def say(speech):
        tts = gtts.gTTS(speech)
        tts.save("audio.mp3")
        playsound("audio.mp3")
    
        # PLACE CONTENT INTO NEW FILE => S T A R T
        shutil.move("audio.mp3", "path/to_your/file_name.mp3")
        # PLACE CONTENT INTO NEW FILE => E N D