Pygame mixer.music.load() 不适用于 gTT

Pygame mixer.music.load() does not work with gTTs

我正在尝试仅使用 pygame.mixer.music.load() 播放 gTTs 语音。我不想将语音保存到文件中,所以我将其保存到 BytesIO 流中。 gTTs returns .mp3 音频我知道 pygame 的支持有限,所以我尝试使用 .mp3 音频转换为 .wav =20=] 模块,但我找不到不将其保存到文件的方法。我怎样才能以任何可能的方式解决这个问题?

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)

pygame.mixer.music.load()返回的错误:pygame.error: ModPlug_Load failed

我通过使用 pydub 将音频转换为 wav 格式解决了这个问题:

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