← Blog

BLOG

Find Song Used in YouTube Video: Automate It with a Remote Browser

Learn how to find the song used in a YouTube video with Playwright and a hosted Chromium session, plus when manual tools are faster.

9 min readRemote Browser
Ivory computer towers connected across terracotta platforms in a quiet desert landscape
The infrastructure behind your browserREMOTE BROWSER / ILLUSTRATION

If you want to find the song used in a YouTube video, the fastest path for a single video is a manual tool: Shazam, AHA Music, or the YouTube "Music in this video" panel. But if you need to do this at scale — a content moderation pipeline, a licensing audit, a music discovery product, or an agent that processes a large batch of links — you need a programmatic path. That path runs through a real browser session, because YouTube's music metadata is rendered client-side and the identification services you'd want to query are themselves browser-gated.

This guide covers how to find the song used in a YouTube video with code, why a hosted Chromium runtime is the right substrate for it, and the trade-offs you need to understand before you build. It is written for developers who already know Playwright or Puppeteer and want a production-shaped answer, not a list of consumer apps.

The short answer: three programmatic approaches

There are three realistic ways to identify music in a YouTube video from code. They differ in reliability, cost, and legal exposure.

ApproachHow it worksReliabilityBest for
YouTube's own metadataParse the "Music in this video" section, video description, or the ytInitialPlayerResponse JSON embedded in the pageHigh when the creator credited the track; zero otherwiseLicensed content, official uploads, music channels
Audio fingerprintingDownload the audio track, extract a fingerprint, query a service like AcoustID, AudD, or ACRCloudHigh for full-length tracks; degrades on short clips, live audio, or heavy processingUser-generated content, remixes, clips
Browser-based identificationLoad the video in a real browser, capture a short audio segment, submit it to a browser-driven identification flowMedium; depends on the service and the clip lengthCases where you cannot download audio or need a human-in-the-loop fallback

In practice, production systems combine the first two. The browser is the orchestration layer that makes both work reliably at scale, because both the YouTube page and most fingerprinting APIs sit behind bot detection, consent walls, and geo-gating that a headless HTTP client will not clear.

Why a real browser session matters

You might assume you can fetch() the YouTube watch page and regex out the metadata. Sometimes you can. In production you will hit three problems:

  1. Consent and region interstitials. YouTube serves a consent page in the EU and other regions before the watch page. The ytInitialPlayerResponse object is not present until consent is handled.
  2. Client-side rendering. The "Music in this video" panel is populated by a separate XHR after the player initializes. Scraping the initial HTML misses it.
  3. Bot detection. YouTube and most fingerprinting services fingerprint TLS, headers, and behavior. A plain HTTP client gets a challenge page; a real Chromium session with a persistent profile behaves like a returning user.

A hosted Chromium session solves all three. You get a real browser engine, a persistent profile that carries cookies and consent state across runs, and CDP access so Playwright or Puppeteer can drive it exactly as if it were local. If you are new to this pattern, the remote browser for AI agents overview covers the architecture; the rest of this post assumes you have a CDP endpoint.

Step 1: Extract YouTube's own music metadata

Start with the cheapest signal. YouTube embeds a structured JSON blob called ytInitialPlayerResponse in the watch page. It contains the video title, description, and — when the creator credited music — a videoDetails and sometimes a microformat block with music attribution.

The reliable way to get it is to let the page load fully, then read the global variable from the page context. Here is a Playwright script that connects to a hosted Chromium session over CDP, navigates to a video, and pulls the metadata:

import { chromium, Browser, Page } from 'playwright';

interface MusicAttribution {
  videoId: string;
  title: string;
  artist: string | null;
  source: 'youtube-metadata' | 'none';
}

async function extractYouTubeMusic(
  cdpEndpoint: string,
  videoId: string
): Promise<MusicAttribution> {
  const browser: Browser = await chromium.connectOverCDP(cdpEndpoint);
  const context = browser.contexts()[0] ?? (await browser.newContext());
  const page: Page = await context.newPage();

  try {
    await page.goto(`https://www.youtube.com/watch?v=${videoId}`, {
      waitUntil: 'domcontentloaded',
      timeout: 45_000,
    });

    // Handle the EU consent interstitial if present.
    const consent = page.locator('button[aria-label*="Accept"]');
    if (await consent.isVisible().catch(() => false)) {
      await consent.click();
      await page.waitForLoadState('networkidle');
    }

    // Wait for the player response to be populated.
    await page.waitForFunction(
      () => (window as any).ytInitialPlayerResponse?.videoDetails,
      { timeout: 30_000 }
    );

    const data = await page.evaluate(() => {
      const pr = (window as any).ytInitialPlayerResponse;
      const details = pr?.videoDetails ?? {};
      // The music panel is rendered separately; check the description
      // and the structured "Music in this video" section if present.
      const desc: string = details.shortDescription ?? '';
      const musicMatch = desc.match(/Music in this video[\s\S]{0,400}/i);
      return {
        title: details.title ?? '',
        description: desc,
        musicBlock: musicMatch ? musicMatch[0] : null,
      };
    });

    // Parse artist/title out of the music block. YouTube's format is
    // "Song\nArtist\nLicensed to YouTube by ..." — split on newlines.
    let artist: string | null = null;
    if (data.musicBlock) {
      const lines = data.musicBlock
        .split('\n')
        .map((l) => l.trim())
        .filter(Boolean);
      // lines[0] is the header, lines[1] the song, lines[2] the artist.
      artist = lines[2] ?? null;
    }

    return {
      videoId,
      title: data.title,
      artist,
      source: artist ? 'youtube-metadata' : 'none',
    };
  } finally {
    await page.close();
    await browser.close();
  }
}

