Vibe coding with Claude Code course Β· Module 11: Spotify clone

The Player and the Queue: A Request with a Finish Line

12 min read
In this lesson9

Ahoy! The crew sings shanties at every watch, but the recordings sit in a folder on the ship's computer and every one has to be started by hand. In this location you build Sea Shanty Sounds, a Spotify clone: a player with a queue, playlists and a search. You start with the player because it is the trickiest piece of the clone. It looks finished after the first click on Play, and the trouble only begins when a track ends on its own.

What you will learn

  • add a finish line to a request, a check that Claude can run by itself;
  • read in Cursor a player whose state listens to audio events, not to clicks;
  • spot two sources of truth and a button that says "Pause" while nothing is playing;
  • ask a side question with /btw that does not clutter the conversation.

A new port: the sea-shanty-sounds project

Sea Shanty Sounds is a separate app, so you create it with the command from lesson 1_2, changing only the name. Before you click Yes, compare the command with this one:

npx create-next-app@latest sea-shanty-sounds --ts --eslint --tailwind --app --no-src-dir --no-cache-components --agents-md --no-agent-feedback --use-npm

Then the familiar routine: a session in the sea-shanty-sounds folder, a CLAUDE.md that imports @AGENTS.md, Vitest with the @types/node fix from lesson 4_1, and a first commit. For the player you need a few sound files in public/audio/. If you have the ffmpeg program, ask Claude for four MP3 files with a clean tone, each with a different pitch and length, the first one exactly 125 seconds long. Without ffmpeg, ask for the same tones as WAV files: it is a simple format that Claude writes with a short Node.js script without extra programs, and the <audio> element plays it in the major browsers. A different tone in each file lets you hear which track is playing.

The finish line

Claude Code best practices say it plainly: Claude stops when the work looks finished. If nothing answers "pass" or "fail", you are left as its only test. A player is the perfect example: after a click on Play everything works, and the bug shows up two minutes later, when a track ends.

That is why the request ends with a list of conditions under the heading "Done when:". Each condition can be checked with a test or a command, not with a verdict of "looks good". The documentation lists this as the first and lightest way: the condition sits in the request itself and Claude judges when it is met, so you still ask for proof. You will meet the stronger levels in lesson 10_4. The step is big, so you start with a plan, as in lesson 1_6.

Request for Claude Code:

/plan Build the Sea Shanty Sounds player. Track, Artist and Album types
in types/music.ts, four tracks from public/audio in lib/catalog.ts,
components MusicPlayer.tsx and Queue.tsx: play and pause, previous and
next, a progress bar with seeking, volume, mute, shuffle and repeat
(off, all, one). The queue shows what is playing and what comes next.
Keep shuffle and repeat in one place, format time with one function
in lib/format.ts.
Done when:
1. formatTime(125) returns "2:05" and formatTime(NaN) returns "0:00";
2. the button shows "Pause" only when the audio is really playing,
   also when a track ends on its own or the audio stops without
   a click on the button;
3. when a track ends the next one plays, and with repeat all the first
   one plays after the last;
4. a rejected play() shows a message instead of pretending to play.
Check conditions 1-4 with Vitest tests, then npm run lint,
npx tsc --noEmit and npm run build. Show the commands and their results.

Condition 2 is the catch. The simplest code an agent can write flips the label on the button at the click, so condition 2 forces a different design: the state of the player must come from what the <audio> element does. Read the plan and check whether it says how the button learns that a track has ended. If you want the full discipline from lesson 4_1, add: "First write the tests for conditions 1-4 and show that they fail".

What Claude wrote: the types and one formatter

Open types/music.ts in Cursor. A track holds its artist and album as objects, the path to the file and the length in seconds:

export interface Track {
  id: string;
  title: string;
  artist: Artist;
  album: Album;
  src: string; // "/audio/hymn.mp3"
  duration: number; // in seconds
  genre: Genre;
}

genre is a genre from a short list, and it will come in handy in lesson 10_3 for recommendations. Time on the screen goes through one function from lib/format.ts:

