package audio import ( "math" "os" "github.com/faiface/beep" "github.com/faiface/beep/effects" "github.com/faiface/beep/mp3" "github.com/faiface/beep/speaker" "github.com/faiface/beep/wav" ) var initialized bool func Init() error { // Увеличенный буфер (было 200, стало 4096) для плавности err := speaker.Init(44100, 4096) if err == nil { initialized = true } return err } func Close() { if initialized { speaker.Close() } } func PlaySound(filePath string) error { return PlayWithVolume(filePath, 100) } func PlayWithVolume(filePath string, volume int) error { if !initialized { return nil } if volume <= 0 { return nil } if volume > 100 { volume = 100 } f, err := os.Open(filePath) if err != nil { return err } var streamer beep.StreamSeekCloser var errDecode error if len(filePath) > 4 && filePath[len(filePath)-4:] == ".mp3" { streamer, _, errDecode = mp3.Decode(f) } else { streamer, _, errDecode = wav.Decode(f) } if errDecode != nil { f.Close() return errDecode } gain := 20 * math.Log10(float64(volume)/100.0) volumeStreamer := &effects.Volume{ Streamer: streamer, Base: 2, Volume: gain, Silent: false, } speaker.Play(beep.Seq(volumeStreamer, beep.Callback(func() { streamer.Close() f.Close() }))) return nil }