Convert Figma logo to code with AI

plietar logolibrespot

Open Source Spotify client library

1,137
185
1,137
83

Top Related Projects

A Spotify Connect client that mostly Just Works™

A spotify daemon

Adblocker for Spotify

Quick Overview

Librespot is an open-source Spotify client library written in Rust. It allows developers to create their own Spotify Connect players and integrate Spotify playback functionality into their applications. The project aims to provide a robust and efficient alternative to the official Spotify SDK.

Pros

  • Written in Rust, offering memory safety and high performance
  • Supports Spotify Connect protocol, enabling seamless integration with Spotify ecosystem
  • Actively maintained with regular updates and bug fixes
  • Provides a flexible API for custom implementations

Cons

  • Unofficial library, may not have access to all Spotify features
  • Requires Spotify Premium account for full functionality
  • Documentation could be more comprehensive
  • May require more setup and configuration compared to official SDKs

Code Examples

  1. Creating a Spotify session:
use librespot::core::Session;
use librespot::core::config::SessionConfig;

let session_config = SessionConfig::default();
let session = Session::connect(session_config, credentials).await?;
  1. Playing a track:
use librespot::playback::player::Player;
use librespot::core::spotify_id::SpotifyId;

let player = Player::new(config, session.clone(), None, move || {});
let track_id = SpotifyId::from_base62("spotify:track:0GSwFCbD1Joq8f3cIW2OId").unwrap();
player.load(track_id, true, 0);
  1. Handling events:
use librespot::core::EventSender;

let (event_sender, event_receiver) = tokio::sync::mpsc::unbounded_channel();
let event_sender = EventSender::new(event_sender);

tokio::spawn(async move {
    while let Some(event) = event_receiver.recv().await {
        println!("Received event: {:?}", event);
    }
});

Getting Started

To use librespot in your Rust project, add the following to your Cargo.toml:

[dependencies]
librespot = "0.4"
tokio = { version = "1", features = ["full"] }

Then, in your Rust code:

use librespot::core::config::SessionConfig;
use librespot::core::session::Session;
use librespot::playback::config::PlayerConfig;
use librespot::playback::player::Player;

#[tokio::main]
async fn main() {
    let session_config = SessionConfig::default();
    let player_config = PlayerConfig::default();
    
    // Initialize session and player
    let session = Session::connect(session_config, credentials).await.unwrap();
    let player = Player::new(player_config, session.clone(), None, move || {});

    // Use the player to control playback
}

Competitor Comparisons

A Spotify Connect client that mostly Just Works™

Pros of Raspotify

  • Easier setup and installation process, especially for Raspberry Pi users
  • Includes a systemd service for automatic startup and management
  • Provides a convenient command-line interface for configuration

Cons of Raspotify

  • Less flexible and customizable compared to Librespot
  • Limited to Raspberry Pi and Debian-based systems
  • May have slower update cycles for new Spotify features

Code Comparison

Raspotify (shell script for installation):

curl -sL https://dtcooper.github.io/raspotify/install.sh | sh

Librespot (Rust code for audio playback):

let (mut player, _) = Player::new(None, None, false, None);
player.load(track.id(), true, 0);
player.play();

Raspotify is built on top of Librespot, providing a more user-friendly experience for Raspberry Pi users. It offers a simpler installation process and automatic startup, making it ideal for those who want a quick Spotify Connect solution. However, Librespot provides more flexibility and customization options, allowing developers to integrate Spotify playback into their own applications. Librespot also supports a wider range of platforms and can be more easily adapted to different use cases. While Raspotify is great for plug-and-play setups, Librespot is better suited for developers and advanced users who need more control over the Spotify Connect implementation.

A spotify daemon

Pros of Spotifyd

  • Written in Rust, offering better performance and memory safety
  • Designed specifically as a Spotify daemon, with a focus on lightweight operation
  • Supports more audio backends, including PulseAudio and ALSA

Cons of Spotifyd

  • Less actively maintained compared to librespot
  • Fewer features and less flexibility for integration into other projects
  • Limited to Spotify-specific functionality

Code Comparison

Spotifyd (main.rs):

fn main() {
    let config = Config::load_config();
    let (mut spotify, credentials) = get_spotify_object(&config);
    let player = Player::new(config, spotify, credentials);
    player.start();
}

librespot (main.rs):

fn main() {
    let session_config = SessionConfig::default();
    let player_config = PlayerConfig::default();
    let audio_config = AudioConfig::default();
    let credentials = Credentials::with_password(username, password);
    let (session, _) = Session::connect(session_config, credentials, None).unwrap();
}

