【问题标题】:Playsound only plays the mp3 file once and then gives the error "Permission Denied"Playsound 只播放一次 mp3 文件,然后给出错误“Permission Denied”
【发布时间】:2022-05-12 23:43:31
【问题描述】:

我在 Spyder IDE 中使用 Playsoundgtts 来创建 mp3 文件然后播放它。

import gtts
from playsound import playsound
#pass text to gTTS object 

# make request to google to get synthesis
english = gtts.gTTS("Hello world") #retrieved the actual audio speech from the API

# save the audio file
english.save("hello.mp3")
# play the audio file
playsound("hello.mp3")

第一次播放很好,但每次运行时都会显示:

  File "C:\Users\ASUS\.spyder-py3\all codes\Text2Speech.py", line 27, in <module>
    english.save("hello.mp3")

  File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\Lib\site-packages\gtts\tts.py", line 312, in save
    with open(str(savefile), 'wb') as f:

  PermissionError: [Errno 13] Permission denied: 'hello.mp3'

我重新启动 Spyder 后它再次正常工作,然后只玩一次后再次无法正常工作。我的操作系统是 Windows 10,Playsound 版本 1.2.2

【问题讨论】:

  • 很难说没有看到完整的回溯,但我的猜测是playsound 没有关闭文件句柄,所以english.save 下次失败。
  • 感谢您的反馈。我只是在回溯部分添加了更多行。如果因为playsound 没有关闭而发生这种情况,如何解决该问题?
  • 第一次运行代码时,您会得到 Error 263 for command: close hello.mp3 Device is not open or not recognized by MCI. Failed to close the file: hello.mp3 的输出,这表明 playsound 没有关闭文件。因此,下一次,GTTS 不能再写入它了。我个人的经验是playsound 不是一个成熟的库。它会做所有无法真正控制的外部事务。
  • 我也不推荐pydub,因为它需要安装FFMPEG的副本。我也不推荐Mpg123,因为它需要安装libmpg123。我之前用pygame没问题,但它不能播放GTTS的MP3文件。是的,用 Python 播放声音真的很糟糕。

标签: python python-3.x spyder gtts python-playsound


【解决方案1】:

我知道这个问题有点老了,但我会留在这里,以防其他人对此感到困惑。

我的代码也有类似的问题,我正在构建一个语音助手,它使用来自您的麦克风的输入,然后使用 gTTS 和 playsound 与您对话。它只能工作一次,然后在创建 mp3 文件后,不能再通过第二个语音命令再次使用它。

我找到的解决方案是在每次创建文件时给文件一个不同的名称(这在大多数情况下会造成混乱),或者在使用后删除文件。

这是我的“说话”功能的样子,它只是将文本以声音翻译成 mp3 文件然后播放。最后我添加了os.remove(file_path) file_path 是文件名本身或它的路径。

def speak(text):
    tts = gTTS(text=text, lang="en")
    filename = "voice.mp3"
    tts.save(filename)
    playsound.playsound(filename)
    os.remove("voice.mp3")

此解决方案仅在程序使用此特定 mp3 文件向您“说话”时才有效,因为它很少需要回到之前所说的内容,该文件是临时的,删除它不会做任何伤害。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多