Implement MPRIS D-Bus interface in your application

Overview

MPRIS Server

github crates.io docs CI

Implement MPRIS D-Bus interface in your application.

This library provides the essential functionalities for implementing the MPRIS D-Bus interface on the service side. This enables your application to become discoverable and controllable by other MPRIS-compatible media controllers, including but not limited to GNOME Shell, KDE Plasma, and other libraries such as mpris.

This library supports all the following interfaces as defined in the specification:

To implement these interfaces, this crate offers two flavors: you can either create your own struct and implement RootInterface and PlayerInterface (or with optional TrackListInterface and PlaylistsInterface), or you can use the ready-to-use Player struct.

Examples

For more detailed examples, see also the examples directory.

There is also a real-word example of this library being used in Mousai, a music recognizer application for Linux.

Manual Implementation (via Server or LocalServer)

It is recommended to manually create your own implementation of the interfaces if you want to have more control. You can do this by creating your own struct and implementing the required interfaces, then passing your struct as implementation in Server. You can also use LocalServer and the local version of the interfaces if your struct can't be sent and shared across threads.

use std::future;

use mpris_server::{
    async_trait,
    zbus::{fdo, Result},
    Metadata, PlayerInterface, Property, RootInterface, Server, Signal, Time, Volume,
};

pub struct MyPlayer;

#[async_trait]
impl RootInterface for MyPlayer {
    async fn identity(&self) -> fdo::Result<String> {
        Ok("MyPlayer".into())
    }

    // Other methods...
}

#[async_trait]
impl PlayerInterface for MyPlayer {
    async fn set_volume(&self, volume: Volume) -> Result<()> {
        self.volume.set(volume);
        Ok(())
    }

    async fn metadata(&self) -> fdo::Result<Metadata> {
        let metadata = Metadata::builder()
            .title("My Song")
            .artist(["My Artist"])
            .album("My Album")
            .length(Time::from_micros(123))
            .build();
        Ok(metadata)
    }

    // Other methods...
}

#[async_std::main]
async fn main() -> Result<()> {
    let server = Server::new("com.my.Application", MyPlayer);

    // Initialize server's connection to the session bus
    server.init().await?;

    // Emit `PropertiesChanged` signal for `CanSeek` and `Metadata` properties
    server.properties_changed(Property::CanSeek | Property::Metadata).await?;

    // Emit `Seeked` signal
    server
        .emit(Signal::Seeked {
            position: Time::from_micros(124),
        })
        .await?;

    // Prevent the program from exiting.
    future::pending::<()>().await;

    Ok(())
}

Ready-to-use Implementation (via Player)

If you want to create a simple player without having to implement the interfaces, you can use the ready-to-use Player struct that implements those interfaces internally. This struct has its own internal state, automatically emits properties changed signals, and allows you to connect to method and property setter calls.

However, Player currently only supports the more commonly used org.mpris.MediaPlayer2 and org.mpris.MediaPlayer2.Player interfaces.

use std::future;

use mpris_server::{zbus::Result, Player, Time};

#[async_std::main]
async fn main() -> Result<()> {
    let player = Player::builder("com.my.Application")
        .can_play(true)
        .can_pause(true)
        .build();

    // Handle `PlayPause` method call
    player.connect_play_pause(|_player| {
        println!("PlayPause");
    });

    // Initialize connection and run event handler task
    let task = player.init_and_run();
    async_std::task::spawn_local(async move {
        task.await.unwrap();
    });

    // Update `CanPlay` property and emit `PropertiesChanged` signal for it
    player.set_can_play(false).await?;

    // Emit `Seeked` signal
    player.seeked(Time::from_millis(1000)).await?;

    // Prevent the program from exiting.
    future::pending::<()>().await;

    Ok(())
}

License

Copyright 2023 Dave Patrick Caberto

This software is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at this site.

You might also like...
An utility application to help managing your C++ OI workspaces.

oi_helper oi_helper is an utility application to help managing your C++ OI workspaces. Why oi_helper We all know that we often need a project manager

FileSorterX is an automatic file sorting application that sorts your files into folders based on their file extension
FileSorterX is an automatic file sorting application that sorts your files into folders based on their file extension