Two things to note. First, connectOverCDP is the standard way to attach Playwright to a remote Chromium instance; the Playwright CDP documentation is the authoritative reference for the connection semantics. Second, the ytInitialPlayerResponse shape is undocumented and changes without notice — treat every field as optional and version your parser.

This approach returns a result for maybe 30–50% of videos in practice, depending on the corpus. Official music uploads and licensed content almost always have the panel; personal vlogs and gameplay clips usually do not.

Step 2: Fall back to audio fingerprinting

When the metadata is empty, you need to identify the audio itself. The pipeline is: get the audio, fingerprint it, query a service.

Getting the audio is the hard part. YouTube's terms of service prohibit downloading content, and the yt-dlp-style tools that do it are legally contested in many jurisdictions. If you are building a commercial product, talk to counsel before you ship an audio-download step. For internal tooling, research, or cases where you have rights to the content, the flow is:

  1. Extract the audio stream URL from the player response (streamingData.adaptiveFormats, filter for audio/).
  2. Download a short segment (30–60 seconds is enough for most fingerprinting services).
  3. Submit to a fingerprinting API — AcoustID (free, open), AudD, or ACRCloud (commercial, higher accuracy).

The browser's role here is to obtain the stream URL, which is signed and time-limited. You cannot construct it offline; you have to read it from the player response in a live session. That is another reason the hosted browser is the right substrate: the signed URL is bound to the session's IP and cookies, so a session that fetched the page can also fetch the stream.

If you cannot or will not download audio, the browser-based identification route is the fallback: load the video, play a segment, capture the audio via MediaRecorder in the page context, and submit the captured blob to an identification service. This is slower and less accurate, but it stays within the browser session and avoids a separate download step.

Step 3: Handle the failure cases

A production pipeline needs to handle the cases where neither approach returns a confident answer. The common ones:

  • Live streams and premieres. No stable audio track, no metadata. Skip or queue for later.
  • Covers and remixes. Fingerprinting returns the original composition, not the performance. Surface both and let the caller decide.
  • Multi-track videos. A single video may contain several songs. The metadata panel lists them; fingerprinting returns the dominant one. Parse the full panel, not just the first entry.
  • Region-locked videos. The watch page returns a "not available in your country" screen. Detect it and route through a proxy in an allowed region — a hosted runtime with configurable proxy settings handles this without code changes.
  • Consent walls that reappear. If your session does not persist cookies, you will re-solve consent on every run. Use a persistent profile.

Production criteria for the runtime

If you are going to run this at any volume, the browser runtime matters more than the parsing logic. Here is what to evaluate:

  • Persistent profiles. Consent state, cookies, and login sessions should survive across runs. A fresh profile per request means re-solving consent every time.
  • CDP access. You need connectOverCDP or the Puppeteer equivalent. Some hosted browsers only expose a proprietary API; that locks you into their client.
  • Session isolation. One video's cookies should not leak into another's. Isolated sessions per job are the safe default.
  • Configurable proxy and browser settings. Region-locked content and geo-gated fingerprinting services need per-session proxy configuration. Look for configurable browser settings rather than hardcoded defaults.
  • Live viewer. When a run fails, you need to see what the page looked like. A live viewer or session recording cuts debugging time dramatically.
  • Usage controls. Browser-hours are the unit of cost. You want per-session timeouts and a way to cap concurrency so a runaway job does not burn your budget. See /pricing for current rates and limits.

The remote browser online guide covers the setup mechanics if you are starting from zero, and remote web browser explains the runtime model in more depth.

A note on scale and cost

The dominant cost in this pipeline is browser time, not compute. A single video takes 5–15 seconds of browser time to load, handle consent, and extract metadata. At 10,000 videos per day, that is roughly 14–42 browser-hours daily. The arithmetic is straightforward; the variable is how much of your corpus needs the fingerprinting fallback, which adds download and API latency.

Two optimizations matter:

  1. Cache aggressively. Video metadata changes rarely. Cache the ytInitialPlayerResponse extraction keyed by video ID with a TTL of days, not hours.
  2. Batch by session. Reuse a single browser context for multiple videos in the same region and consent state. Creating a new context per video is the most common performance mistake.

Do not assume high concurrency from any provider without checking. Review the limits on your plan and design your queue around them.

When not to automate

If you are identifying one song for yourself, use Shazam. If you are identifying a handful per week, use a browser extension like AHA Music. The automation path only pays off when you have a corpus, a product requirement, or an agent that needs to do this unattended. Building the pipeline for five videos is a waste of a week.

The honest framing: the browser runtime is the infrastructure, the metadata parser is the easy part, and the legal review around audio downloading is the part that sinks projects. Get that review early.

Summary

To find the song used in a YouTube video programmatically, start with YouTube's own metadata via a real browser session, fall back to audio fingerprinting when the metadata is empty, and handle the failure cases explicitly. The runtime choice — hosted Chromium with CDP access, persistent profiles, and configurable proxy settings — determines whether the pipeline holds up at scale. Start with the documentation to wire up a session, and check /pricing before you size your concurrency.