Both projects aim to provide Spotify playback functionality, but Spotifyd is more focused on being a standalone daemon, while librespot offers a more flexible library for integration into other applications. librespot has a larger community and more frequent updates, making it potentially more suitable for developers looking to build custom Spotify-enabled applications.

Adblocker for Spotify

Pros of spotify-adblock

  • Specifically designed to block ads in the Spotify desktop client
  • Lightweight and focused on a single purpose
  • Easy to install and use for non-technical users

Cons of spotify-adblock

  • Limited functionality compared to librespot's full client implementation
  • May break with Spotify client updates, requiring frequent maintenance
  • Only works with the official Spotify desktop client

Code Comparison

spotify-adblock:

static int (*real_connect)(int sockfd, const struct sockaddr *addr, socklen_t addrlen) = NULL;

int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
    if (is_spotify_ad(addr))
        return -1;
    return real_connect(sockfd, addr, addrlen);
}

librespot:

pub struct Session {
    country: String,
    device_id: String,
    access_token: AccessToken,
    client: Client,
    // ... other fields
}

impl Session {
    pub async fn connect(config: SessionConfig) -> Result<Session, Error> {
        // ... implementation
    }
}

The spotify-adblock code focuses on intercepting network connections to block ads, while librespot implements a full Spotify client session, showcasing the difference in scope and functionality between the two projects.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

librespot

librespot is an open source client library for Spotify. It enables applications to use Spotify's service, without using the official but closed-source libspotify. Additionally, it will provide extra features which are not available in the official library.

Note: librespot only works with Spotify Premium.

Unmaintained

Unfortunately I am unable to maintain librespot anymore. It should still work, but issues and Pull requests will be ignored. Feel free to fork it and continue development there. If a fork gains traction I will happily point to it from the README.

Building

Rust 1.17.0 or later is required to build librespot.

If you are building librespot on macOS, the homebrew provided rust may fail due to the way in which homebrew installs rust. In this case, uninstall the homebrew version of rust and use rustup, and librespot should then build.

It also requires a C, with portaudio.

On debian / ubuntu, the following command will install these dependencies :

sudo apt-get install build-essential portaudio19-dev

On Fedora systems, the following command will install these dependencies :

sudo dnf install portaudio-devel make gcc

On macOS, using homebrew :

brew install portaudio

Once you've cloned this repository you can build librespot using cargo.

cargo build --release

Usage

A sample program implementing a headless Spotify Connect receiver is provided. Once you've built librespot, run it using :

target/release/librespot --username USERNAME --cache CACHEDIR --name DEVICENAME

Discovery mode

librespot can be run in discovery mode, in which case no password is required at startup. For that, simply omit the --username argument.

Audio Backends

librespot supports various audio backends. Multiple backends can be enabled at compile time by enabling the corresponding cargo feature. By default, only PortAudio is enabled.

A specific backend can selected at runtime using the --backend switch.

cargo build --features portaudio-backend
target/release/librespot [...] --backend portaudio

The following backends are currently available :

  • ALSA
  • PortAudio
  • PulseAudio

Cross-compiling

A cross compilation environment is provided as a docker image. Build the image from the root of the project with the following command :

$ docker build -t librespot-cross -f contrib/Dockerfile .

The resulting image can be used to build librespot for linux x86_64, armhf (compatible e. g. with Raspberry Pi 2 or 3, but not with Raspberry Pi 1 or Zero) and armel. The compiled binaries will be located in /tmp/librespot-build

docker run -v /tmp/librespot-build:/build librespot-cross

If only one architecture is desired, cargo can be invoked directly with the appropriate options :

docker run -v /tmp/librespot-build:/build librespot-cross cargo build --release --no-default-features --features alsa-backend
docker run -v /tmp/librespot-build:/build librespot-cross cargo build --release --target arm-unknown-linux-gnueabihf --no-default-features --features alsa-backend
docker run -v /tmp/librespot-build:/build librespot-cross cargo build --release --target arm-unknown-linux-gnueabi --no-default-features --features alsa-backend

Don't forget to set the with-tremor feature flag if your target device does not have floating-point capabilities.

Development

When developing librespot, it is preferable to use Rust nightly, and build it using the following :

cargo build --no-default-features --features "nightly portaudio-backend"

This produces better compilation error messages than with the default configuration.

Disclaimer

Using this code to connect to Spotify's API is probably forbidden by them. Use at your own risk.

Contact

Come and hang out on gitter if you need help or want to offer some. https://gitter.im/sashahilton00/spotify-connect-resources

License

Everything in this repository is licensed under the MIT license.