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

C#调用IBM Watson SpeechToText返回空响应及空引用异常求助

问题解决步骤
  • 补全Recognize方法的必填参数contentType,根据你的音频实际格式传入对应值,示例:如果是16k采样率的单声道wav文件,传入"audio/wav; rate=16000",如果是mp3传入"audio/mp3",该参数未指定时服务端无法解析音频会返回空结果。
  • 调用接口前重置内存流的读取位置,避免传入空内容:在调用Recognize前添加代码memStream.Position = 0;
  • 移除不必要的SSL验证关闭配置,官方Watson服务无需关闭SSL校验,该配置可能引发请求异常。
  • 先判断请求状态码再处理返回结果,同时打印错误信息排查问题,避免直接访问可能为空的属性抛出NullReferenceException。

修正后代码示例

IamAuthenticator authenticator = new IamAuthenticator(apikey: apikey);
SpeechToTextService speechToText = new SpeechToTextService(authenticator);
speechToText.SetServiceUrl(url);

// 重置流的读取位置
memStream.Position = 0;
// 补全contentType参数,替换为你实际使用的音频格式
var res = speechToText.Recognize(
    audio: memStream, 
    contentType: "audio/wav; rate=16000",
    inactivityTimeout: 180
);

if (res != null && res.StatusCode == 200)
{
    Console.WriteLine("Result: " + res.Result);
}
else
{
    Console.WriteLine("Status: " + res?.StatusCode);
    Console.WriteLine("Error: " + res?.Error);
}

异步调用优化

如果使用异步调用,不要直接用.Result获取结果,改用await避免阻塞和异常:

// 需放在标记为async的方法中
var res = await speechToText.RecognizeAsync(
    audio: memStream, 
    contentType: "audio/wav; rate=16000",
    inactivityTimeout: 180
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:36:07