export function formatTime(seconds: number): string {
  if (!Number.isFinite(seconds) || seconds < 0) return "0:00";
  const whole = Math.floor(seconds);
  const minutes = Math.floor(whole / 60);
  const rest = whole % 60;
  return `${minutes}:${String(rest).padStart(2, "0")}`;
}

padStart(2, "0") adds a zero at the front, so 5 seconds becomes "05". The first line is not excessive caution: according to MDN, the duration property of an audio element returns NaN until the browser has loaded the file data, and Infinity for a live stream. Without that line the bar would show "NaN:NaN". In our run the test returned "2:05" for 125 seconds and "0:00" for NaN.

What Claude wrote: state listens to the audio

Open components/MusicPlayer.tsx. The most important piece is the effect that hooks into the events of the <audio> element, the messages the player sends by itself:

useEffect(() => {
  const audio = audioRef.current;
  if (!audio) return;
  const syncPlaying = () => setIsPlaying(!audio.paused);
  const syncTime = () => setCurrentTime(audio.currentTime);
  audio.addEventListener("play", syncPlaying);
  audio.addEventListener("pause", syncPlaying);
  audio.addEventListener("emptied", syncPlaying);
  audio.addEventListener("timeupdate", syncTime);
  return () => {
    audio.removeEventListener("play", syncPlaying);
    audio.removeEventListener("pause", syncPlaying);
    audio.removeEventListener("emptied", syncPlaying);
    audio.removeEventListener("timeupdate", syncTime);
  };
}, []);

isPlaying changes only here, always to what audio.paused says. According to MDN the pause event arrives when paused is already true, and timeupdate arrives several times a second while playing (MDN gives roughly 4 to 66 times). At the end of a track pause comes first and then ended: that is how the HTML specification describes it, and that is what happened in our browser. emptied has a reason: when the file changed, the browser stopped the old track without a pause event and sent only abort and emptied. The version without emptied showed "Pause" for us after a jump to a broken file, although nothing was playing.

The return with a cleanup function detaches every listener when the player leaves the page. The real code also has a loadedmetadata listener that saves the track length once the browser knows it.

What Claude wrote: the button only asks

The Play button does not set the state. It asks the audio element to change, and the state catches up with reality through events:

function togglePlay() {
  const audio = audioRef.current;
  if (!audio) return;
  if (audio.paused) {
    setAutoPlay(true);
    audio.play().catch(() => setError("The browser did not allow playback. Click Play again."));
  } else {
    audio.pause();
  }
}

According to MDN, play() returns a promise that the browser rejects when it does not allow playback, for example with a NotAllowedError, and a page should not show an interface that assumes playback started. You know this from the feed in lesson 9_1. Here the rejection leaves the Play label in place, because the play event never came, and shows a message. autoPlay is the state of the autoPlay attribute on <audio>: from the first click on Play every new track starts by itself once the browser has loaded it.

What Claude wrote: the queue and repeat

The repeat modes and the choice of the next track live in pure functions in lib/queue.ts, so they are easy to test. The RepeatMode type comes from the array of modes: as const keeps three exact strings in it, and (typeof REPEAT_MODES)[number] gathers them into the type "off" | "all" | "one", so the function will not accept a typo:

export const REPEAT_MODES = ["off", "all", "one"] as const;
export type RepeatMode = (typeof REPEAT_MODES)[number];

export function nextIndex(current: number, length: number, repeat: RepeatMode): number | null {
  if (current + 1 < length) return current + 1;
  return repeat === "all" ? 0 : null;
}

The repeat button walks through the array in a circle: off, all, one and off again. null means "end of the queue, nothing plays any more", and with repeat all, index 0 comes back after the last track. Repeating one track is done by the browser itself through the loop={repeat === "one"} attribute. MDN says that with loop on, the ended event never arrives at all: for us the track went back to the start at its end with no pause and no ended.

There is no shuffle in nextIndex, and it should stay that way. The same file holds a shuffled function that shuffles a copy of the list and leaves the original alone, which a separate test checks. Clicking Shuffle puts the playing track at the start of the queue, shuffles the rest behind it and sets the index to 0, so the music does not stop and nextIndex still goes in order. A second click brings back the catalog order and finds the playing track in it. Look for exactly this when you read the code: shuffle changes the queue once and does not pick a new track at every end, because then the same track could play twice in a row.

