python - 使用语音识别后的python无法删除音频文件
问题描述
这是我的语音到文本的测试代码,文本的语音工作唯一的问题是删除音频文件后
import os
from os import walk
import speech_recognition as sr
def remove_spaces(string) : # removes all spaces in a string
return string.replace(" ", "")
def search_name() : # search for any file in path
_, _, filenames = next(walk('C:\\audios\\'))
return filenames[0]
def remove_file(name) : # should look for the file and removes it
print(('C:\\audios\\' + name))
if os.path.isfile(('C:\\\audios\\' + name)) :
os.remove(('C:\\audios\\' + name))
print("success, file .waw removed!")
else :
print("File doesn't exists!")
def main() :
r = sr.Recognizer()
audio_name = search_name() #get the name of file
print("Filename of Audio:", audio_name)
with sr.AudioFile(f'C:\\audios\\{audio_name}') as source :
audio_text = r.listen(source)
text = r.recognize_google(audio_text, language='de-DE')
print('Converting audio transcripts into text ...')
code = remove_spaces(text)
print(code)
remove_file(audio_name)
return code
if __name__ == '__main__' :
main()
错误,在使用语音转文本后,我想删除“audio.waw”,但它说该文件仍在使用中
C:\Users\J-Roc\AppData\Local\Programs\Python\Python39\python.exe C:/speech_to_text.py
Filename of Audio: xyz.wav
Traceback (most recent call last):
File "C:\speech_to_text.py", line 43, in <module>
main()
File "C:\speech_to_text.py", line 38, in main
remove_file(audio_name)
File "C:\speech_to_text.py", line 20, in remove_file
os.remove(('C:\\audios\\' + name))
PermissionError: [WinError 32] The process cannot access the file because it is used by another process: 'C:\\audios\\xyz.wav'
Converting audio transcripts into text ...
5549355
C:\audios\xyz.wav
Process finished with exit code 1
解决方案
您正在文件上下文中删除文件。您应该在上下文完成后删除。在您的主要功能中:
with sr.AudioFile(f'C:\\audios\\{audio_name}') as source :
audio_text = r.listen(source)
text = r.recognize_google(audio_text, language='de-DE')
print('Converting audio transcripts into text ...')
code = remove_spaces(text)
print(code)
remove_file(audio_name) #Still inside the file context. Can't remove file.
remove_file(audio_name)
return code
还强烈建议使用 try-except。
推荐阅读
- datatables - JQuery 数据表:卡中不是全尺寸
- javascript - UnhandledPromiseRejectionWarning:TypeError:无法在客户端读取未定义的属性“通道”。
- reactjs - 将 Redux 与 useEffect Hook 混合使用
- php - Angular 9(使用 --proxy-config 运行)POST 返回 301,然后是 OPTIONS,然后 GET 没有 POST 正文发送到服务器
- django-forms - 在 Django 中为 Meta 类添加 modelForm 验证约束
- java - 使用相机意图捕获图像后,Android 应用程序崩溃
- angular - ngrxLet 是否替代了智能和愚蠢的组件风格?
- asp.net-mvc - 使用具有 datetimeoffset 的模型更新 Kendo 网格中的行时出错
- c - 加法输入错误
- c# - 如何遍历 Outlook 的提醒?