【问题标题】:Pygame mixer.music.load() does not work with gTTsPygame mixer.music.load() 不适用于 gTT
【发布时间】:2021-04-23 13:40:07
【问题描述】:

我正在尝试仅使用 pygame.mixer.music.load() 播放 gTTs 语音。我不想将语音保存到文件中,所以我将其保存到BytesIO 流中。 gTTs 返回.mp3 音频,我知道pygame 对它的支持有限,所以我尝试使用pydub 模块将.mp3 音频转换为.wav,但我找不到办法所以无需将其保存到文件中。如何以任何可能的方式解决此问题?

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

【问题讨论】:

    标签: python pygame text-to-speech pydub gtts


    【解决方案1】:

    我通过使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-08
      • 2020-10-09
      • 1970-01-01
      • 1970-01-01
      • 2019-07-22
      • 2022-11-28
      • 2022-01-21
      • 1970-01-01
      相关资源
      最近更新 更多