私はPythonでmini-JARVISのようなことに取り組んできました。私は多くの進歩を遂げました。私のコードを実行すると、AIの音声をmp3ファイルに保存し、pygameを使ってそのmp3を再生します。しかし、mp3ファイルを削除しようとすると、「プロセスが別のプロセスで使用されているためファイルにアクセスできません」というメッセージが表示されます。もっと私を混乱させるのは、この.pyを使ってmp3を実際に作成し、同じものを使って削除しようとしているのですが、別のプロセスで使用されていると言います。タスクマネージャを使用しても、実行中のPythonファイルがないことを確認しても、別のプロセスで使用されていると表示され、コンピュータを再起動するとどちらも機能しないため、ファイルを削除する方法はありますか?私は助けを使うことができました、ありがとう。ここに私のコードです。Pythonで使用されているmp3ファイルを閉じるには?
#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()
最後の2行は、基本的なAIとユーザーが実際に動作するかどうかを確認するためのものです。エラーは、おそらく推測したように、 "os.remove()"のspeech_output関数で発生します。
を参照してください、最後に音を待つために
ようなものが必要。 'time.sleep()'を使って音楽ファイルの長さを過ぎても、 'os.remove()'は別のプロセスがファイルを使用していることを示すPermissionErrorを送出します。それはファイルがまだミキサーにロードされているからです。別のファイルを読み込むとすぐ、前のファイルを削除することができます。 – Reti43