PHP LogoMusic Playlist

A music playlist is a curated collection of audio tracks, typically songs, arranged for sequential or randomized playback. It serves as a fundamental feature in most music players and streaming services, allowing users to organize their music library, create themed listening experiences, or simply enjoy continuous playback without manual selection for each track.

Key functionalities of a music playlist often include:

1. Adding Songs: Users can add individual songs or entire albums to a playlist.
2. Removing Songs: Songs can be removed from a playlist at any time.
3. Reordering Songs: The order of songs within a playlist can usually be changed, allowing users to create specific listening flows.
4. Playback Control: Playlists provide mechanisms for playing the current song, skipping to the next or previous song, pausing, resuming, and stopping playback.
5. Shuffling: This feature randomizes the order of songs in the playlist for varied listening.
6. Looping/Repeating: Options to repeat the current song or the entire playlist.
7. Current Song Tracking: The playlist system keeps track of which song is currently playing or is next in the queue.

In a programming context, a music playlist can be implemented using data structures like arrays or linked lists to store song information. Each 'song' could be represented as an object or an associative array containing details such as title, artist, album, file path/URL, and duration. The playlist object/class would then manage this collection of songs and provide methods for the functionalities mentioned above.

Example Code

<?php

class MusicPlaylist {
    private array $songs = [];
    private int $currentSongIndex = -1; // -1 indicates no song is selected initially

    /
     * Adds a song to the playlist.
     * @param string $title The title of the song.
     * @param string $artist The artist of the song.
     * @param string $album The album the song belongs to.
     * @param int $duration The duration of the song in seconds.
     */
    public function addSong(string $title, string $artist, string $album, int $duration): void
    {
        $this->songs[] = [
            'title' => $title,
            'artist' => $artist,
            'album' => $album,
            'duration' => $duration
        ];
        // If this is the first song added, set it as the current song
        if (count($this->songs) === 1) {
            $this->currentSongIndex = 0;
        }
        echo "Added: \"{$title}\" by {$artist}\n";
    }

    /
     * Removes a song from the playlist by its index.
     * @param int $index The 0-based index of the song to remove.
     */
    public function removeSong(int $index): void
    {
        if (isset($this->songs[$index])) {
            $removedSong = $this->songs[$index]['title'];
            array_splice($this->songs, $index, 1);
            echo "Removed: \"{$removedSong}\" from the playlist.\n";

            // Adjust current song index if necessary
            if ($this->currentSongIndex === $index) {
                if (!empty($this->songs)) {
                    $this->currentSongIndex = min($index, count($this->songs) - 1); // Move to next or last song
                } else {
                    $this->currentSongIndex = -1; // Playlist is empty
                }
            } elseif ($this->currentSongIndex > $index) {
                $this->currentSongIndex--; // Shift index if a song before it was removed
            }
        } else {
            echo "Error: Song at index {$index} not found.\n";
        }
    }

    /
     * Displays all songs in the playlist.
     */
    public function listSongs(): void
    {
        if (empty($this->songs)) {
            echo "Playlist is empty.\n";
            return;
        }
        echo "\n--- Current Playlist ---\n";
        foreach ($this->songs as $index => $song) {
            $isCurrent = ($index === $this->currentSongIndex) ? " (Playing)" : "";
            echo "{$index}. \"{$song['title']}\" by {$song['artist']} ({$song['duration']}s){$isCurrent}\n";
        }
        echo "-----------------------\n";
    }

    /
     * Plays the current song.
     */
    public function playCurrentSong(): void
    {
        if ($this->currentSongIndex !== -1 && isset($this->songs[$this->currentSongIndex])) {
            $song = $this->songs[$this->currentSongIndex];
            echo "Now playing: \"{$song['title']}\" by {$song['artist']}.\n";
        } else {
            echo "No song selected or playlist is empty.\n";
        }
    }

    /
     * Advances to the next song in the playlist.
     */
    public function nextSong(): void
    {
        if (empty($this->songs)) {
            echo "Playlist is empty. Cannot go to the next song.\n";
            return;
        }
        if ($this->currentSongIndex < count($this->songs) - 1) {
            $this->currentSongIndex++;
            $this->playCurrentSong();
        } else {
            echo "End of playlist. No next song.\n";
            // Option to loop back to the beginning: $this->currentSongIndex = 0; $this->playCurrentSong();
        }
    }

    /
     * Goes back to the previous song in the playlist.
     */
    public function previousSong(): void
    {
        if (empty($this->songs)) {
            echo "Playlist is empty. Cannot go to the previous song.\n";
            return;
        }
        if ($this->currentSongIndex > 0) {
            $this->currentSongIndex--;
            $this->playCurrentSong();
        } else {
            echo "Beginning of playlist. No previous song.\n";
            // Option to loop to the end: $this->currentSongIndex = count($this->songs) - 1; $this->playCurrentSong();
        }
    }

    /
     * Shuffles the songs in the playlist randomly.
     */
    public function shuffle(): void
    {
        if (empty($this->songs)) {
            echo "Playlist is empty. Nothing to shuffle.\n";
            return;
        }
        // Store the currently playing song to try and maintain its position or find it after shuffle
        $currentSong = $this->getCurrentSong();

        shuffle($this->songs);
        echo "Playlist shuffled.\n";

        // Try to find the previously current song's new index
        if ($currentSong) {
            foreach ($this->songs as $index => $song) {
                if ($song['title'] === $currentSong['title'] && $song['artist'] === $currentSong['artist']) {
                    $this->currentSongIndex = $index;
                    break;
                }
            }
        } else {
            $this->currentSongIndex = 0; // If no song was playing, default to the first after shuffle
        }
    }

    /
     * Gets the currently playing song's details.
     * @return array|null The song details or null if no song is playing.
     */
    public function getCurrentSong(): ?array
    {
        if ($this->currentSongIndex !== -1 && isset($this->songs[$this->currentSongIndex])) {
            return $this->songs[$this->currentSongIndex];
        }
        return null;
    }
}

// --- Example Usage ---
echo "=== Creating a Music Playlist ===\n";
$myPlaylist = new MusicPlaylist();

$myPlaylist->addSong("Bohemian Rhapsody", "Queen", "A Night at the Opera", 355);
$myPlaylist->addSong("Hotel California", "Eagles", "Hotel California", 390);
$myPlaylist->addSong("Stairway to Heaven", "Led Zeppelin", "Led Zeppelin IV", 482);
$myPlaylist->addSong("Smells Like Teen Spirit", "Nirvana", "Nevermind", 301);
$myPlaylist->addSong("Imagine", "John Lennon", "Imagine", 181);

$myPlaylist->listSongs();
$myPlaylist->playCurrentSong(); // Should play the first song

echo "\n=== Navigating Playlist ===\n";
$myPlaylist->nextSong(); // Play next
$myPlaylist->nextSong(); // Play next
$myPlaylist->previousSong(); // Play previous

echo "\n=== Modifying Playlist ===\n";
$myPlaylist->removeSong(1); // Remove 'Hotel California'
$myPlaylist->listSongs(); // List updated playlist
$myPlaylist->playCurrentSong(); // Show what's playing after removal

echo "\n=== Shuffling Playlist ===\n";
$myPlaylist->shuffle();
$myPlaylist->listSongs();
$myPlaylist->playCurrentSong();

echo "\n=== Edge Cases ===\n";
$emptyPlaylist = new MusicPlaylist();
$emptyPlaylist->listSongs();
$emptyPlaylist->nextSong();
$emptyPlaylist->shuffle();

?>