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

如何在Azure文本转语音合成音频中获取时间戳

Azure文本转语音获取单词级时间戳解决方案

调用request_word_level_timestamps()后,时间戳数据并非直接暴露在result.properties的表面,而是存储在特定属性键中,需要手动提取并解析。以下是修正后的实现步骤和代码:

关键要点

  • 时间戳以JSON字符串形式存储在speechsdk.PropertyId.SpeechServiceResponse_SynthesisWordTimestampsJson属性中
  • 必须先验证合成结果是否成功,否则无法获取有效数据
  • 时间戳单位为纳秒,可按需转换为毫秒(除以1e6)或秒(除以1e9)

修正后的代码

import json
import azure.cognitiveservices.speech as speechsdk

speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=service_region)
speech_config.speech_synthesis_voice_name = "en-US-AndrewMultilingualNeural"
# 请求单词级时间戳
speech_config.request_word_level_timestamps()

text = "Hi there, welcome to Azure Text to Speech service."

speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config)
result = speech_synthesizer.speak_text_async(text).get()

# 检查合成结果状态
if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:
    # 提取时间戳JSON数据
    timestamps_json = result.properties.get(
        speechsdk.PropertyId.SpeechServiceResponse_SynthesisWordTimestampsJson,
        None
    )
    if timestamps_json:
        timestamps_data = json.loads(timestamps_json)
        print("单词级时间戳信息:")
        for word_item in timestamps_data["Words"]:
            word = word_item["Word"]
            start_time_ms = word_item["Offset"] / 1000000  # 转换为毫秒
            duration_ms = word_item["Duration"] / 1000000
            print(f"单词: {word} | 开始时间: {start_time_ms:.2f}ms | 持续时间: {duration_ms:.2f}ms")
    else:
        print("未获取到时间戳数据,请检查语音配置或文本长度")
elif result.reason == speechsdk.ResultReason.Canceled:
    cancellation_details = result.cancellation_details
    print(f"合成任务取消:{cancellation_details.reason}")
    if cancellation_details.reason == speechsdk.CancellationReason.Error:
        print(f"错误详情:{cancellation_details.error_details}")

补充说明

  • 若使用极短文本(如单个单词"Hi"),服务可能返回的时间戳数据有限,建议用稍长的句子测试
  • 确保使用的语音模型支持时间戳功能,en-US-AndrewMultilingualNeural属于支持该功能的神经语音模型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 05:12:40