如何在Windows上用pygame多次编写和播放同一个.mp3文件?

2024-09-28 21:45:06 发布

您现在位置:Python中文网/ 问答频道 /正文

在Linux上,以下示例运行良好:

import pygame
from gtts import gTTS

pygame.mixer.init()

t = 'temp.mp3'
for i in range(5):
    gTTS(str(i)).save(t)
    pygame.mixer.music.load(t)
    pygame.mixer.munic.play()

这将播放数字0-4。在

在Windows上,相同的代码将导致错误:

^{pr2}$

i==1时。也就是说,它在第二个循环中崩溃。崩溃位于gTTS.save内:

with open(savefile, 'wb') as f: 
    self.write_to_fp(f)

作为一种解决办法,我还尝试了:

with tempfile.TemporaryFile() as t:
    gTTS(str(i)).save(t)
    pygame.mixer.music.load(t)
    pygame.mixer.munic.play()

但得到了错误

error: Couldn't read from RWops     

值得注意的是,这是一个每次都失败的最小示例。在我的完整代码中,我通常很少编写和播放,这是成功的,我可以在同一个脚本中多次从temp.py中播放。只有当我尝试多次背靠背写入和读取时,才会出现此问题。在


Tags: 代码fromimport示例playsave错误music