mpris

package module
v2.0.0-...-0a7d37a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 24, 2026 License: MIT Imports: 9 Imported by: 0

README

Go MPRIS

Go library for DBus-MPRIS.

[!IMPORTANT] 🔥 Found this useful? A quick star goes a long way.

[!DANGER] v2 is very unstable!

Features

  1. Full MPRIS 2.2 support for Base and Player interfaces (TrackList and Playlists are incomplete).
  2. Type-safe D-Bus access ensuring reliable data handling across all players.
  3. Native time.Duration usage for playback times instead of raw microseconds.
  4. Simple, high-level API for playback control, metadata, and property management.

Install

go get github.com/Nadim147c/go-mpris/v2

The dependency github.com/godbus/dbus/v5 is going to be installed as well.

Client Example

Printing the current playback status and then changing it:

import (
	"log"

	"github.com/Nadim147c/go-mpris/v2"
	"github.com/godbus/dbus/v5"
)

func main() {
	conn, err := dbus.SessionBus()
	if err != nil {
		panic(err)
	}
	names, err := mpris.List(conn)
	if err != nil {
		panic(err)
	}
	if len(names) == 0 {
		log.Fatal("No player found")
	}

	name := names[0]
	client := mpris.NewClient(conn, name)

	status, err := client.GetPlaybackStatus()
	if err != nil {
		log.Fatal("Could not get current playback status")
	}

	log.Printf("The player was %s...", status)
	err = client.PlayPause()
	if err != nil {
		log.Fatal("Could not play/pause player")
	}
}

Server Example

Creating a mock MPRIS server:

import (
	"context"
	"log"

	"github.com/Nadim147c/go-mpris/v2"
	"github.com/godbus/dbus/v5"
)

func main() {
	conn, err := dbus.SessionBus()
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	name := mpris.BaseInterface + ".my_server"
	server := mpris.NewServer(conn, name)

	meta := mpris.Metadata{}
	meta.Set(mpris.KeyTitle, "My Track")
	meta.Set(mpris.KeyArtist, []string{"My Artist"})

	pm := mpris.NewPropertiesManager(&mpris.Properties{
		PlaybackStatus: mpris.PlaybackPlaying,
		Metadata:       meta,
	})

	server.RegisterPropertiesManager(pm, mpris.NoOpPropertySetter{})
	server.RegisterBaseHandler(mpris.NoOpBaseHandler{})
	server.RegisterPlayerHandler(mpris.NoOpPlayerHandler{})

	log.Printf("Listening on %s", name)
	if err := server.Listen(context.Background()); err != nil {
		log.Fatal(err)
	}
}

For more examples, see the examples folder.

Go Docs

Read the docs at https://pkg.go.dev/github.com/Nadim147c/go-mpris.

Credits

emersion and Pauloo27 for the original code.

Documentation

Index

Constants

