C#调用Google语音转文字API实现短FLAC文件德语转录时程序挂起求助
Google Cloud Speech to Text 德语音频同步转录无响应问题
问题描述
我正尝试使用代码对时长不足60秒的短音频执行同步德语转录,在Program.cs文件所在的正确目录下运行dotnet run命令时,程序直接挂起无响应。
此前我使用测试文件brooklyn.flac运行英语转录功能完全正常,本次我希望对时长稍长的德语音频执行同类操作,暂不清楚问题根源。我曾遇到存储桶目录权限问题,目前已修复完毕,现在运行dotnet run不会抛出任何警告,但没有任何输出。我认为不需要等待极长时间让Google Cloud处理该短音频,怀疑是自身操作有误,恳请大家帮忙排查问题。
原始问题代码
using Google.Cloud.Speech.V1; using System; namespace SpeechToTextApiDemo { public class Program { public static void Main(string[] args) { var speech = SpeechClient.Create(); var config = new RecognitionConfig { Encoding = RecognitionConfig.Types.AudioEncoding.Flac, SampleRateHertz = 16000, LanguageCode = LanguageCodes.English.UnitedStates }; var audio = RecognitionAudio.FromStorageUri("gs://cloud-samples-tests/speech/brooklyn.flac"); var response = speech.Recognize(config, audio); foreach (var result in response.Results) { foreach (var alternative in result.Alternatives) { Console.WriteLine(alternative.Transcript); } } } } }
问题根因及修复方案
发布该问题后,经确认上述C#代码本身逻辑正常,故障由参数配置不匹配导致:
- 采样率配置错误:我自行从MP4中提取转换得到的Flac音频实际采样率为44100,而非代码中沿用的示例值16000,需将
SampleRateHertz字段值修改为实际采样率44100 - 缺少声道数配置:转换得到的Flac音频为双声道,对应2位说话人,需要在
RecognitionConfig中新增AudioChannelCount = 2配置项,否则接口无法正确识别音频流 - 语言编码配置错误:原代码使用的是英语美国的语言编码,需替换为对应德语编码,例如
LanguageCodes.German.Germany
修正后可运行代码示例
using Google.Cloud.Speech.V1; using System; namespace SpeechToTextApiDemo { public class Program { public static void Main(string[] args) { var speech = SpeechClient.Create(); var config = new RecognitionConfig { Encoding = RecognitionConfig.Types.AudioEncoding.Flac, SampleRateHertz = 44100, LanguageCode = LanguageCodes.German.Germany, AudioChannelCount = 2 }; // 替换为你的德语音频对应的Google Cloud存储桶地址 var audio = RecognitionAudio.FromStorageUri("gs://<你的存储桶路径>/目标德语音频.flac"); var response = speech.Recognize(config, audio); foreach (var result in response.Results) { foreach (var alternative in result.Alternatives) { Console.WriteLine(alternative.Transcript); } } } } }
内容的提问来源于stack exchange,提问作者Gary Lebowitz
相关产品推荐
相关产品推荐

