You have a queue of YouTube links and a PHP app that needs MP3s this week. By the end of this guide, you’ll call the Youtube Video to Audio API from your PHP backend, get a direct MP3 link plus metadata, and handle it safely in production—using one API key from Zyla API Hub.
What you can build with the Youtube Video to Audio API
The Youtube Video to Audio API converts a YouTube video (by ID) into an audio file and returns:
- A direct link to the MP3 file
- The video title
- File size
- Conversion progress and status
- Duration in seconds (floating-point)
Typical use cases include podcast feed generation from short-form videos, internal transcription pipelines (first get MP3, then feed to speech-to-text), automated content clipping, or offline listening workflows. The endpoint is designed for short videos (about 5 minutes or less).
Getting started on Zyla API Hub
Zyla API Hub centralizes thousands of APIs behind a single account, subscription, and API key. You subscribe once and call endpoints across categories with a consistent Authorization header. Billing is subscription + quota (not pay-per-call). For the first API you try, you typically get a 7-day trial or 50 requests. There is no Free Plan; check the API page for current access options and pricing before you ship.
- Open the API page: Youtube Video to Audio API on Zyla.
- Click Subscribe (or Start Free Trial when available) and get your API key.
- Use Authorization: Bearer YOUR_API_KEY in every request to zylalabs.com API endpoints.
Ready to integrate? Create your free developer account here to get an API key: Register.
Endpoint reference
The API exposes one actionable endpoint for conversion. Use the exact URL and params shown below.
Get Audio
- Method: GET
- URL: https://zylalabs.com/api/1812/youtube-video-to-audio-api/5870/get-audio
- Description: Provide a YouTube video ID. Videos should be approximately 5 minutes or less.
- Required query parameter:
- id (string): the YouTube video ID
cURL
curl -s -X GET "https://zylalabs.com/api/1812/youtube-video-to-audio-api/5870/get-audio?id=p-Z3YrHJ1sU" \
-H "Authorization: Bearer YOUR_API_KEY"
JSON (REAL API RESPONSE)
{
"link": "https://eta.123tokyo.xyz/get.php/9/9e/ty7nkwYqodA.mp3?cid=MmEwMTo0Zjg6YzAxMjozMmVlOjoxfE5BfERF&h=FwrcvY5cIfOO0jyXh5C-6Q&s=1737705748&n=%E2%82%B91%2C07%2C000%20_iPhone%2016%20Pro%20Max_%20USA%20to%20INDIA_%20%23shorts%20%23youtubeshorts&uT=R&uN=QWxlam9aeWxhTGFicw%3D%3D",
"title": "₹1,07,000 *iPhone 16 Pro Max* USA to INDIA! #shorts #youtubeshorts",
"filesize": 417480,
"progress": 100,
"duration": 22.896054233758,
"status": "ok",
"msg": "success"
}
What these fields mean and how to use them:
- link: Direct URL to the generated MP3. It includes URL-encoded parameters; treat it as an opaque string and don’t modify it.
- title: Original video title. Useful for file naming or metadata.
- filesize: Size of the MP3 in bytes. Good for quota checks or storage planning.
- progress: 100 indicates completion.
- duration: Length in seconds (float). Use for UX (e.g., progress bars) or downstream processing.
- status/msg: Simple status indicators. Expect "ok" and "success" on a successful run.
PHP integration (curl_init) with robust handling
Below is a minimal PHP example to call the endpoint, parse the JSON, and optionally download the MP3 to disk. It uses only the required id parameter and the Authorization header.
PHP
<?php
$apiKey = 'YOUR_API_KEY';
$videoId = 'p-Z3YrHJ1sU'; // Replace with your YouTube video ID
$url = 'https://zylalabs.com/api/1812/youtube-video-to-audio-api/5870/get-audio?id=' . urlencode($videoId);
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $apiKey,
'Accept: application/json'
],
CURLOPT_TIMEOUT => 30,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($response === false || $httpCode < 200 || $httpCode >= 300) {
http_response_code(502);
echo json_encode([
'error' => 'API request failed',
'httpCode' => $httpCode,
'curlError' => $error,
]);
exit;
}
$data = json_decode($response, true);
if (!is_array($data) || empty($data['status']) || $data['status'] !== 'ok') {
http_response_code(500);
echo json_encode([
'error' => 'Unexpected API response',
'response' => $response,
]);
exit;
}
// Extract fields
$link = $data['link'] ?? null;
$title = $data['title'] ?? 'untitled';
$filesize = $data['filesize'] ?? null;
$duration = $data['duration'] ?? null;
echo "Title: {$title}\n";
echo "Duration (s): {$duration}\n";
echo "Filesize (bytes): {$filesize}\n";
echo "MP3 URL: {$link}\n";
// Optional: download the MP3
if ($link) {
$safeTitle = preg_replace('/[^A-Za-z0-9_\-]+/', '_', $title);
$target = __DIR__ . '/' . $safeTitle . '.mp3';
$fp = fopen($target, 'w');
if ($fp === false) {
throw new RuntimeException('Cannot open file for writing: ' . $target);
}
$ch2 = curl_init($link);
curl_setopt_array($ch2, [
CURLOPT_FILE => $fp,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 120,
]);
$ok = curl_exec($ch2);
$err2 = curl_error($ch2);
curl_close($ch2);
fclose($fp);
if (!$ok) {
unlink($target);
throw new RuntimeException('Download failed: ' . $err2);
}
echo "Saved: {$target}\n";
}
JavaScript example (Node.js fetch)
This example demonstrates a simple GET request using native fetch in Node.js 18+ or undici. It prints the same key fields and shows how to stream the MP3 if you need to persist it.
JavaScript
import fs from 'node:fs';
import { pipeline } from 'node:stream';
import { promisify } from 'node:util';
const streamPipeline = promisify(pipeline);
const API_KEY = 'YOUR_API_KEY';
const videoId = 'p-Z3YrHJ1sU';
const url = `https://zylalabs.com/api/1812/youtube-video-to-audio-api/5870/get-audio?id=${encodeURIComponent(videoId)}`;
const res = await fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Accept': 'application/json'
}
});
if (!res.ok) {
throw new Error(`API error: ${res.status} ${res.statusText}`);
}
const data = await res.json();
if (data.status !== 'ok') {
throw new Error(`Conversion not ok: ${JSON.stringify(data)}`);
}
console.log('Title:', data.title);
console.log('Duration (s):', data.duration);
console.log('Filesize (bytes):', data.filesize);
console.log('MP3 URL:', data.link);
// Optional download
if (data.link) {
const mp3Res = await fetch(data.link);
if (!mp3Res.ok) throw new Error(`Download failed: ${mp3Res.status}`);
const safeTitle = data.title.replace(/[^A-Za-z0-9_\-]+/g, '_');
await streamPipeline(mp3Res.body, fs.createWriteStream(`${safeTitle}.mp3`));
console.log(`Saved: ${safeTitle}.mp3`);
}
End-to-end flow in production
Use this sequence to fit the API into your pipeline:
- Validate input: ensure you pass only the YouTube video ID (e.g., p-Z3YrHJ1sU). If you have full URLs, extract the v parameter or path ID on your side.
- Call the Get Audio endpoint with Authorization: Bearer YOUR_API_KEY.
- Check status and msg; proceed only if status is ok.
- Read duration to enforce your own upper bounds for processing time and storage. The endpoint is intended for videos about 5 minutes or less.
- Consume link to download the MP3. Treat it as an opaque URL; do not modify query params.
- Store filesize and title as metadata for downstream services (indexing, S3 object metadata, etc.).
Practical tips that save time
- Timeouts: Set sane HTTP client timeouts (e.g., 30s for API call, longer for MP3 download) to prevent stuck workers.
- Retries: For transient network errors, retry the API call with backoff. Do not hammer retries on 4xx responses.
- Caching: If you process the same IDs often, cache successful responses (title, filesize, duration, link) in a store and set your own retention. Re-validate as needed.
- Filenames: Video titles can contain characters not suitable for filesystems. Sanitize before saving.
- Units: filesize is bytes; duration is seconds (float). Convert before display.
- Length guard: Enforce your own limit near 5 minutes to avoid wasted work on longer videos.
Using the API from AI agents via MCP
You can call the same endpoint from MCP-compatible tools (Claude Code, Cursor, Windsurf, etc.) using Zyla’s MCP hub. Configure your client to use the MCP base and include your API key:
- MCP base: https://mcp.zylalabs.com/mcp?apikey=YOUR_API_KEY
- You’ll still issue a GET to the same resource URL: https://zylalabs.com/api/1812/youtube-video-to-audio-api/5870/get-audio?id=p-Z3YrHJ1sU
- Keep the Authorization: Bearer YOUR_API_KEY header in your tool’s HTTP call configuration.
For environment setup and client details, see the MCP documentation.
Common patterns and real-world use cases
- Batch ingestion for transcription: Convert many short IDs to MP3, queue files into your speech-to-text pipeline, attach duration and filesize for cost estimates.
- Audio preview service: Store link, title, and duration in your DB to power playback UIs and compact audio cards.
- Automated clipping: Pull MP3 for short-form clips and run them through audio normalization or silence trimming.
- Internal content archiving: For specific creator channels, parse IDs, convert, and deposit into managed storage with metadata for search.
Troubleshooting and edge cases
- Non-200 HTTP code from the API: Log the HTTP status and response body; do not parse JSON blindly on errors.
- status not "ok": Treat as a failed conversion and surface msg to logs or operators.
- Invalid or missing id: Ensure you’re passing only the video ID string. Sanitization is on you.
- Downloads failing: Follow redirects and allow enough timeout on the MP3 fetch; store partial failures and retry separately from the metadata call.
- Quota planning: Zyla uses subscription + quota. Monitor usage in your Zyla dashboard and check the API page for current plan details.
Security notes
- Do not hardcode API keys in source; use environment variables or secret managers.
- Limit who can trigger conversions in your app. Validate origin of requests if exposing a webhook or HTTP endpoint.
- Log only the last 4 characters of keys. Never print full credentials in logs or client-side code.
Test checklist before shipping
- Test with at least three different YouTube IDs (including one near 5 minutes and one short).
- Verify JSON parsing and field presence for link, title, filesize, duration, status, msg.
- Simulate timeouts and network failures to confirm retries and error surfacing.
- Ensure filenames derived from title are sanitized on all deployment OS targets.
- Run end-to-end: API call, MP3 download, storage, and any downstream processing (e.g., transcription).
Where to go next
Explore more audio and content tools on Zyla’s Youtube Video to Audio API page and the rest of Zyla API Hub. One account, one key, consistent headers across categories like audio, AI, enrichment, and more.
FAQ
1) What parameter do I need to pass to get audio?
Pass the YouTube video ID via the id query parameter. Example: id=p-Z3YrHJ1sU.
2) How do I authenticate?
Include Authorization: Bearer YOUR_API_KEY in the request headers to zylalabs.com endpoints.
3) What output do I get back?
A JSON object with link (direct MP3 URL), title, filesize (bytes), progress (100 when complete), duration (seconds), status, and msg.
4) Any limits on video length?
Yes. The endpoint is intended for videos approximately 5 minutes or less.
5) How is billing handled?
Zyla uses subscription + quota (not pay-per-call). For your first API, you typically get a 7-day trial or 50 requests. There’s no Free Plan; check the API page for current options.
Ship your integration now: get your API key in minutes and start calling the endpoint. Create your account here: Register. Then visit the Youtube Video to Audio API page, subscribe, and plug the Authorization header into your PHP code.