I'm trying to play a gTTs voice with pygame.mixer.music.load()
only. I don't want to save the voice into a file, so I saved it into a BytesIO
stream. gTTs
returns .mp3
audio which I know has limited support by pygame
, so I tried to convert the .mp3
audio to .wav
using the pydub
module, but I couldn't find a way to do so without saving it to a file. How can I fix this issue in any way possible?
from pygame import mixer
from gtts import gTTS
def play(buffer):
buffer.seek(0)
mixer.music.load(buffer) #Load the mp3
print("Sound loaded. Time to play!")
mixer.music.play() #Play it
def generate_voice(text, accent):
mp3_fp = BytesIO()
tts = gTTS(text)
tts.write_to_fp(mp3_fp)
return mp3_fp
text = "Hi there"
buffer = generate_voice(text, accent)
play(buffer)
The error returned by pygame.mixer.music.load()
: pygame.error: ModPlug_Load failed
I fixed this issue by using pydub
to convert the audio into a wav
format:
def play(buffer):
mixer.init()
mixer.music.load(buffer) #Load the mp3
print("Sound loaded. Time to play!")
mixer.music.play() #Play it
def generate_voice(text, lang):
fp = BytesIO()
wav_fp = BytesIO()
tts = gTTS(text=text, lang=lang)
tts.write_to_fp(fp)
fp.seek(0)
sound = AudioSegment.from_file(fp)
wav_fp = sound.export(fp, format = "wav")
return wav_fp