View Source
const (
	// DBusObjectPath is the root object path for MPRIS-compatible media
	// players. All MPRIS interfaces are exposed under this path on the D-Bus.
	DBusObjectPath = "/org/mpris/MediaPlayer2"
	// PropertiesChangedSignal is the D-Bus signal name emitted when a property
	// changes on an MPRIS interface.
	PropertiesChangedSignal = "org.freedesktop.DBus.Properties.PropertiesChanged"
	// BaseInterface is the main MPRIS interface that provides general
	// information and capabilities about the media player instance.
	BaseInterface = "org.mpris.MediaPlayer2"
	// PlayerInterface defines methods and properties for controlling playback,
	// such as play, pause, seek, and retrieving track metadata.
	PlayerInterface = "org.mpris.MediaPlayer2.Player"
	// TrackListInterface provides access to the list of tracks managed by the
	// player, allowing navigation, retrieval, and management of track items.
	TrackListInterface = "org.mpris.MediaPlayer2.TrackList"
	// PlaylistsInterface defines the MPRIS interface for managing and
	// activating playlists exposed by the player.
	PlaylistsInterface = "org.mpris.MediaPlayer2.Playlists"
	// PlaylistsInterface defines the MPRIS properties.
	DBusPropertyInterface = "org.freedesktop.DBus.Properties"
	// GetPropertyMethod is the standard D-Bus method used to retrieve the value
	// of a property from an interface that implements
	// org.freedesktop.DBus.Properties.
	GetPropertyMethod = "org.freedesktop.DBus.Properties.Get"
	// SetPropertyMethod is the standard D-Bus method used to change the value
	// of a writable property on an interface that implements
	// org.freedesktop.DBus.Properties.
	SetPropertyMethod = "org.freedesktop.DBus.Properties.Set"
)
View Source
const (
	// KeyAlbum is the album name.
	KeyAlbum = "xesam:album"
	// KeyAlbumArtist is the album artist(s).
	KeyAlbumArtist = "xesam:albumArtist"
	// KeyArtist is the track artist(s).
	KeyArtist = "xesam:artist"
	// KeyAsText is the text/lyrics of the track.
	KeyAsText = "xesam:asText"
	// KeyAudioBPM is the speed of the music in beats per minute.
	KeyAudioBPM = "xesam:audioBPM"
	// KeyAutoRating is an automatically generated rating (0.0 to 1.0).
	KeyAutoRating = "xesam:autoRating"
	// KeyComment is a social comment about the track.
	KeyComment = "xesam:comment"
	// KeyComposer is the track composer(s).
	KeyComposer = "xesam:composer"
	// KeyContentCreated is the date/time the content was created.
	KeyContentCreated = "xesam:contentCreated"
	// KeyDiscNumber is the disc number on the album.
	KeyDiscNumber = "xesam:discNumber"
	// KeyFirstUsed is the date/time the track was first played.
	KeyFirstUsed = "xesam:firstUsed"
	// KeyGenre is the genre(s) of the track.
	KeyGenre = "xesam:genre"
	// KeyLastUsed is the date/time the track was last played by any user.
	KeyLastUsed = "xesam:lastUsed"
	// KeyLastUsedByMe is the date/time the track was last played by the current
	// user.
	KeyLastUsedByMe = "xesam:lastUsedByMe"
	// KeyLyricist is the person who wrote the lyrics for the track.
	KeyLyricist = "xesam:lyricist"
	// KeyTitle is the item title.
	KeyTitle = "xesam:title"
	// KeyTrackNumber is the track number on the album.
	KeyTrackNumber = "xesam:trackNumber"
	// KeyURL is the location of the media file.
	KeyURL = "xesam:url"
	// KeyUseCount is the number of times the track has been played.
	KeyUseCount = "xesam:useCount"
	// KeyUserRating is the user's rating of the track (0.0 to 1.0).
	KeyUserRating = "xesam:userRating"
	// KeyTrackID is a unique identity for the track within the context of the playlist.
	KeyTrackID = "mpris:trackid"
	// KeyLength is the duration of the track in microseconds.
	KeyLength = "mpris:length"
	// KeyArtURL is a URI of some album art designed to represent the track/album.
	KeyArtURL = "mpris:artUrl"
)

Variables

View Source
var (
	ErrInvalidType     = errors.New("invalid type")
	ErrNotPrimaryOwner = errors.New("not primary owner")
	ErrValueMissing    = errors.New("value missing or nil")
)

Functions

func List

func List(conn *dbus.Conn) ([]string, error)

List lists the available players.

func OnSignal

func OnSignal(conn *dbus.Conn, ch chan<- *dbus.Signal) error

OnSignal adds a handler to the player's properties change signal.

Types

type BaseHandler

type BaseHandler interface {
	Raise() error
	Quit() error
}

BaseHandler defines the methods for the org.mpris.MediaPlayer2 interface.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents a mpris player.

func NewClient

func NewClient(conn *dbus.Conn, name string) *Client

NewClient connects the the player with the name in the connection conn.

func (*Client) CanControl

func (i *Client) CanControl() (bool, error)

CanControl returns whether the player can be controlled.

func (*Client) CanEditTracks

func (i *Client) CanEditTracks() (bool, error)

CanEditTracks returns if player can edit track list.

func (*Client) CanGoNext

func (i *Client) CanGoNext() (bool, error)

CanGoNext returns whether the player can skip to the next track.

func (*Client) CanGoPrevious

func (i *Client) CanGoPrevious() (bool, error)

CanGoPrevious returns whether the player can skip to the previous track.

func (*Client) CanPause

func (i *Client) CanPause() (bool, error)

CanPause returns whether the player can pause playback.

func (*Client) CanPlay

func (i *Client) CanPlay() (bool, error)

CanPlay returns whether the player can start or resume playback.

func (*Client) CanQuit

func (i *Client) CanQuit() (bool, error)

CanQuit returns whether the player can be quit.

func (*Client) CanRaise

func (i *Client) CanRaise() (bool, error)

