首页 > 解决方案 > 使用语音识别后的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

标签: pythonoperating-systemspeech-recognition

解决方案


您正在文件上下文中删除文件。您应该在上下文完成后删除。在您的主要功能中:

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。


推荐阅读