Skip to the content

Music Player API: How to Build a Custom Audio Player with Streaming Service Data

Music Player API: How to Build a Custom Audio Player with Streaming Service Data

Building a music player used to mean picking one streaming service and locking yourself into its SDK. Today, users expect access to tracks from the services they already pay for. A music player API gives you the data layer to make that happen: track metadata, artwork, preview URLs, and user libraries, all through standard REST calls instead of platform-specific SDKs.

This guide walks you through what a music player API provides, how to normalize data across streaming services, and how to build a custom audio player step by step with real code examples.

What Is a Music Player API?

A music player API is a REST interface that exposes streaming service data for use in your own applications. It gives you programmatic access to track metadata (title, artist, album, duration, artwork), search functionality, user playlists, liked tracks, and playback preview URLs. Developers reach for a music player API when they need to integrate music data into a custom UI without rebuilding authentication, pagination, and response parsing for every streaming platform individually.

Core Features of a Music Player API

The feature set you need depends on what you are building. At minimum, most music player integrations require track search, metadata retrieval, and a preview URL or the service's own player. More advanced builds add queue management, user library access, and cross-service functionality.

Here is how the three main approaches compare:

FeatureNative SDKs (per service)Unified API (MusicAPI)Build from Scratch
Track searchYes (per SDK)Yes (one endpoint)Yes (you build each)
Metadata retrievalYes (different formats)Yes (normalized response)Yes (you normalize)
Preview URLsVaries by SDKYes (when the service gives one)You handle each
Full-track playbackYes (the SDK plays)No (use the service's SDK or embed)You integrate each SDK
User playlistsYes (per SDK auth)Yes (one auth flow)Yes (you build each)
Liked tracksYes (per SDK auth)Yes (one auth flow)Yes (you build each)
Cross-service supportNo (one SDK = one service)Yes (11 services)You build and maintain
OAuth handlingYou implement per serviceHandled for youYou implement per service
Time to first integrationDays to weeks per serviceMinutesWeeks to months

Native SDKs give you deep access to a single platform, but every additional service multiplies your auth code, response parsing, and maintenance burden. Building from scratch offers maximum control at maximum cost. A unified music API sits in the middle for the data: one integration, normalized responses, and broad service coverage. It does not replace the playback SDKs.

How MusicAPI Handles Track Data Across Services

MusicAPI connects to 11 streaming services through a single REST API. The catalog endpoints (search, match, inspect) need no connected user. The library endpoints (playlists, liked tracks, user profiles) work for a connected user on services including Spotify, Apple Music, YouTube, Tidal, Deezer, Amazon Music and SoundCloud. MusicAPI does not play audio and has no playback endpoints.

The key advantage for building a music player: every response follows the same schema regardless of which streaming service the data comes from. A track object from Spotify looks identical to a track object from Tidal or Deezer in MusicAPI's response format.

Here is a search request that works across any supported service:

const response = await fetch('https://api.musicapi.com/public/search', {
  method: 'POST',
  headers: {
    // The Client ID is public, so this call may run in a browser
    'Authorization': 'Token YOUR_CLIENT_ID',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    type: 'track',
    track: 'Bohemian Rhapsody',
    artist: 'Queen',
    sources: ['spotify', 'appleMusic', 'tidal', 'deezer']
  })
});

const data = await response.json();

The response returns a normalized track object from each service:

{
  "tracks": [
    {
      "source": "spotify",
      "status": "success",
      "type": "track",
      "data": {
        "externalId": "4u7EnebtmKWzUH433cf5Qv",
        "name": "Bohemian Rhapsody",
        "artistNames": ["Queen"],
        "albumName": "A Night at the Opera",
        "imageUrl": "https://i.scdn.co/image/...",
        "previewUrl": null,
        "isrc": "GBUM71029604",
        "duration": 354947,
        "url": "https://open.spotify.com/track/..."
      }
    },
    {
      "source": "tidal",
      "status": "success",
      "type": "track",
      "data": {
        "externalId": "56450803",
        "name": "Bohemian Rhapsody",
        "artistNames": ["Queen"],
        "albumName": "A Night At The Opera",
        "imageUrl": "https://resources.tidal.com/images/...",
        "previewUrl": null,
        "isrc": "GBUM71029604",
        "duration": 354000,
        "url": "https://tidal.com/browse/track/..."
      }
    }
  ]
}

Same fields, same structure, regardless of source. previewUrl is a short sample where the service gives one, and null otherwise. No per-service response parsing. No conditional logic to extract artist names from different nested objects. MusicAPI handles the per-service OAuth and response normalization so you can focus on your player UI. Check out all available endpoints to see what data you can pull into your player.

Building a Custom Audio Player: Step by Step

Let's build a functional audio player in React that pulls track data from multiple streaming services, displays metadata, and handles playback controls. This walkthrough covers authentication, data fetching, UI rendering, and playback state management.

Setting Up MusicAPI Authentication

Before fetching user-specific data like playlists and liked tracks, you need to authenticate users with their streaming service accounts. MusicAPI provides a unified auth flow that works across all supported services.

