语音转文本的pyhton程序
时间: 2024-04-11 12:06:59 浏览: 160
以下是一个简单的Python程序,可以将音频文件中的语音转换为文本:
1. 首先,需要安装SpeechRecognition模块。可以使用pip命令来安装。在命令行中输入以下命令:
`pip install SpeechRecognition`
2. 导入SpeechRecognition模块和AudioFile模块
```python
import speech_recognition as sr
from pydub import AudioSegment
from pydub.silence import split_on_silence
```
3. 定义一个函数,将音频文件分割为小段,以便于识别。这里使用了pydub库中的split_on_silence函数,将音频文件根据静音部分分割成多个小段。
```python
def get_large_audio_transcription(path):
r = sr.Recognizer()
sound = AudioSegment.from_wav(path)
chunks = split_on_silence(sound,
min_silence_len=500,
silence_thresh=sound.dBFS-14,
keep_silence=500,
)
folder_name = "audio-chunks"
if not os.path.isdir(folder_name):
os.mkdir(folder_name)
whole_text = ""
for i, audio_chunk in enumerate(chunks, start=1):
chunk_filename = os.path.join(folder_name, f"chunk{i}.wav")
audio_chunk.export(chunk_filename, format="wav")
with sr.AudioFile(chunk_filename) as source:
audio_listened = r.record(source)
try:
text = r.recognize_google(audio_listened)
except sr.UnknownValueError as e:
print("Error:", str(e))
else:
text = f"{text.capitalize()}. "
print(chunk_filename, ":", text)
whole_text += text
return whole_text
```
4. 调用该函数并传入音频文件的路径,即可将音频转换为文本。
```python
path = "path/to/audio_file.wav"
print("\nFull text:", get_large_audio_transcription(path))
```
完整代码示例:
```python
import os
import speech_recognition as sr
from pydub import AudioSegment
from pydub.silence import split_on_silence
def get_large_audio_transcription(path):
r = sr.Recognizer()
sound = AudioSegment.from_wav(path)
chunks = split_on_silence(sound,
min_silence_len=500,
silence_thresh=sound.dBFS-14,
keep_silence=500,
)
folder_name = "audio-chunks"
if not os.path.isdir(folder_name):
os.mkdir(folder_name)
whole_text = ""
for i, audio_chunk in enumerate(chunks, start=1):
chunk_filename = os.path.join(folder_name, f"chunk{i}.wav")
audio_chunk.export(chunk_filename, format="wav")
with sr.AudioFile(chunk_filename) as source:
audio_listened = r.record(source)
try:
text = r.recognize_google(audio_listened)
except sr.UnknownValueError as e:
print("Error:", str(e))
else:
text = f"{text.capitalize()}. "
print(chunk_filename, ":", text)
whole_text += text
return whole_text
path = "path/to/audio_file.wav"
print("\nFull text:", get_large_audio_transcription(path))
```
阅读全文