CanRaise returns whether the player can be raised.

func (*Client) CanSeek

func (i *Client) CanSeek() (bool, error)

CanSeek returns whether the player can seek within the current track.

func (*Client) CanSetFullscreen

func (i *Client) CanSetFullscreen() (bool, error)

CanSetFullscreen returns whether the player allows changing fullscreen state.

func (*Client) GetAlbum

func (i *Client) GetAlbum() (string, error)

GetAlbum returns the current track album.

func (*Client) GetArtURL

func (i *Client) GetArtURL() (string, error)

GetArtURL returns the cover art URL of the current track.

func (*Client) GetArtist

func (i *Client) GetArtist() ([]string, error)

GetArtist returns the current track artist(s).

func (*Client) GetBaseProperty

func (i *Client) GetBaseProperty(property string) (dbus.Variant, error)

GetBaseProperty returns the prop from the base interface.

func (*Client) GetDesktopEntry

func (i *Client) GetDesktopEntry() (string, error)

GetDesktopEntry returns the desktop entry name of the player.

func (*Client) GetFullscreen

func (i *Client) GetFullscreen() (bool, error)

GetFullscreen returns whether the player is in fullscreen mode.

func (*Client) GetIdentity

func (i *Client) GetIdentity() (string, error)

GetIdentity returns the player identity.

func (*Client) GetLength

func (i *Client) GetLength() (time.Duration, error)

GetLength returns the current track length.

func (*Client) GetLoopStatus

func (i *Client) GetLoopStatus() (LoopStatus, error)

GetLoopStatus returns the current loop status.

func (*Client) GetMaximumRate

func (i *Client) GetMaximumRate() (float64, error)

GetMaximumRate returns the maximum playback rate.

func (*Client) GetMetadata

func (i *Client) GetMetadata() (Metadata, error)

GetMetadata returns the current track metadata.

func (*Client) GetMinimumRate

func (i *Client) GetMinimumRate() (float64, error)

GetMinimumRate returns the minimum playback rate.

func (*Client) GetName

func (i *Client) GetName() string

GetName gets the player full name.

func (*Client) GetPlaybackStatus

func (i *Client) GetPlaybackStatus() (PlaybackStatus, error)

GetPlaybackStatus returns the current playback status.

func (*Client) GetPlayerProperty

func (i *Client) GetPlayerProperty(property string) (dbus.Variant, error)

GetPlayerProperty returns the prop from the player interface.

func (*Client) GetPlaylistsProperty

func (i *Client) GetPlaylistsProperty(property string) (dbus.Variant, error)

GetPlaylistsProperty returns the prop from the playlists interface.

func (*Client) GetPosition

func (i *Client) GetPosition() (time.Duration, error)

GetPosition returns the current playback position.

func (*Client) GetProperty

func (i *Client) GetProperty(iface, property string) (dbus.Variant, error)

GetProperty returns the prop in the iface.

func (*Client) GetRate

func (i *Client) GetRate() (float64, error)

GetRate returns the current playback rate.

func (*Client) GetShuffle

func (i *Client) GetShuffle() (bool, error)

GetShuffle returns true if shuffle mode is enabled, false if playing linearly through a playlist.

func (*Client) GetSupportedURISchemes

func (i *Client) GetSupportedURISchemes() ([]string, error)

GetSupportedUriSchemes returns the supported URI schemes of the player.

func (*Client) GetTitle

func (i *Client) GetTitle() (string, error)

GetTitle returns the current track title.

func (*Client) GetTrackID

func (i *Client) GetTrackID() (dbus.ObjectPath, error)

GetTrackID returns track id for player as dbus.ObjectPath.

func (*Client) GetTrackListProperty

func (i *Client) GetTrackListProperty(property string) (dbus.Variant, error)

GetTrackListProperty returns the prop from the tracklist interface.

func (*Client) GetURL

func (i *Client) GetURL() (string, error)

GetURL returns the URL of the current track.

func (*Client) GetVolume

func (i *Client) GetVolume() (float64, error)

GetVolume returns the current volume.

func (*Client) HasTrackList

func (i *Client) HasTrackList() (bool, error)

HasTrackList returns whether the player has a track list.

func (*Client) Next

func (i *Client) Next() error

Next skips to the next track in the tracklist.

func (*Client) OnSeeked

func (i *Client) OnSeeked(ctx context.Context, position chan<- time.Duration) error

OnSeeked listens for "Seeked" signal and sends the new position as time.Duration to position until ctx is canceled.

