Files
game-driver/pkg/audio/play.go
mapleafgo 2331d0c73f
All checks were successful
ci/woodpecker/tag/woodpecker Pipeline was successful
fix(tts): 修复 TTS 播放卡死问题并增强日志
- 添加 SoundWithContext 方法,使用请求 context 而非全局 context
- 修复 TTS 使用服务器全局 context 导致无法取消的问题
- 添加详细的诊断日志(解码、播放、TTS 合成各阶段)
- 检测并记录 TTS 合成数据为空的情况

修复前 TTS 播放使用全局 context,当播放卡住时无法通过超时
或取消机制中断,导致后续任务永远无法执行。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-08 12:07:39 +08:00

91 lines
1.8 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package audio
import (
"context"
"github.com/gopxl/beep/v2"
"github.com/gopxl/beep/v2/mp3"
"github.com/gopxl/beep/v2/speaker"
"github.com/gopxl/beep/v2/wav"
"go.uber.org/zap"
"io"
"time"
)
var DefaultSampleRate = beep.SampleRate(44100)
func init() {
err := speaker.Init(DefaultSampleRate, DefaultSampleRate.N(time.Second/10))
if err != nil {
panic("扬声器初始化异常: " + err.Error())
}
zap.S().Infoln("扬声器初始化完成")
}
func PlayWav(c context.Context, r io.Reader) {
zap.S().Debugln("开始 WAV 解码")
streamer, format, err := wav.Decode(r)
if err != nil {
zap.S().Errorln("WAV解码失败: ", err)
return
}
defer streamer.Close()
zap.S().Debugln("WAV解码成功采样率:", format.SampleRate)
s := beep.Resample(4, format.SampleRate, DefaultSampleRate, streamer)
ctrl := &beep.Ctrl{Streamer: s}
done := make(chan struct{})
speaker.Play(beep.Seq(ctrl, beep.Callback(func() {
zap.S().Debugln("音频播放完成")
close(done)
})))
zap.S().Debugln("等待音频播放完成...")
for {
select {
case <-done:
zap.S().Infoln("音频播放正常结束")
return
case <-c.Done():
{
zap.S().Infoln("音频播放被 context 取消")
speaker.Lock()
ctrl.Streamer = nil
speaker.Unlock()
return
}
}
}
}
func PlayMP3(c context.Context, r io.ReadCloser) {
streamer, format, err := mp3.Decode(r)
if err != nil {
zap.S().Errorln("MP3解码失败: ", err)
return
}
defer streamer.Close()
s := beep.Resample(4, format.SampleRate, DefaultSampleRate, streamer)
ctrl := &beep.Ctrl{Streamer: s}
done := make(chan struct{})
speaker.Play(beep.Seq(ctrl, beep.Callback(func() {
close(done)
})))
for {
select {
case <-done:
return
case <-c.Done():
{
speaker.Lock()
ctrl.Streamer = nil
speaker.Unlock()
return
}
}
}
}