FileSorterX is an automatic file sorting application that sorts your files into folders based on their file extension. With FileSorterX, you can easily keep your files organized and find what you need quickly.

Show HTML content
Show HTML content "inside" your egui rendered application

hframe Show HTML content "inside" your egui rendered application. "hframe" stands for "HTML Frame". Note: hframe only works when the application is co

Low-level Rust library for implementing terminal command line interface, like in embedded systems.

Terminal CLI Need to build an interactive command prompt, with commands, properties and with full autocomplete? This is for you. Example, output only

A Text User Interface library for the Rust programming language
A Text User Interface library for the Rust programming language

Cursive Cursive is a TUI (Text User Interface) library for rust. It uses ncurses by default, but other backends are available. It allows you to build

A cross platform minimalistic text user interface
A cross platform minimalistic text user interface

titik Titik is a crossplatform TUI widget library with the goal of being able to interact intuitively on these widgets. It uses crossterm as the under

A cross-platform graphical process/system monitor with a customizable interface and a multitude of features
A cross-platform graphical process/system monitor with a customizable interface and a multitude of features

A cross-platform graphical process/system monitor with a customizable interface and a multitude of features. Supports Linux, macOS, and Windows. Inspired by both gtop and gotop.

⚗️ Superfast CLI interface for the conventional commits commit format
⚗️ Superfast CLI interface for the conventional commits commit format

resin ⚗️ Superfast CLI interface for the conventional commits commit format ❓ What is resin? resin is a CLI (command-line interface) tool that makes i

⚗️ Superfast CLI interface for the conventional commits commit format
⚗️ Superfast CLI interface for the conventional commits commit format

resin ⚗️ Superfast CLI interface for the conventional commits commit format ❓ What is resin? resin is a CLI (command-line interface) tool that makes i

A fully extensible command interface to navigate around your leptos application.

leptos-kbar A fully extensible command interface to navigate around your leptos application. See demo: https://leptos-kbar.vercel.app/ Roadmap leptos-

null 7 Mar 10, 2024
A diff-based data management language to implement unlimited undo, auto-save for games, and cloud-apps which needs to retain every change.

Docchi is a diff-based data management language to implement unlimited undo, auto-save for games, and cloud-apps which needs to save very often. User'

juzy 21 Sep 19, 2022
The joker_query is a cute query builder, with Joker can implement most complex queries with sugar syntax

joker_query The joker_query is most sugared query builder of Rust, with joker_query can implement most complex queries with sugar syntax Features − (O

DanyalMh 8 Dec 13, 2023
Add CLI & form interface to your program

Add CLI & form interface to your program

null 292 Nov 4, 2022
OSINT from your favorite services in a friendly terminal user interface

osintui Open Source Intelligence Terminal User Interface Report Bug · Request Feature Installation First, install Rust (using the recommended rustup i

Will Sheldon 639 Jan 4, 2023
A command line application which sets your wall paper with new image generating pollens once they arrive.

pollenwall Table of Contents pollenwall About Installation Binary releases Build from source Usage Command Line Arguments Running as a service MacOS L

Pollinations.AI 2 Jan 7, 2022
Wena is a micro-framework that provides an elegant starting point for your console application.

Wena was created by Nuno Maduro, and is a Rust Lang micro-framework that provides an elegant starting point for your console application. This project

null 251 Dec 11, 2022
laydown is a simple CLI application to help you prepare for your next Daily Standup

laydown is a simple CLI application to help you prepare for your next Daily Standup. No longer shall your name be called on only for you to stare into the abyss while you struggle to remember what you did yesterday.

badjr13 83 Dec 26, 2022
omekasy is a command line application that converts alphanumeric characters in your input to various styles defined in Unicode.

omekasy is a command line application that converts alphanumeric characters in your input to various styles defined in Unicode. omekasy means "dress up" in Japanese.

null 105 Nov 16, 2022
A robust, customizable, blazingly-fast, efficient and easy-to-use command line application to uwu'ify your text!

uwuifyy A robust, customizable, blazingly-fast, efficient and easy-to-use command line application to uwu'ify your text! Logo Credits: Jade Nelson Tab

Hamothy 43 Dec 12, 2022