我不确定为什么,但是它只是偶尔查找,转换和转录目录中的所有mp3文件,但从来没有100%的时间。我不知道为什么。我希望我在正确的地方提出要求。我的目标是找到所有m4a文件,然后转换为WAV文件,然后找到所有WAV文件并转录它们。该程序有时会执行此操作,但并非总是如此。
#!/usr/bin/env python3
import speech_recognition as sr
import time
import subprocess
import os
from os import path
from os import listdir
# find and convert mp3 files to wav files
# find all files with an extension, convert to wav files, transcribe to text file then transfer all wav files and mp3 files to finished directory and email transcribed files.
# find files with mp3 extension
def list_files1(directory, extension):
ext = []
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith(extension):
ext.append(file)
print(ext)
return ext
# get directory path
originalDir = os.getcwd()
# call function to find files with mp3 extension
mp3files = list_files1(originalDir, "m4a")
# os.chdir("/Users/williamjohnson/Dropbox/goodscrapers/publimaison2/")
# convert all mp3 files to wav files
for x in mp3files:
print(x)
timestr = time.strftime("%Y%m%d-%H%M%S")
command = "ffmpeg -i " + x + ' ' + timestr + ".wav"
print(command)
subprocess.call(command, shell=True)
# find all converted wav files
wavfiles = list_files1(originalDir, "wav")
for y in wavfiles:
print(y)
# obtain path to "english.wav" in the same folder as this script
AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), y)
# AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), "french.aiff")
# AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), "chinese.flac")
# use the audio file as the audio source
r = sr.Recognizer()
with sr.AudioFile(AUDIO_FILE) as source:
audio = r.record(source) # read the entire audio file
# recognize speech using Sphinx
try:
print("Sphinx thinks you said " + r.recognize_sphinx(audio))
timestr = time.strftime("%Y%m%d-%H%M%S")
text_file = open(timestr + ".txt", "a")
text_file.write(r.recognize_sphinx(audio))
text_file.close()
except sr.UnknownValueError:
print("Sphinx could not understand audio")
except sr.RequestError as e:
print("Sphinx error; {0}".format(e))
编辑:这是我犯的一个非常愚蠢的错误,我用相同的名称命名所有输出的文本文件,因此它们被覆盖了,因此我确保将名称改为毫秒,以使其具有唯一性然后在文件名中添加一个随机数以达到良好的效果。
答案 0 :(得分:0)
使用os.walk()
时,它将返回文件,不包含任何目录,因此您正在收集文件列表,但会丢弃其目录名。
您的包装器似乎未在os.walk()
上添加任何值;无论如何,我都会重构一次转换一个文件。相切地,如果您不太在意当前目录的绝对路径,则也不需要调用getcwd
。
import os
def get_next_file(directory, extension):
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith(extension):
yield os.path.join(root, file)
for x in get_next_file('.', 'm4a'):
print(x)