Files
beatglow/player/player.go
T
2026-10-29 17:29:41 +01:00

153 lines
2.9 KiB
Go

package player
import (
"fmt"
"image"
"strconv"
"strings"
"time"
"periph.io/x/conn/v3/physic"
"github.com/BeatGlow/beatglow/hardware"
)
// Player controls music playback.
type Player interface {
hardware.Driver
// Name returns the name of the source.
Name() string
// Events returns a channel that will be used to send events to the source.
Events() (<-chan Event, error)
// Status of the player
Status() *Status
// ChangeVolume changes the relative volume of the player.
ChangeVolume(delta int) error
// SetVolume changes the volume of the player.
SetVolume(level int) error
// ToggleMute toggles mute.
ToggleMute() error
// Player controls
Play() error
Pause() error
Next() error
Previous() error
Seek(time.Duration) error
// Playlist controls.
Playlist() ([]*Track, error)
}
type AlbumArt interface {
AlbumArt(*Track) (image.Image, bool)
}
// AudioFormat is the audio format.
type AudioFormat struct {
Encoding string
SampleRate physic.Frequency
Bits int
Channels int
BitRate int
}
func (f AudioFormat) String() string {
e := f.Encoding
if e == "" {
e = "PCM"
}
return fmt.Sprintf("%s %s %d-bits %dch %d bits/s", e, f.SampleRate, f.Bits, f.Channels, f.BitRate)
}
func ParseMPDAudioFormat(s string) (f AudioFormat, err error) {
var i int
if i = strings.IndexByte(s, ':'); i == -1 {
return f, fmt.Errorf("player: malformed MPD audio format %q", s)
} else if err = f.SampleRate.Set(s[:i]); err != nil {
return
}
s = s[i+1:]
if i = strings.IndexByte(s, ':'); i == -1 {
return f, fmt.Errorf("player: malformed MPD audio format %q", s)
} else if f.Bits, err = strconv.Atoi(s[:i]); err != nil {
return
}
s = s[i+1:]
if f.Channels, err = strconv.Atoi(s); err != nil {
return
}
return f, err
}
// Status represents the current status of the player.
type Status struct {
// Player instance.
Player Player
// Format of the stream.
Format AudioFormat
// Duration of the current track.
Duration time.Duration
// Elapsed time playing the current track.
Elapsed time.Duration
// ElapsedPercentage of the current track.
ElapsedPercentage float64
// Playing indicates if a track is playing.
Playing bool
// Paused indicates if the track is paused.
Paused bool
// Repeat enabled.
Repeat bool
// Shuffle enabled.
Shuffle bool
// Volume in range [0..100]
Volume int
// Muted indicates if the player is muted.
Muted bool
// Track is the current track loaded in the player.
Track *Track
}
func (s *Status) String() string {
return fmt.Sprintf("format=%s elapsed=%s/%d play=%t", s.Format, s.Elapsed, s.Duration, s.Playing)
}
func (s *Status) Eq(o *Status) bool {
if s == nil || o == nil {
return false
}
return s.Playing == o.Playing && s.Paused == o.Paused
}
type EventObserver interface {
PlayerEvent(Event)
}
type StatusObserver interface {
StatusChanged(*Status)
}
type TrackObserver interface {
TrackChanged(Player, *Track)
}