залил
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"math"
|
||||
"os"
|
||||
"stream-bot/internal/logger"
|
||||
|
||||
"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 {
|
||||
logger.Warn("Audio player not initialized, cannot play %s", filePath)
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user