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

时间:2017-05-22 14:10:20

标签: python python-3.x artificial-intelligence mp3 speech-recognition

所以我在python中一直在研究mini-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和用户交谈以确保它们确实有效。正如您可能猜到的那样,在“os.remove()”上的speech_output函数中发生了错误。

1 个答案:

答案 0 :(得分:2)

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