Monthly Archives: September 2025
Batch extract captions from youtube

Create a text file called videos.txt, all captions will be extracted the video title name.

Download YT-DLP and run this command line

yt-dlp.exe –ignore-config –no-overwrite –write-sub –write-auto-subs –sub-lang en –skip-download –output “%(title)s %(id)s.%(ext)s” -a videos.txt

Posted on September 28, 2025, 7:19 am By
Categories: tech tips
Make your own Youtube to MP3 website

Using an API that gives you a bit of free usage together with AI help I’ve make this Youtube to MP3 site as a single file.

To get it going signup to https://rapidapi.com/ with a free and personal account.  Search for “YT Search and Download MP3” API and subscribe to it. Find your API KEY can add to this index.php on line $apiKey = ‘PUT YOUR KEY HERE’;

 

index.php

<?php
// — Download Handler —
// This block checks if a download request has been made to this script.
if (isset($_GET[‘download_url’]) && isset($_GET[‘filename’])) {
    $fileUrl = urldecode($_GET[‘download_url’]);
    $filename = urldecode($_GET[‘filename’]);
    // It’s crucial to validate the URL to prevent security issues.
    // Here, we’re just checking if it’s from the expected domain.
    if (strpos($fileUrl, ‘fileready.me’) !== false) {
        // Set headers to force the browser to download the file with the correct name.
        header(‘Content-Type: audio/mpeg’);
        header(‘Content-Disposition: attachment; filename=”‘ . $filename . ‘”‘);
        header(‘Pragma: no-cache’);
        // Use readfile() to stream the file directly from the source to the user.
        // This is memory-efficient as it doesn’t load the whole file into RAM.
        @readfile($fileUrl); // Use @ to suppress warnings on connection abort
        // Stop the script from rendering the rest of the page.
        exit;
    } else {
        // Handle invalid URL
        die(“Invalid download link.”);
    }
}
// — End of Download Handler —
// Function to extract the YouTube video ID from a URL
function getYouTubeVideoId($url) {
    $videoId = ”;
    $pattern = ‘/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^”&?\/\s]{11})/i’;
    if (preg_match($pattern, $url, $matches)) {
        $videoId = $matches[1];
    }
    return $videoId;
}
// Function to call the API using cURL
function callApi($videoUrl) { // Changed parameter to accept the full URL
    // — IMPORTANT —
    // Replace this with your own RapidAPI Key
    $apiKey = ‘PUT YOUR KEY HERE’;
    // —————–
    $curl = curl_init();
    // CORRECTED: The API expects the parameter to be named ‘url’, not ‘id’.
    curl_setopt_array($curl, [
        CURLOPT_URL => “https://yt-search-and-download-mp3.p.rapidapi.com/mp3?url=” . urlencode($videoUrl),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => “”,
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => “GET”,
        CURLOPT_HTTPHEADER => [
            “x-rapidapi-host: yt-search-and-download-mp3.p.rapidapi.com”,
            “x-rapidapi-key: ” . $apiKey
        ],
    ]);
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    if ($err) {
        return [‘status’ => ‘error’, ‘message’ => “cURL Error #: ” . $err];
    } else {
        return json_decode($response, true);
    }
}
// Initialize variables
$results = [];
$submittedUrls = ”;
$diagnostics = [];
// Check if the form has been submitted
if ($_SERVER[“REQUEST_METHOD”] == “POST” && !empty($_POST[‘youtube_urls’])) {
    $diagnostics[] = “— Diagnostic Report Started: ” . date(“Y-m-d H-i-s”) . ” —“;
    $submittedUrls = $_POST[‘youtube_urls’];
    // Split the textarea content into an array of URLs, trimming whitespace and removing empty lines
    $urls = array_filter(array_map(‘trim’, explode(“\n”, $submittedUrls)));
    if (empty($urls)) {
        $results[] = [‘error’ => ‘No valid URLs were submitted.’];
    } else {
        // Set a higher time limit for this script to handle waiting
        set_time_limit(count($urls) * 180); // 3 minutes per video
        // Process each URL
        foreach ($urls as $index => $url) {
            $diagnostics[] = “\n— Processing URL #” . ($index + 1) . “: ” . htmlspecialchars($url) . ” —“;
            $currentResult = [‘url’ => $url];
            $videoId = getYouTubeVideoId($url);
            if ($videoId) {
                $diagnostics[] = “Successfully extracted Video ID for validation: ” . htmlspecialchars($videoId);
                $maxRetries = 15;
                $retryDelay = 5;
                $diagnostics[] = “Configuration: Max Retries = {$maxRetries}, Delay = {$retryDelay}s”;
                $downloadLink = null;
                for ($i = 0; $i < $maxRetries; $i++) {
                    $diagnostics[] = “API Call Attempt #” . ($i + 1);
                    $response = callApi($url);
                    $diagnostics[] = “Raw API Response: ” . json_encode($response);
                    if (isset($response[‘success’])) {
                        if ($response[‘success’] === true && !empty($response[‘download’])) {
                            $diagnostics[] = “SUCCESS: ‘success:true’ received.”;
                            $currentResult[‘downloadLink’] = $response[‘download’];
                            $currentResult[‘title’] = $response[‘title’] ?? ‘Your Video’;
                            break;
                        } else {
                            $currentResult[‘error’] = $response[‘error’] ?? ‘An unknown API error occurred.’;
                            $diagnostics[] = “ERROR: API returned a failure response. Message: ” . htmlspecialchars($currentResult[‘error’]);
                            break;
                        }
                    } elseif (isset($response[‘status’])) {
                         if ($response[‘status’] === ‘processing’) {
                            $diagnostics[] = “Status ‘processing’. Waiting for {$retryDelay} seconds.”;
                            sleep($retryDelay);
                        } else {
                            $currentResult[‘error’] = $response[‘message’] ?? ‘An unknown API error occurred.’;
                            $diagnostics[] = “ERROR: API returned an error status. Message: ” . htmlspecialchars($currentResult[‘error’]);
                            break;
                        }
                    } else {
                        $currentResult[‘error’] = “Invalid response from the API.”;
                        $diagnostics[] = “ERROR: The API response was malformed.”;
                        break;
                    }
                }
                if (!isset($currentResult[‘downloadLink’]) && !isset($currentResult[‘error’])) {
                    $currentResult[‘error’] = “The conversion timed out.”;
                    $diagnostics[] = “ERROR: Process timed out after {$maxRetries} retries.”;
                }
            } else {
                $currentResult[‘error’] = “Invalid YouTube URL.”;
                $diagnostics[] = “ERROR: Failed to extract Video ID.”;
            }
            $results[] = $currentResult;
        }
    }
    $diagnostics[] = “\n— Diagnostic Report Ended —“;
}
?>
<!DOCTYPE html>
<html lang=”en”>
<head>
    <meta charset=”UTF-8″>
    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
    <title>YouTube to MP3 Downloader</title>
    <script src=”https://cdn.tailwindcss.com”></script>
    <link href=”https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap” rel=”stylesheet”>
    <style>
        body {
            font-family: ‘Inter’, sans-serif;
        }
    </style>
</head>
<body class=”bg-gray-100 flex items-center justify-center min-h-screen py-12″>
    <div class=”w-full max-w-2xl mx-auto bg-white rounded-lg shadow-xl p-8″>
        <div class=”text-center mb-8″>
            <h1 class=”text-3xl font-bold text-gray-800″>YouTube to MP3 Downloader</h1>
            <p class=”text-gray-500 mt-2″>Enter YouTube video URLs below, one per line.</p>
        </div>
        <form action=”<?php echo htmlspecialchars($_SERVER[“PHP_SELF”]); ?>” method=”POST” class=”space-y-4″>
            <div>
                <label for=”youtube_urls” class=”block text-sm font-medium text-gray-700″>YouTube URLs (one per line)</label>
                <textarea name=”youtube_urls” id=”youtube_urls” rows=”5″
                          class=”mt-1 block w-full px-4 py-3 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm”
                          placeholder=”https://www.youtube.com/watch?v=…&#10;https://youtu.be/…&#10;https://www.youtube.com/watch?v=…”
                          required><?php echo htmlspecialchars($submittedUrls); ?></textarea>
            </div>
            <div>
                <button type=”submit”
                        class=”w-full flex justify-center py-3 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500″>
                    Download All MP3s
                </button>
            </div>
        </form>
        <!– Results Section –>
        <div id=”results” class=”mt-8 space-y-4″>
            <?php foreach ($results as $result): ?>
                <div class=”border border-gray-200 p-4 rounded-lg”>
                    <p class=”text-sm text-gray-600 truncate mb-2″><strong>URL:</strong> <?php echo htmlspecialchars($result[‘url’]); ?></p>
                    <?php if (isset($result[‘error’])): ?>
                        <!– Error Message –>
                        <div class=”bg-red-100 border-l-4 border-red-500 text-red-700 p-3 rounded-md text-sm” role=”alert”>
                            <p><span class=”font-bold”>Error:</span> <?php echo htmlspecialchars($result[‘error’]); ?></p>
                        </div>
                    <?php elseif (isset($result[‘downloadLink’])):
                        // Sanitize the video title for the filename
                        $safeFilename = preg_replace(‘/[\/:*?”<>|]/’, ”, $result[‘title’]);
                        $safeFilename = trim($safeFilename);
                        if (empty($safeFilename)) { $safeFilename = ‘download’; }
                        $safeFilename .= ‘.mp3’;
                        // Create the proxy download link
                        $selfUrl = htmlspecialchars($_SERVER[“PHP_SELF”]);
                        $proxyDownloadLink = $selfUrl . ‘?download_url=’ . urlencode($result[‘downloadLink’]) . ‘&filename=’ . urlencode($safeFilename);
                    ?>
                        <!– Success Message –>
                        <div>
                            <p class=”mb-2″><strong>Title:</strong> <?php echo htmlspecialchars($result[‘title’]); ?></p>
                            <a href=”<?php echo $proxyDownloadLink; ?>”
                               class=”inline-block w-full text-center bg-green-600 text-white font-bold py-2 px-4 rounded-md hover:bg-green-700 transition duration-300 text-sm”>
                                Download “<?php echo htmlspecialchars($safeFilename); ?>”
                            </a>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
        <!– Diagnostic Report Section –>
        <?php if (!empty($diagnostics)): ?>
        <div class=”mt-8″>
            <details class=”bg-gray-50 p-4 rounded-lg border border-gray-200″>
                <summary class=”font-medium text-gray-700 cursor-pointer”>
                    Show Diagnostic Report
                </summary>
                <div class=”mt-4 pt-4 border-t border-gray-200″>
                    <h3 class=”text-lg font-semibold text-gray-800 mb-2″>API Communication Log</h3>
                    <pre class=”bg-gray-900 text-white text-sm rounded-md p-4 overflow-x-auto”><code><?php
                        foreach ($diagnostics as $line) {
                            echo htmlspecialchars($line) . “\n”;
                        }
                    ?></code></pre>
                </div>
            </details>
        </div>
        <?php endif; ?>
        <!– End of Diagnostic Report Section –>
    </div>
</body>
</html>

 

 

Posted on September 8, 2025, 2:17 pm By
Categories: tech tips