First, send your user to the hosted sign-in:

// The sign-in is a page, not an API call. Open it in the user's browser.
const url = new URL('https://app.musicapi.com/your-account-slug');
url.searchParams.set('returnUrl', 'https://yourapp.com/callback');
window.location.assign(url.toString());

// To skip the service picker, put the service in the path:
// https://app.musicapi.com/your-account-slug/spotify/auth?returnUrl=...

After the user completes authentication, they return to your return URL with a data64 parameter. Decode it on your backend and store the integrationUserUUID with your user:

// On your backend: the return URL gets a `data64` query parameter (base64-encoded JSON)
const params = new URL(request.url, 'https://yourapp.com').searchParams;
const data = JSON.parse(Buffer.from(params.get('data64'), 'base64').toString('utf8'));

if (data.authModel.status !== 'success') {
  throw new Error(`Sign-in failed: ${data.authModel.errorType ?? data.authModel.error}`);
}
const integrationUserUUID = data.integrationUserUUID; // store it with your user

Fetching Track Data and Metadata

With the user authenticated, your backend can fetch their music data. The library calls use your Client Secret, so they never run in the browser:

// Backend (Express): the liked tracks of the signed-in user
const auth = Buffer.from(
  `${process.env.MUSICAPI_CLIENT_ID}:${process.env.MUSICAPI_CLIENT_SECRET}`
).toString('base64');

app.get('/api/liked-tracks', async (req, res) => {
  const response = await fetch(
    `https://api.musicapi.com/api/${req.session.integrationUserUUID}/liked/tracks`,
    { headers: { Authorization: `Basic ${auth}` } }
  );
  res.status(response.status).json(await response.json());
});

Here is a React hook that reads them from that route:

import { useState, useEffect } from 'react';

function useLikedTracks() {
  const [tracks, setTracks] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchTracks() {
      const response = await fetch('/api/liked-tracks');
      const data = await response.json();
      setTracks(data.results);
      setLoading(false);
    }

    fetchTracks();
  }, []);

  return { tracks, loading };
}

The response gives you everything your player needs to render a track list:

{
  "results": [
    {
      "id": "4u7EnebtmKWzUH433cf5Qv",
      "name": "Bohemian Rhapsody",
      "isrc": "GBUM71029604",
      "duration": 354947,
      "imageUrl": "https://i.scdn.co/image/ab67616d...",
      "previewUrl": null,
      "album": {
        "name": "A Night at the Opera",
        "artists": [{ "name": "Queen" }]
      },
      "artists": [{ "name": "Queen" }],
      "dateAdded": "2024-03-15T10:30:00Z"
    }
  ],
  "nextParam": "eyJvZmZzZXQiOjUwfQ==",
  "totalItems": 342
}

You can also fetch user playlists and their tracks using the same pattern:

// Backend: the user's playlists
const playlists = await fetch(
  `https://api.musicapi.com/api/${integrationUserUUID}/playlists`,
  { headers: { Authorization: `Basic ${auth}` } }
).then(res => res.json());

// Backend: the tracks of one playlist
const playlistTracks = await fetch(
  `https://api.musicapi.com/api/${integrationUserUUID}/playlists/${playlistId}/items`,
  { headers: { Authorization: `Basic ${auth}` } }
).then(res => res.json());

Rendering the Player UI

Now let's build the player component. This component displays the current track's metadata and artwork:

function MusicPlayer({ track, isPlaying, onPlayPause, onNext, onPrevious }) {
  if (!track) return null;

  const artistName = track.artists?.[0]?.name || 'Unknown Artist';
  const duration = formatDuration(track.duration);

  return (
    <div className="music-player">
      <img 
        src={track.imageUrl} 
        alt={`${track.album?.name} cover`}
        className="album-art"
      />
      <div className="track-info">
        <h3 className="track-name">{track.name}</h3>
        <p className="artist-name">{artistName}</p>
        <p className="album-name">{track.album?.name}</p>
      </div>
      <div className="controls">
        <button onClick={onPrevious} aria-label="Previous track">⏮</button>
        <button onClick={onPlayPause} aria-label={isPlaying ? 'Pause' : 'Play'}>
          {isPlaying ? '⏸' : '▶'}
        </button>
        <button onClick={onNext} aria-label="Next track">⏭</button>
      </div>
      <span className="duration">{duration}</span>
    </div>
  );
}

function formatDuration(ms) {
  if (!ms) return '0:00';
  const minutes = Math.floor(ms / 60000);
  const seconds = Math.floor((ms % 60000) / 1000);
  return `${minutes}:${seconds.toString().padStart(2, '0')}`;
}

Handling Playback State and Controls

The final piece: managing playback state with the HTML5 Audio API. This hook plays the preview of a track, where the track has one. It does not play full tracks: for those, hand the track id to the streaming service's own SDK (Spotify Web Playback SDK, Apple MusicKit and similar).

import { useState, useRef, useCallback } from 'react';

