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

163 lines
2.9 KiB
Go

package player
import (
"fmt"
"image"
"strconv"
"strings"
"time"
"periph.io/x/conn/v3/physic"
"go.maze.io/harmon/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
Play() error
Pause() error
Next() error
Previous() error
Seek(time.Duration) error
}
// 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
// Source format
Source AudioFormat
// Output format
Output AudioFormat
// 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("source=%s output=%s elapsed=%s play=%t", s.Source, s.Output, s.Elapsed, s.Playing)
}
// Track represents an audio track.
type Track struct {
// Artist is the performing artist.
Artist string
// Title of the track.
Title string
// Album the track appears on.
Album string
// Label the album is released on.
Label string
// Date the track was published.
Date time.Time
// Track number.
Track int
// Disc number.
Disc int
// Duration is the track length.
Duration time.Duration
// Format is the audio format.
Format string
// Genre names.
Genre []string
// Path is the file path of the track.
Path string
// Image is the track or album art.
Image image.Image
}
func (t *Track) String() string {
if t == nil {
return "nil"
}
return fmt.Sprintf("%s - %s (%d on %s, %s)", t.Artist, t.Title, t.Track, t.Album, t.Duration)
}