The move after a track ends is handled by a separate effect:

useEffect(() => {
  const audio = audioRef.current;
  if (!audio) return;
  function handleEnded() {
    const next = nextIndex(index, queue.length, repeat);
    if (next !== null) setIndex(next);
  }
  audio.addEventListener("ended", handleEnded);
  return () => audio.removeEventListener("ended", handleEnded);
}, [index, queue.length, repeat]);

The dependencies are plain numbers and a string, so the effect attaches a fresh listener only when the track, the queue length or the mode changes. The state of shuffle and repeat lives only in MusicPlayer. Queue gets the queue and the index in props, shows "Now playing" and the "Up next" list, which is queue.slice(index + 1), and the Remove button stands only next to tracks that have yet to play. Removing them therefore never shifts the index of the track that is playing. Volume is a slider from 0 to 1, because according to MDN that is exactly the range volume accepts.

Captain's review

  1. State from the click. A typical agent mistake is setIsPlaying(!isPlaying) in togglePlay and not a single play or pause listener. For us that version passed lint and tsc, and the test from condition 2 failed: Unable to find role="button" and name "Play". Search the file (Cmd+F on a Mac, Ctrl+F on Windows) for setIsPlaying(: the only hit should sit in the event listener.
  2. One source of truth. Search the project (Cmd+Shift+F) for useState<RepeatMode>. Two hits, for example in MusicPlayer and in a parent with an onRepeat function, are two copies of the same state: the button shows one and the player does the other.
  3. Cleanup. Every addEventListener in an effect has its removeEventListener in the return. Count the hits of both names.
  4. One formatter. You find padStart only in lib/format.ts. A second, almost identical formatter in Queue.tsx is a copy that will one day start counting differently.
  5. Proof. The test and build results in Claude's answer are the first proof, and you check the second one in the browser. Run npm run dev, click Play, open the developer tools and type document.querySelector("audio").pause() in the console. The button must change to Play although you did not click it.

These points will come back with every later player. When you repeat them for the third time, save them as your own reviewer subagent, like video-reviewer from lesson 9_5.

Next step

If something in the code surprised you, you do not have to add it to the conversation. The Claude Code documentation describes /btw as a question about the current work that does not go into the conversation history:

/btw why does the handleEnded effect have the dependencies [index, queue.length, repeat]?

Claude answers from what is already in the conversation, that is from the code it wrote itself. It has no tools for this: it does not read files and does not run commands. The answer appears in an overlay that you close with Space, Enter or Escape, and /btw works even while Claude is in the middle of a task. When you need something new from the project, you need a subagent, and you will return to that in lesson 10_3.

When the tests and the browser agree, ask for a commit, for example "Player and queue". In the editor below a miniature player is waiting, with fake sound that counts seconds. End a track with the button, stop it "from outside", then turn on the agent bug and compare the label on the button with what is really playing.

Remember: the captain's music box plays as long as someone is listening to the notes, not as long as the gears look pretty, and a player button must say what you hear, not what somebody clicked.

Code for this lesson: App.jsx
// Player in miniature: fake audio counts seconds and fires events like <audio>
import { useEffect, useState } from 'react';

const tracks = [
  { id: 't1', title: 'Pirate Hymn', duration: 8 },
  { id: 't2', title: 'Battle Drums', duration: 6 },
  { id: 't3', title: 'Island Shanty', duration: 10 },
  { id: 't4', title: "Kraken's Song", duration: 5 },
];

const REPEAT_MODES = ['off', 'all', 'one'];
const REPEAT_LABELS = { off: 'Repeat: off', all: 'Repeat: all', one: 'Repeat: one' };

// One time formatter for the whole player
function formatTime(seconds) {
  if (!Number.isFinite(seconds) || seconds < 0) return '0:00';
  const whole = Math.floor(seconds);
  return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, '0')}`;
}

function nextIndex(current, length, repeat) {
  if (current + 1 < length) return current + 1;
  return repeat === 'all' ? 0 : null;
}

export default function App() {
  const [index, setIndex] = useState(0);
  const [audio, setAudio] = useState({ paused: true, time: 0 }); // fake <audio> element
  const [isPlaying, setIsPlaying] = useState(false); // what the button shows
  const [autoPlay, setAutoPlay] = useState(false);
  const [repeat, setRepeat] = useState('off');
  const [log, setLog] = useState([]);
  const [error, setError] = useState('');
  const [agentBug, setAgentBug] = useState(false);
  const [blockPlay, setBlockPlay] = useState(false);
  const track = tracks[index];

  // An event from the fake audio. Without the agent bug the button listens to play, pause and emptied.
  function emit(name, paused) {
    setLog((l) => [`${name} (paused = ${paused})`, ...l].slice(0, 8));
    if (!agentBug && ['play', 'pause', 'emptied'].includes(name)) setIsPlaying(!paused);
  }

  function playAudio() {
    if (blockPlay) {
      // play() rejected (NotAllowedError): no play event
      if (!agentBug) setError('The browser did not allow playback. Click Play again.');
      return;
    }
    setError('');
    setAutoPlay(true);
    setAudio((a) => ({ ...a, paused: false }));
    emit('play', false);
  }

  function pauseAudio() {
    setAudio((a) => ({ ...a, paused: true }));
    emit('pause', true);
  }

  function startTrack(i, play) {
    setIndex(i);
    emit('emptied', true); // file changed: paused = true without a pause event
    if (play && !blockPlay) {
      setAudio({ paused: false, time: 0 });
      emit('play', false);
    } else {
      setAudio({ paused: true, time: 0 });
    }
  }

  function togglePlay() {
    if (agentBug) {
      // agent bug: the button flips its own label and does not listen to the audio
      if (isPlaying) pauseAudio();
      else playAudio();
      setIsPlaying(!isPlaying);
      return;
    }
    if (audio.paused) playAudio();
    else pauseAudio();
  }

  // Clock of the fake audio: adds a second every second, at the end of a track fires pause and ended
  useEffect(() => {
    if (audio.paused) return;
    const id = setTimeout(() => {
      const time = audio.time + 1;
      if (time < track.duration) {
        setAudio({ paused: false, time });
      } else if (repeat === 'one') {
        setAudio({ paused: false, time: 0 }); // loop: no pause and no ended
      } else {
        setAudio({ paused: true, time: track.duration });
        emit('pause', true);
        emit('ended', true);
        const next = nextIndex(index, tracks.length, repeat);
        if (next !== null) startTrack(next, autoPlay);
      }
    }, 1000);
    return () => clearTimeout(id);
  }, [audio, index, repeat, agentBug, autoPlay, blockPlay]);

  const reallyPlaying = !audio.paused;
  const lying = isPlaying !== reallyPlaying;

  return (
    <div className="min-h-screen bg-gray-950 p-4 text-white">
      <div className="mx-auto max-w-xl space-y-4">
        <div className="rounded-xl bg-gray-900 p-4">
          <p className="text-lg font-semibold">{track.title}</p>
          <div className="mt-3 flex flex-wrap items-center gap-2">
            <button type="button" onClick={() => startTrack(Math.max(0, index - 1), autoPlay)} className="rounded bg-gray-700 px-3 py-1">Previous</button>
            <button type="button" onClick={togglePlay} className="rounded-full bg-white px-5 py-2 font-semibold text-black">
              {isPlaying ? 'Pause' : 'Play'}
            </button>
            <button type="button" onClick={() => { const n = nextIndex(index, tracks.length, repeat); if (n !== null) startTrack(n, autoPlay); }} className="rounded bg-gray-700 px-3 py-1">Next</button>
            <button type="button" onClick={() => setRepeat(REPEAT_MODES[(REPEAT_MODES.indexOf(repeat) + 1) % REPEAT_MODES.length])} className="rounded bg-gray-700 px-3 py-1 text-sm">
              {REPEAT_LABELS[repeat]}
            </button>
          </div>
          <p className="mt-3 text-sm text-gray-300">
            {formatTime(audio.time)} / {formatTime(track.duration)}
          </p>
          {error && <p className="mt-2 text-sm text-red-400">{error}</p>}
        </div>

        <div className={`rounded-xl p-3 text-sm ${lying ? 'bg-red-900' : 'bg-gray-800'}`}>
          <p>Audio really: <strong>{reallyPlaying ? 'playing' : 'stopped'}</strong>. The button says: <strong>{isPlaying ? 'Pause' : 'Play'}</strong>.</p>
          {lying && <p className="mt-1 font-semibold">The button lies: it shows something other than what you hear.</p>}
        </div>

        <div className="flex flex-wrap gap-2 text-sm">
          <button type="button" onClick={() => setAudio((a) => ({ ...a, time: Math.max(0, track.duration - 2) }))} className="rounded bg-gray-700 px-3 py-1">Skip to the end</button>
          <button type="button" onClick={pauseAudio} className="rounded bg-gray-700 px-3 py-1">Stop from outside</button>
        </div>

        <div className="rounded-xl bg-gray-900 p-3 text-sm">
          <p className="text-gray-400">Now playing</p>
          <p>{track.title}</p>
          <p className="mt-2 text-gray-400">Up next</p>
          {tracks.slice(index + 1).length === 0 && <p className="text-gray-500">The queue is empty.</p>}
          <ol>
            {tracks.slice(index + 1).map((t, i) => (
              <li key={t.id}>
                <button type="button" onClick={() => startTrack(index + 1 + i, true)} className="hover:underline">
                  {t.title} ({formatTime(t.duration)})
                </button>
              </li>
            ))}
          </ol>
        </div>

        <div className="space-y-1 text-sm">
          <label className="flex items-center gap-2">
            <input type="checkbox" checked={agentBug} onChange={(e) => setAgentBug(e.target.checked)} />
            Agent bug: setIsPlaying(!isPlaying) instead of events
          </label>
          <label className="flex items-center gap-2">
            <input type="checkbox" checked={blockPlay} onChange={(e) => setBlockPlay(e.target.checked)} />
            The browser rejects play() (NotAllowedError)
          </label>
        </div>

        <div className="rounded-xl bg-black p-3 font-mono text-xs text-green-400">
          <p className="text-gray-400">Audio events (newest on top):</p>
          {log.map((line, i) => <p key={i}>{line}</p>)}
        </div>
      </div>
    </div>
  );
}

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Why does a request for Claude Code end with a list headed "Done when:"?

  2. 2. What does formatTime(NaN) return in the player from the lesson, and where does NaN come from?

These are 2 of 7 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Horizontal ordering

    Arrange in one line the playback call with rejection handling:

  • Horizontal ordering

    Arrange in one line the computation of the tracks that will play after the current one:

  • Code editor

    Music player component

  • Click in order

    Click the pieces to build the condition from togglePlay that checks whether the audio is stopped:

  • Click in order

    Click the pieces to build the function that sets the button state from the audio element:

  • Horizontal ordering

    Arrange in one line setting the volume of the audio element to half:

  • Vertical ordering

    Arrange the repeat modes the way they stand in the REPEAT_MODES array that the button walks through:

  • Horizontal ordering

    Arrange in one line the return statement of formatTime:

  • Click in order

    Click the pieces to attach the progress listener:

  • Code editor

    Queue management interface

  • Vertical ordering

    Arrange what happens at the end of a track with repeat off when there is a next one in the queue:

  • Vertical ordering

    Arrange the lines of the effect that moves to the next track:

  1. QuestionThe finish line
  2. QuestionLength of an unknown track
  3. Put in orderplay() with rejection handling
  4. Put in orderThe Up next list in the queue
  5. Coding taskPractice: Music player UI
  6. QuestionThe Play button only asks
  7. Click in orderThe audio.paused condition
  8. Click in orderState from audio.paused
  9. QuestionThe side question /btw
  10. Put in orderVolume from 0 to 1
  11. Put in orderOrder of the repeat modes
  12. QuestionRepeat all
  13. Put in orderSeconds with a leading zero
  14. Click in orderBuild the timeupdate addEventListener
  15. Coding taskPractice: Queue component
  16. QuestionRepeating one track
  17. Put in orderThe end of a track step by step
  18. Put in orderThe effect with the ended listener
  19. QuestionRemoving from the queue

Useful articles