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

ASP.NET 5.0应用Debug模式语音正常 发布后无声音如何解决?

问题根本原因

你本地调试时ASP.NET进程运行在你的本地设备上,调用Azure语音SDK的SpeakTextAsync方法会直接调用本地音频输出设备播放声音,所以你能听到语音。发布到Azure服务器后,代码运行在Azure的远程服务器上,语音会在服务器侧播放,用户的浏览器无法接收到音频流,因此没有声音。你观察到的URL末尾出现?handler=button是表单提交后页面刷新的正常Razor Pages路由行为,和无声音故障无关。

修复方案
  • 调整服务端代码,取消服务端直接播放逻辑,改为合成语音后返回音频字节流给前端
    修改SynthesizeAudioAsync方法如下:
public static async Task<byte[]> SynthesizeAudioAsync()
{
    var config = SpeechConfig.FromSubscription("你的语音服务密钥", "westeurope");
    // 配置输出为通用MP3格式
    config.SetSpeechSynthesisOutputFormat(SpeechSynthesisOutputFormat.Audio16Khz32KBitRateMonoMp3);
    // 传入null作为音频配置,不绑定服务端音频设备
    using var synthesizer = new SpeechSynthesizer(config, null);
    var result = await synthesizer.SpeakTextAsync("Hello, I'm Aria, can you hear me ?");
    if (result.Reason == ResultReason.SynthesizingAudioCompleted)
    {
        return result.AudioData;
    }
    // 可自行添加错误处理逻辑
    return Array.Empty<byte>();
}

修改OnPost方法返回音频文件:

public async Task<IActionResult> OnPost()
{
    var audioBytes = await SynthesizeAudioAsync();
    return File(audioBytes, "audio/mpeg");
}
  • 调整前端逻辑,取消表单提交刷新页面的方式,改为AJAX请求获取音频后在浏览器侧播放
    首先在cshtml页面添加防伪标记,替换原有表单代码:
@Html.AntiForgeryToken()
<div>
    <button id="speakBtn" class="btn btn-default">CLICK ME</button>
</div>

@section Scripts {
<script>
document.getElementById('speakBtn').addEventListener('click', async () => {
    try {
        // 请求服务端获取音频流
        const response = await fetch('?handler=button', {
            method: 'POST',
            headers: {
                'RequestVerificationToken': document.querySelector('input[name="__RequestVerificationToken"]').value
            }
        });
        // 转换为Blob并播放
        const audioBlob = await response.blob();
        const audioUrl = URL.createObjectURL(audioBlob);
        const audio = new Audio(audioUrl);
        await audio.play();
        // 释放资源
        URL.revokeObjectURL(audioUrl);
    } catch (err) {
        console.error('音频播放失败:', err);
    }
});
</script>
}
  • Azure侧无需特殊调整,仅需确认你的Azure App Service网络可以正常访问对应区域的Azure语音服务即可。

内容的提问来源于stack exchange,提问作者Noémie Tapie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 20:24:02