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

如何将Google Cloud Speech-to-Text API转录结果中的纳秒转成秒?

解决Google Cloud Speech-to-Text时间戳纳秒转秒的问题

Google Cloud Speech-to-Text API返回的时间戳本质是包含seconds和nanos字段的Duration对象,直接打印response时会显示完整的纳秒结构,这是API的默认返回格式,和是否开启enable_word_time_offsets无关。其他人显示的秒数是对返回的Duration对象做了转换处理后的结果,你可以通过以下方式实现:

转换时间戳为秒数的代码示例

替换你代码中print(response)的部分,改为遍历结果并转换时间格式:

for result in response.results:
    alternative = result.alternatives[0]
    print(f"转录文本: {alternative.transcript}")
    print("词级时间戳(秒):")
    for word_info in alternative.words:
        word = word_info.word
        # 把秒和纳秒合并为总秒数,保留3位小数
        start_sec = word_info.start_time.seconds + word_info.start_time.nanos / 1e9
        end_sec = word_info.end_time.seconds + word_info.end_time.nanos / 1e9
        print(f"  '{word}' 开始时间: {start_sec:.3f}s, 结束时间: {end_sec:.3f}s")

关键说明

  • API返回的start_time和end_time都是google.protobuf.Duration类型,包含两个属性:seconds(整数秒)和nanos(0-999999999的纳秒数)
  • 通过seconds + nanos/1e9可以将其转换为以秒为单位的浮点数,方便读取和使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 20:15:33