func (*Client) OpenURI

func (i *Client) OpenURI(uri string) error

OpenURI opens and plays the given URI if supported.

func (*Client) Pause

func (i *Client) Pause() error

Pause pauses the current track.

func (*Client) Play

func (i *Client) Play() error

Play starts or resumes playback of the current track.

func (*Client) PlayPause

func (i *Client) PlayPause() error

PlayPause resumes the current track if it's paused and pauses it if it's playing.

func (*Client) Previous

func (i *Client) Previous() error

Previous skips to the previous track in the tracklist.

func (*Client) Quit

func (i *Client) Quit() error

Quit closes the player.

func (*Client) Raise

func (i *Client) Raise() error

Raise raises player priority.

func (*Client) Seek

func (i *Client) Seek(offset time.Duration) error

Seek changes the current track position by the given offset. If the offset is negative, the playback position moves backward.

func (*Client) SetBaseProperty

func (i *Client) SetBaseProperty(property string, value any) error

SetBaseProperty sets the propertyName from the base interface.

func (*Client) SetFullscreen

func (i *Client) SetFullscreen(fullscreen bool) error

SetFullscreen sets the fullscreen state of the player.

func (*Client) SetLoopStatus

func (i *Client) SetLoopStatus(loopStatus LoopStatus) error

SetLoopStatus sets the loop status.

func (*Client) SetPlayerProperty

func (i *Client) SetPlayerProperty(property string, value any) error

SetPlayerProperty sets the propertyName from the player interface.

func (*Client) SetPlaylistsProperty

func (i *Client) SetPlaylistsProperty(property string, value any) error

SetPlaylistsProperty sets the propertyName from the playlists interface.

func (*Client) SetPosition

func (i *Client) SetPosition(position time.Duration) error

SetPosition sets the playback position of the current track.

func (*Client) SetProperty

func (i *Client) SetProperty(iface, property string, value any) error

SetProperty sets the value of a property in the interface.

func (*Client) SetRate

func (i *Client) SetRate(rate float64) error

SetRate sets the playback rate.

func (*Client) SetShuffle

func (i *Client) SetShuffle(value bool) error

SetShuffle sets the shuffle mode.

func (*Client) SetTrackListProperty

func (i *Client) SetTrackListProperty(property string, value any) error

SetTrackListProperty sets the propertyName from the tracklist interface.

func (*Client) SetTrackPosition

func (i *Client) SetTrackPosition(
	trackID *dbus.ObjectPath,
	position time.Duration,
) error

SetTrackPosition sets the playback position of a specific track.

func (*Client) SetVolume

func (i *Client) SetVolume(volume float64) error

SetVolume sets the current volume.

func (*Client) Stop

func (i *Client) Stop() error

Stop stops the current track.

func (*Client) SupportedMimeTypes

func (i *Client) SupportedMimeTypes() ([]string, error)

SupportedMimeTypes returns the supported MIME types of the player.

type LoopStatus

type LoopStatus string

LoopStatus represents the loop status of the player. It can be "None", "Track" or "Playlist".

const (
	LoopNone     LoopStatus = "None"
	LoopTrack    LoopStatus = "Track"
	LoopPlaylist LoopStatus = "Playlist"
)

type Metadata

type Metadata map[string]dbus.Variant

Metadata represents the metadata of the current track.

func (Metadata) Get

func (m Metadata) Get(key string) (any, error)

Get returns the value for the given metadata key.

func (Metadata) Has

func (m Metadata) Has(key string) bool

Has checks if the metadata key exists.

func (Metadata) Set

func (m Metadata) Set(key string, v any)

Set sets a value to metadata.

type NoOpBaseHandler

type NoOpBaseHandler struct{}

NoOpBaseHandler implement All method of BaseHandler.

func (NoOpBaseHandler) Quit

func (NoOpBaseHandler) Quit() error

func (NoOpBaseHandler) Raise

func (NoOpBaseHandler) Raise() error

type NoOpPlayerHandler

type NoOpPlayerHandler struct{}

NoOpPlayerHandler implement All method of PlayerHandler.

func (NoOpPlayerHandler) Next

func (NoOpPlayerHandler) Next() error

func (NoOpPlayerHandler) OpenURI

func (NoOpPlayerHandler) OpenURI(string) error

func (NoOpPlayerHandler) Pause

func (NoOpPlayerHandler) Pause() error

func (NoOpPlayerHandler) Play