function useAudioPlayer(tracks) {
  const audioRef = useRef(new Audio());
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [progress, setProgress] = useState(0);

  const currentTrack = tracks[currentIndex] || null;

  const play = useCallback(() => {
    if (!currentTrack?.previewUrl) return;
    
    const audio = audioRef.current;
    if (audio.src !== currentTrack.previewUrl) {
      audio.src = currentTrack.previewUrl;
    }
    audio.play();
    setIsPlaying(true);
  }, [currentTrack]);

  const pause = useCallback(() => {
    audioRef.current.pause();
    setIsPlaying(false);
  }, []);

  const playPause = useCallback(() => {
    isPlaying ? pause() : play();
  }, [isPlaying, play, pause]);

  const next = useCallback(() => {
    const nextIndex = (currentIndex + 1) % tracks.length;
    setCurrentIndex(nextIndex);
    audioRef.current.src = tracks[nextIndex]?.previewUrl || '';
    if (isPlaying) audioRef.current.play();
  }, [currentIndex, tracks, isPlaying]);

  const previous = useCallback(() => {
    const prevIndex = currentIndex === 0 
      ? tracks.length - 1 
      : currentIndex - 1;
    setCurrentIndex(prevIndex);
    audioRef.current.src = tracks[prevIndex]?.previewUrl || '';
    if (isPlaying) audioRef.current.play();
  }, [currentIndex, tracks, isPlaying]);

  const seek = useCallback((percent) => {
    const audio = audioRef.current;
    audio.currentTime = (percent / 100) * audio.duration;
  }, []);

  return {
    currentTrack,
    isPlaying,
    progress,
    playPause,
    next,
    previous,
    seek
  };
}

Putting it all together in your app:

function App() {
  const { tracks, loading } = useLikedTracks();
  const player = useAudioPlayer(tracks);

  if (loading) return <div>Loading your music...</div>;

  return (
    <div className="app">
      <TrackList 
        tracks={tracks} 
        onSelect={(index) => player.selectTrack(index)} 
      />
      <MusicPlayer
        track={player.currentTrack}
        isPlaying={player.isPlaying}
        onPlayPause={player.playPause}
        onNext={player.next}
        onPrevious={player.previous}
      />
    </div>
  );
}

Not building a custom player? POST /public/embed/url takes a share link and returns the streaming service's own iframe player for it. The service plays the audio. See the embed player page.

Music Player API Use Cases

A music player API is not just for standalone music apps. Here are five use cases where streaming service data powers a better product:

Fitness apps. Pull a user's workout playlists from their connected streaming service and sync BPM-matched tracks to exercise intensity. The user stays in your app while hearing music from the library they already built.

Social music sharing. Let users share what they are listening to, build collaborative playlists, or vote on tracks in a group session. Fetching playlist data from multiple services means friends on different platforms can still participate.

DJ and mixing tools. Access track metadata, BPM, duration, and ISRC codes to build beat-matching interfaces, setlist planners, or transition tools. The normalized response format means your matching logic works the same regardless of the source service.

In-game music. Give players control over their in-game soundtrack by connecting their streaming account. Fetch their playlists, display album art as game textures, and tie the controls of the service's player to the game UI.

Podcast and music hybrid apps. Combine podcast RSS feeds with a user's music library in a single player experience. Use MusicAPI for the music layer and your own feeds for podcasts, in one interface of your own.

FAQ

What is a music player API?

A music player API is a programmatic interface that gives developers access to streaming music data: track metadata, search, user playlists, liked songs, and playback preview URLs. Instead of building direct integrations with each streaming platform, you call a REST API and receive structured JSON responses with the track information your application needs.

Can I build a music player with multiple streaming services?

Yes. With a unified API like MusicAPI, you connect once and access data from 11 streaming services through the same endpoints. Users authenticate with whichever service they use, and your code stays the same regardless of the source.

How do I handle authentication for a music player?

MusicAPI provides a single hosted sign-in that works across all supported streaming services. You send users to the sign-in URL, they log in with their streaming account, and your backend receives an integrationUserUUID for the library calls. You do not write an OAuth flow per service. Full-track playback is separate: the service's playback SDK runs its own sign-in.

What data does a music player API return?

Track responses include the track name, artist names, album name, duration (in milliseconds), album artwork URL, preview URL (when the service gives one), ISRC code, and a direct link to the track on its source service. Playlist and library endpoints return similar structured data with pagination support. See the full endpoint reference for complete response schemas.

Is MusicAPI free to start with?

Every new account starts as an evaluation (sandbox) account with up to 5 connected users, so you can test the integration and explore the endpoints before you go live. Check the pricing page for current plan details and rate limits.

How do I handle rate limiting in my music player?

MusicAPI handles rate limiting at the service level so you do not hit individual platform limits directly. Cache track metadata on your end for data you display repeatedly (album art, track names) and use pagination parameters to avoid fetching more data than your UI needs at once.

Start Building Your Music Player

A custom audio player gives your users the experience they want, with the streaming service they already use. MusicAPI provides the data layer: normalized track metadata, cross-service search, user libraries, and a single sign-in for 11 services. The audio itself comes from the streaming service's SDK or embed.

Ready to skip months of OAuth and SDK work? Create your MusicAPI account and connect 11 streaming services with one API.