You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Azure Speech Translation API的Python代码无输出求助

代码问题分析与修复

你的代码存在几个关键逻辑和配置错误,导致无输出也无报错,以下是具体问题和修复方案:

1. Azure Speech服务Endpoint配置错误

你使用的ENDPOINT是STS令牌请求地址,这不是语音翻译服务的正确Endpoint。正确的做法是:

  • 优先使用region参数(更简洁),比如你的服务部署在northeurope,直接设置region="northeurope"
  • 或者使用语音服务的区域Endpoint:https://northeurope.api.cognitive.microsoft.com/

原代码的配置初始化需修改为:

translation_config = speechsdk.translation.SpeechTranslationConfig(
    subscription=API_KEY, region="northeurope")  # 用region替换错误的endpoint

2. 识别结果的错误处理缺失

  • 初始recognize_once()后,没有打印识别状态信息,无法排查是成功、失败还是取消
  • 循环逻辑混乱:循环开始时判断的是第一次识别的旧结果,而非每次循环新获取的结果;且未处理识别失败的情况,直接解析result.json会触发潜在报错(但因配置错误可能根本没走到这一步)

3. 循环逻辑顺序错误

while循环应先调用recognize_once()获取新结果,再判断结果状态,而非先判断旧结果。原逻辑会导致无限循环或提前退出。

4. 调试信息缺失

vars(result)不会自动打印输出,需添加print(vars(result))才能查看结果详情,方便排查问题。

修复后的完整代码

import json
import azure.cognitiveservices.speech as speechsdk

API_KEY = "2b0ddf64d03744d8aa77c0ca526ecc18"
REGION = "northeurope"  # 替换为你的服务区域

media_file_path = "/content/konec_Outlook.wav"

# 修复配置:使用region而非错误的endpoint
translation_config = speechsdk.translation.SpeechTranslationConfig(
    subscription=API_KEY, region=REGION) 
translation_config.speech_recognition_language = "en-GB"
translation_config.add_target_language("cs-CZ")

audio_config = speechsdk.audio.AudioConfig(filename=media_file_path)
recognizer = speechsdk.translation.TranslationRecognizer(
    translation_config=translation_config, audio_config=audio_config)

# 初始识别并打印调试信息
result = recognizer.recognize_once()
print("初始识别状态:", speechsdk.ResultReason(result.reason).name)
print("结果详情:", vars(result))

# 处理初始识别结果
if result.reason == speechsdk.ResultReason.TranslatedSpeech:
    source_language_text = result.text
    duration = result.duration // 10000000  # 转换为秒(duration单位是100纳秒)
    print("\n翻译结果(cs-CZ):", result.translations['cs-CZ'])

    translation_json = json.loads(result.json)
    print("识别状态:", translation_json['RecognitionStatus'])
    print("音频时长(100纳秒单位):", translation_json['Duration'])
    print("源文本:", translation_json['Text'])
    for translated in translation_json['Translation']['Translations']:
        print("目标语言:", translated['Language'])
        print("翻译文本:", translated['Text'])
        print()
elif result.reason == speechsdk.ResultReason.Canceled:
    cancellation_details = result.cancellation_details
    print("识别被取消:", cancellation_details.reason)
    if cancellation_details.reason == speechsdk.CancellationReason.Error:
        print("错误详情:", cancellation_details.error_details)

# 连续识别修复版
print("\n--- 连续识别开始 ---")
recognizer = speechsdk.translation.TranslationRecognizer(
    translation_config=translation_config, audio_config=audio_config)
outputs = []
toStop = False

while not toStop:
    result = recognizer.recognize_once()
    print("当前识别状态:", speechsdk.ResultReason(result.reason).name)
    
    if result.reason == speechsdk.ResultReason.TranslatedSpeech:
        translation_json = json.loads(result.json)
        for translated in translation_json['Translation']['Translations']:        
            print("目标语言:", translated['Language'])
            print("翻译文本:", translated['Text'])
            outputs.append({'language': translated['Language'],  'text': translated['Text']})
    elif result.reason == speechsdk.ResultReason.NoMatch:
        print("未识别到语音")
        toStop = True
    elif result.reason == speechsdk.ResultReason.Canceled:
        cancellation_details = result.cancellation_details
        print("识别被取消:", cancellation_details.reason)
        if cancellation_details.reason == speechsdk.CancellationReason.Error:
            print("错误详情:", cancellation_details.error_details)
        toStop = True

print("\n最终收集的翻译结果:", outputs)

额外排查点

  • 确认音频文件存在:在Colab中执行!ls /content查看文件列表
  • 确认音频格式合规:Azure Speech要求音频为16kHz采样率、16位深度、单声道PCM编码的WAV文件,格式不符会导致识别失败
  • 确认密钥与区域匹配:你的API密钥必须属于northeurope区域的语音服务,否则会触发权限错误

内容的提问来源于stack exchange,提问作者Adam Black

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 08:41:07