func (NoOpPlayerHandler) Play() error

func (NoOpPlayerHandler) PlayPause

func (NoOpPlayerHandler) PlayPause() error

func (NoOpPlayerHandler) Previous

func (NoOpPlayerHandler) Previous() error

func (NoOpPlayerHandler) Seek

func (NoOpPlayerHandler) SetPosition

func (NoOpPlayerHandler) Stop

func (NoOpPlayerHandler) Stop() error

type NoOpPropertySetter

type NoOpPropertySetter struct{}

NoOpPropertySetter implement All method of PropertySetter.

func (NoOpPropertySetter) SetFullscreen

func (NoOpPropertySetter) SetFullscreen(fullscreen bool) error

func (NoOpPropertySetter) SetLoopStatus

func (NoOpPropertySetter) SetLoopStatus(status LoopStatus) error

func (NoOpPropertySetter) SetRate

func (NoOpPropertySetter) SetRate(rate float64) error

func (NoOpPropertySetter) SetShuffle

func (NoOpPropertySetter) SetShuffle(shuffle bool) error

func (NoOpPropertySetter) SetVolume

func (NoOpPropertySetter) SetVolume(volume float64) error

type PlaybackStatus

type PlaybackStatus string

PlaybackStatus represents the playback status. It can be "Playing", "Paused" or "Stopped".

const (
	PlaybackPlaying PlaybackStatus = "Playing"
	PlaybackPaused  PlaybackStatus = "Paused"
	PlaybackStopped PlaybackStatus = "Stopped"
)

type PlayerHandler

type PlayerHandler interface {
	Next() error
	Previous() error
	Pause() error
	PlayPause() error
	Stop() error
	Play() error
	Seek(offset time.Duration) error
	SetPosition(trackID dbus.ObjectPath, position time.Duration) error
	OpenURI(uri string) error
}

PlayerHandler defines the methods for the org.mpris.MediaPlayer2.Player interface.

type Properties

type Properties struct {
	// Base properties
	CanQuit             bool
	Fullscreen          bool
	CanSetFullscreen    bool
	CanRaise            bool
	HasTrackList        bool
	Identity            string
	DesktopEntry        string
	SupportedUriSchemes []string
	SupportedMimeTypes  []string

	// Player properties
	PlaybackStatus PlaybackStatus
	LoopStatus     LoopStatus
	Rate           float64
	Shuffle        bool
	Metadata       Metadata
	Volume         float64
	Position       time.Duration
	MinimumRate    float64
	MaximumRate    float64
	CanGoNext      bool
	CanGoPrevious  bool
	CanPlay        bool
	CanPause       bool
	CanSeek        bool
	CanControl     bool
}

Properties contains all the properties supported by the MPRIS server.

type PropertiesManager

type PropertiesManager struct {
	// contains filtered or unexported fields
}

PropertiesManager manages access to MPRIS properties.

func NewPropertiesManager

func NewPropertiesManager(p *Properties) *PropertiesManager

NewPropertiesManager creates a new PropertiesManager.

func (*PropertiesManager) SetProperty

func (pm *PropertiesManager) SetProperty(f func(p *Properties))

SetProperty allows modifying properties safely.

type PropertySetter

type PropertySetter interface {
	SetFullscreen(fullscreen bool) error
	SetLoopStatus(status LoopStatus) error
	SetRate(rate float64) error
	SetShuffle(shuffle bool) error
	SetVolume(volume float64) error
}

PropertySetter handles write requests to MPRIS properties.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server represents a mpris server.

func NewServer

func NewServer(conn *dbus.Conn, name string) *Server

NewServer connects the the server with the name in the connection conn.

func (*Server) Close

func (s *Server) Close() error

func (*Server) Listen

func (s *Server) Listen(ctx context.Context) error

func (*Server) RegisterBaseHandler

func (s *Server) RegisterBaseHandler(handler BaseHandler) error

RegisterBaseHandler registers the base handler on the server.

func (*Server) RegisterPlayerHandler

func (s *Server) RegisterPlayerHandler(handler PlayerHandler) error

RegisterPlayerHandler registers the player handler on the server.

func (*Server) RegisterPropertiesManager

func (s *Server) RegisterPropertiesManager(pm *PropertiesManager, setter PropertySetter) error

RegisterPropertiesManager registers the property manager on the server.

Directories

Path Synopsis
examples
playpause command
raise command
seeked command
signal command
volume command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址