gpt4 book ai didi

python - 如何关闭 Python 正在使用的 mp3 文件?

转载 作者:行者123 更新时间:2023-11-28 17:16:05 25 4
gpt4 key购买 nike

所以我一直在用 python 开发类似 JARVIS 的东西,并且取得了很大的进步。发生的事情是,当我运行我的代码时,它首先将 AI 语音存储到一个 mp3 文件中,然后使用 pygame 播放该 mp3。但是,当我尝试删除 mp3 文件时,它说“该进程无法访问该文件,因为它正被另一个进程使用”,然后是文件名。更让我困惑的是,我用这个 .py 来实际制作 mp3,我用同一个文件试图删除它,但它说它正在被另一个进程使用?我将如何删除这些文件,因为即使在使用任务管理器并确保没有运行 python 文件之后,它仍然说它被另一个进程使用,并且重新启动计算机也不起作用。我需要任何帮助,谢谢。这是我的代码。

#google text to speech, for putting into mp3
from gtts import gTTS
#actual speech recognition library
import speech_recognition as speech_recog
#to play the mp3
from pygame import mixer
#to get the time and the date
import time
#to print the calendar
import calendar
#to delete the file after it has been played
import os

#make the computer talk
def speech_output(ai_string):
tts = gTTS(text=ai_string, lang='en-us')
comp_string = str('compspeech.mp3')
tts.save(comp_string)

mixer.init()
mixer.music.load(comp_string)
mixer.music.play()
print('AI Speech:', ai_string)
os.remove('compspeech.mp3')

#get user's speech
def speech_input():
r = speech_recog.Recognizer()
with speech_recog.Microphone() as source:
print('You may speak after AI has talked ')
user_speech = r.listen(source)

try:
print("Sphinx thinks you said: " + r.recognize_sphinx(user_speech))
except sr.UnknownValueError:
print("Sphinx could not understand audio")
except sr.RequestError as e:
print("Sphinx error - {0}".format(e))

#start testing for what user said
if user_speech == 'what is the time' or user_speech == 'what is the date':
time(user_speech)
elif user_speech == 'show me a calendar':
show_calendar()
else:
speech_output('No action found for that statement, sorry about that.')

#get the date and the time
def date_time():
current_date_time = time.asctime()
speech_output(current_date_time)

#display the calendar
def show_calendar():
speech_output('Please enter the year for the calendar you want to see')
year = int(input('Type year here: '))
print(calendar.calendar(year, 2, 1, 10))

speech_output('Hi')
speech_input()

最后两行只是执行基本的 AI 和用户对话以确保它们确实有效。正如您可能猜到的那样,错误发生在 speech_output 函数中的“os.remove()”上。

最佳答案

mixer.music.play() 开始在后台播放,因此当您尝试删除文件时它仍在播放。您需要等待声音结束,例如

mixer.init()
mixer.music.load(comp_string)
mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
os.remove(mp3file)

详见how play mp3 with pygame

关于python - 如何关闭 Python 正在使用的 mp3 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44115080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com