Design an Audio Player Core with Queue Management and Shuffle Logic
Data Structure DesignModel answerLast updated
Architect the object-oriented structure and state machine for a media player featuring play/pause controls, queue prioritization, looping modes, and deterministic shuffle handling.
Design the core object models, state transitions, and playback policies for a media player application.
Your solution should support the following operations and features:
- Core Controls:
play(),pause(), andnext(). - Track Queueing: User-queued tracks that take precedence over normal playlist progression.
- Looping Modes: Support for standard playback (stop at end), loop single track, and loop playlist/queue.
- Shuffle Playback: Randomization that visits each remaining item without immediate duplication while preserving history for navigation.
- Hardware Decoupling: Interfaces that decouple playback logic from audio output devices (allowing for stubbed testing).
Operational Rules & Assumptions
- Tracks are unique domain objects; identical metadata (e.g., song title) does not imply track identity. A single track instance can appear multiple times in a playlist.
- Explicitly define queue priority: User "play next" additions must take precedent over the default playlist sequence.
- State handling must account for async events, such as track completion notifications emitted by the underlying audio driver interface.
- Threading and network streaming can be simplified to a single-threaded local model, but asynchronous callbacks from the audio hardware driver must be handled safely.
Hints
Hint 1
Consider using a state pattern or explicit state enum (e.g., PLAYING, PAUSED, STOPPED) to govern how commands like play() or next() behave.
Hint 2
Separate the user-queued tracks (priority queue / explicit buffer) from the underlying playlist sequence.
Hint 3
To make shuffle testable, inject a random seed or randomizer dependency into the shuffle logic rather than relying directly on system randomness.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Architectural Overview
An effective design decouples the high-level player logic, state management, queue progression algorithm, and low-level hardware output into clearly defined components:
Track: Value object holding track metadata, absolute URI, and unique identifier (UUID).AudioBackend: Interface abstracting native media playback hardware or audio decoding libraries.PlaybackQueue: Encapsulates play order, user-queued tracks, history stacks, and shuffle states.MediaPlayer: Main controller managing the player state machine, handling user events, and receiving execution callbacks fromAudioBackend.
Class Specifications & Models
1. Audio Backend Interface
from abc import ABC, abstractmethod
class AudioBackendListener(ABC):
@abstractmethod
def on_track_completed(self, track_id: str) -> None:
"""Triggered asynchronously when the backend finishes playing a track."""
pass
@abstractmethod
def on_track_error(self, track_id: str, error: Exception) -> None:
"""Triggered if track loading or decoding fails."""
pass
class AudioBackend(ABC):
@abstractmethod
def load_and_play(self, uri: str, track_id: str) -> None:
pass
@abstractmethod
def pause(self) -> None:
pass
@abstractmethod
def resume(self) -> None:
pass
@abstractmethod
def stop(self) -> None:
pass
@abstractmethod
def set_listener(self, listener: AudioBackendListener) -> None:
pass
2. Queue & Loop Policy Management
We support three loop modes:
NO_LOOP: Stop after reaching the end of the queue.REPEAT_ONE: Replay the current track continuously on completion.REPEAT_ALL: Wrap around to the beginning of the queue once exhausted.
import random
from enum import Enum
from typing import List, Optional
import uuid
class LoopMode(Enum):
NO_LOOP = 1
REPEAT_ONE = 2
REPEAT_ALL = 3
class Track:
def __init__(self, title: str, duration_sec: int, uri: str):
self.id: str = str(uuid.uuid4())
self.title: str = title
self.duration_sec: int = duration_sec
self.uri: str = uri
class PlaybackQueue:
def __init__(self, random_generator=random.Random()):
self._playlist: List[Track] = []
self._user_queue: List[Track] = [] # Priority manual "Play Next" tracks
self._history: List[Track] = []
self.current_track: Optional[Track] = None
self.loop_mode: LoopMode = LoopMode.NO_LOOP
self.is_shuffled: bool = False
self._shuffled_order: List[int] = []
self._shuffled_cursor: int = 0
self._playlist_cursor: int = 0
self._rng = random_generator
def set_playlist(self, tracks: List[Track]) -> None:
self._playlist = list(tracks)
self._playlist_cursor = 0
self._shuffled_cursor = 0
if self.is_shuffled:
self._rebuild_shuffle_indices()
def enqueue_user_track(self, track: Track) -> None:
"""User manually queued track; plays before standard playlist items."""
self._user_queue.append(track)
def set_shuffle(self, enabled: bool) -> None:
if self.is_shuffled == enabled:
return
self.is_shuffled = enabled
if enabled:
self._rebuild_shuffle_indices()
def _rebuild_shuffle_indices(self) -> None:
self._shuffled_order = list(range(len(self._playlist)))
self._rng.shuffle(self._shuffled_order)
self._shuffled_cursor = 0
def get_next_track(self) -> Optional[Track]:
# Handle REPEAT_ONE
if self.current_track and self.loop_mode == LoopMode.REPEAT_ONE:
return self.current_track
# Save previous track to history
if self.current_track:
self._history.append(self.current_track)
# 1. User manual queue takes top priority
if len(self._user_queue) > 0:
self.current_track = self._user_queue.pop(0)
return self.current_track
if not self._playlist:
self.current_track = None
return None
# 2. Shuffled Playlist Traversal
if self.is_shuffled:
if self._shuffled_cursor < len(self._shuffled_order):
idx = self._shuffled_order[self._shuffled_cursor]
self._shuffled_cursor += 1
self.current_track = self._playlist[idx]
return self.current_track
elif self.loop_mode == LoopMode.REPEAT_ALL:
self._rebuild_shuffle_indices()
idx = self._shuffled_order[0]
self._shuffled_cursor = 1
self.current_track = self._playlist[idx]
return self.current_track
# 3. Standard Sequential Traversal
else:
if self._playlist_cursor < len(self._playlist):
self.current_track = self._playlist[self._playlist_cursor]
self._playlist_cursor += 1
return self.current_track
elif self.loop_mode == LoopMode.REPEAT_ALL:
self._playlist_cursor = 0
self.current_track = self._playlist[0]
self._playlist_cursor = 1
return self.current_track
self.current_track = None
return None
3. Main Controller & State Machine
The player transitions across 3 main states: STOPPED, PLAYING, and PAUSED.
class PlayerState(Enum):
STOPPED = 1
PLAYING = 2
PAUSED = 3
class MediaPlayer(AudioBackendListener):
def __init__(self, audio_backend: AudioBackend):
self.backend = audio_backend
self.backend.set_listener(self)
self.queue = PlaybackQueue()
self.state = PlayerState.STOPPED
def play(self) -> None:
if self.state == PlayerState.PAUSED:
self.backend.resume()
self.state = PlayerState.PLAYING
elif self.state == PlayerState.STOPPED:
next_track = self.queue.get_next_track()
if next_track:
self.state = PlayerState.PLAYING
self.backend.load_and_play(next_track.uri, next_track.id)
def pause(self) -> None:
if self.state == PlayerState.PLAYING:
self.backend.pause()
self.state = PlayerState.PAUSED
def next(self) -> None:
next_track = self.queue.get_next_track()
if next_track:
self.state = PlayerState.PLAYING
self.backend.load_and_play(next_track.uri, next_track.id)
else:
self.backend.stop()
self.state = PlayerState.STOPPED
def on_track_completed(self, track_id: str) -> None:
# Ignore stale callbacks if track ID does not match current state
if self.queue.current_track and self.queue.current_track.id != track_id:
return
# Advance automatically when playback completes
self.next()
def on_track_error(self, track_id: str, error: Exception) -> None:
# Graceful recovery: log error and attempt to skip to next track
self.next()
Key Edge Cases & Design Trade-offs
-
Race Conditions & Stale Callbacks: When a user clicks
next()rapidly, the audio driver might still emit anon_track_completedevent for an older track. Matching uniquetrack_idvalues inside completion handlers prevents double-skipping. -
Deterministic Shuffle Testing: By injecting
random_generator(random.Random(seed)), test suites can verify shuffle order deterministically without flakiness. -
Track Uniqueness vs. Metadata Matching: Using
UUIDinstances per Track entry prevents collision bugs when the same song file is added multiple times to a single playlist. -
Time & Space Complexity:
get_next_track()runs in $O(1)$ time.- Enabling shuffle incurs an initial $O(N)$ index-shuffling overhead where $N$ is playlist length.