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

请求Azure Speech to Text服务SDK调用本地音频转文本快速入门示例

Azure Speech to Text 音频转文本 Java 示例代码

前置准备

  • 已添加你提供的Maven依赖:
<dependency>
    <groupId>com.microsoft.cognitiveservices.speech</groupId>
    <artifactId>client-sdk</artifactId>
    <version>1.28.0</version>
</dependency>
  • 持有Azure Speech服务的密钥和区域标识(例如eastus)
  • 待转换的音频文件(推荐使用16kHz单声道WAV格式,也支持MP3等常见格式)

完整示例代码

import com.microsoft.cognitiveservices.speech.*;
import com.microsoft.cognitiveservices.speech.audio.AudioConfig;

import java.util.concurrent.ExecutionException;

public class SpeechToTextDemo {
    public static void main(String[] args) {
        // 替换为你的Speech服务密钥和区域
        String speechKey = "YOUR_SPEECH_SERVICE_KEY";
        String speechRegion = "YOUR_SERVICE_REGION";
        // 替换为你的本地音频文件路径
        String audioFilePath = "your/audio/file/path.wav";

        try {
            // 初始化语音服务配置
            SpeechConfig speechConfig = SpeechConfig.fromSubscription(speechKey, speechRegion);
            // 绑定待识别的音频文件
            AudioConfig audioConfig = AudioConfig.fromWavFileInput(audioFilePath);

            // 创建语音识别实例
            SpeechRecognizer recognizer = new SpeechRecognizer(speechConfig, audioConfig);

            System.out.println("正在处理音频识别...");

            // 执行单次识别(适合短音频场景)
            SpeechRecognitionResult result = recognizer.recognizeOnceAsync().get();

            // 处理识别结果
            switch (result.getReason()) {
                case ResultReason.RecognizedSpeech:
                    System.out.println("识别结果: " + result.getText());
                    break;
                case ResultReason.NoMatch:
                    System.out.println("未识别有效语音: " + NoMatchDetails.fromResult(result).getReason());
                    break;
                case ResultReason.Canceled:
                    CancellationDetails cancellation = CancellationDetails.fromResult(result);
                    System.out.println("识别任务被取消: " + cancellation.getReason());
                    if (cancellation.getReason() == CancellationReason.Error) {
                        System.out.println("错误详情: " + cancellation.getErrorDetails());
                    }
                    break;
            }

            // 释放资源
            recognizer.close();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

补充说明

  • 若处理长音频(超过15秒),建议使用StartContinuousRecognitionAsync()方法实现持续识别,避免单次识别的长度限制
  • 代码中已包含基础的错误和异常处理,可根据业务需求扩展逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 19:12:45