首页 > 解决方案 > 在python中将大型wav文件转换为文本

问题描述

我已经尝试使用此代码将我的大wav文件转换为文本

import speech_recognition as sr
r = sr.Recognizer()

hellow=sr.AudioFile('hello_world.wav')
with hellow as source:
    audio = r.record(source)
try:
    s = r.recognize_google(audio)
    print("Text: "+s)
except Exception as e:
    print("Exception: "+str(e))

但它并没有准确地转换它,我觉得它是“美国”口音的原因。请告诉我如何准确转换整个大wav文件。

标签: pythonspeech-recognitionspeech-to-text

解决方案


谷歌的语音转文本非常有效,试试下面的链接,

https://cloud.google.com/speech-to-text/

您可以选择语言(在您的情况下为美国英语)并上传文件。

就像@bigdataolddriver 评论的那样,100% 的准确率是不可能的,而且价值数百万。

Google 语音转文本具有三种类型的 API

同步、异步和流式传输,其中异步允许您进行约 480 分钟的音频转换,而其他只能让您约 1 分钟。以下是进行转换的示例代码。

filepath = "~/audio_wav/"     #Input audio file path
output_filepath = "~/Transcripts/" #Final transcript path
bucketname = "callsaudiofiles" #Name of the bucket created in the step before

# Import libraries
from pydub import AudioSegment
import io
import os
from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types
import wave
from google.cloud import storage

Speech to text 支持带有 LINEAR16 或 MULAW 编码音频的 wav 文件。

下面是用代码获取帧速率和通道的代码。

def frame_rate_channel(audio_file_name):
    with wave.open(audio_file_name, "rb") as wave_file:
        frame_rate = wave_file.getframerate()
        channels = wave_file.getnchannels()
        return frame_rate,channels

下面的代码是异步转换的。

def google_transcribe(audio_file_name):

    file_name = filepath + audio_file_name

    # The name of the audio file to transcribe

    frame_rate, channels = frame_rate_channel(file_name)

    if channels > 1:
        stereo_to_mono(file_name)

    bucket_name = bucketname
    source_file_name = filepath + audio_file_name
    destination_blob_name = audio_file_name

    upload_blob(bucket_name, source_file_name, destination_blob_name)

    gcs_uri = 'gs://' + bucketname + '/' + audio_file_name
    transcript = ''

    client = speech.SpeechClient()
    audio = types.RecognitionAudio(uri=gcs_uri)

    config = types.RecognitionConfig(
    encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
    sample_rate_hertz=frame_rate,
    language_code='en-US')

    # Detects speech in the audio file
    operation = client.long_running_recognize(config, audio)
    response = operation.result(timeout=10000)

    for result in response.results:
        transcript += result.alternatives[0].transcript

    delete_blob(bucket_name, destination_blob_name)
    return transcript

这就是您将它们写入文件的方式

def write_transcripts(transcript_filename,transcript):
    f= open(output_filepath + transcript_filename,"w+")
    f.write(transcript)
    f.close()

如果您需要任何进一步的说明,请告诉我。


推荐阅读