r/learnprogramming • • 18d ago

Rendering video from a local webpage

I run a youtube channel for uploading albums, and the visuals consist of a makeshift music player made in html and javascript. I've been screen-recording this webpage to make a video out of it, but that results in skipping/lagging, so I'm interested in rendering the page frame-by-frame instead.

My hope is to use ffmpeg to screenshot-> frame advance the page (this is the easy part) -> repeat -> merge screenshots into a video -> add audio, but my research into ffmpeg has convinced me it's out of my skill level, so. How should I go about learning here, or, is there a better approach to the problem altogether?

2 Upvotes

6 comments sorted by

1

u/rupertavery64 18d ago

Can you share more details about the makeshift music player?

If you can render it to canvas, you can probably capture it as a stream using canvas.captureStream and then the MediaRecorder API to save it as MP4

1

u/BevWeb 18d ago

It's a hidden audio element playing the music, and some text elements displaying track metadata from a big array. There are moving elements like a progress bar and occasional background visuals, but the visuals are made by using js to change css styles

1

u/rupertavery64 18d ago

Theres a library called html2Canvas that lets you render an element to canvas, which you can then stream to the MediaRecorder API. You then setup a timeout that calls the render loop at 30fps or so

This is all information from Google AI. It looks quite doable and a few queries to Google AI or some other LLM can get you setup. It even mentions routing your audio from the hidden element to the media recorder.

I've just tested this and it works perfectly

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Export DOM & Audio to Video</title>
    <!-- Include html2canvas to convert HTML+CSS into canvas frames dynamically -->
    <script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
    <style>
        body { font-family: sans-serif; background: #222; color: #fff; display: flex; flex-direction: column; align-items: center; gap: 20px; }
        
        /* This is the DOM wrapper we want to record */
        #videoSource {
            width: 640px;
            height: 360px;
            background: linear-gradient(45deg, #111, #333);
            position: relative;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
        
        #trackTitle { font-size: 28px; font-weight: bold; margin-bottom: 5px; }
        #trackArtist { font-size: 18px; color: #aaa; margin-bottom: 30px; }
        
        #progressBarWrapper { width: 80%; height: 8px; background: #444; border-radius: 4px; overflow: hidden; }
        #progressBar { width: 0%; height: 100%; background: #00ffcc; transition: width 0.1s linear; }

        button { padding: 10px 20px; font-size: 16px; cursor: pointer; }
    </style>
</head>
<body>

    <!-- The actual visible HTML components updated by JS -->
    <div id="videoSource">
        <div id="trackTitle">Track Title</div>
        <div id="trackArtist">Artist Name</div>
        <div id="progressBarWrapper">
            <div id="progressBar"></div>
        </div>
    </div>

    <!-- Hidden Master Canvas for Recording -->
    <canvas id="recorderCanvas" width="1280" height="720" style="display:none;"></canvas>
    
    <!-- Hidden Audio Element -->
    <audio id="bgAudio" src="vorspiel.mp3" crossOrigin="anonymous" loop></audio>

    <div>
        <button id="startBtn">Start Recording</button>
        <button id="stopBtn" disabled>Stop & Download</button>
    </div>

<script>
const videoSource = document.getElementById('videoSource');
const trackTitle = document.getElementById('trackTitle');
const trackArtist = document.getElementById('trackArtist');
const progressBar = document.getElementById('progressBar');
const audio = document.getElementById('bgAudio');
audio.crossOrigin = "anonymous";

const recorderCanvas = document.getElementById('recorderCanvas');
const recorderCtx = recorderCanvas.getContext('2d');

const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');

let mediaRecorder;
let recordedChunks = [];
let renderInterval;
let audioContext, audioSource, audioDestination;

// Simulated track data array
const trackContainer = [
    { title: "Neon Horizons", artist: "Syntax Error" },
    { title: "Digital Rain", artist: "Cyber Dream" }
];

// Set initial metadata text
trackTitle.innerText = trackContainer[0].title;
trackArtist.innerText = trackContainer[0].artist;

// 1. Setup Web Audio API to route the hidden audio into the recording stream
function setupAudioRouting() {
    audioContext = new (window.AudioContext || window.webkitAudioContext)();
	console.log(audioContext);
    audioSource = audioContext.createMediaElementSource(audio);
    audioDestination = audioContext.createMediaStreamDestination();
    
    // Connect audio to destination (for recording) AND to speakers (so you can hear it)
    audioSource.connect(audioDestination);
    audioSource.connect(audioContext.destination);
}

// 2. The Core Render Loop: Converts HTML/CSS to Canvas frames on-the-fly
function recordLoop() {
    // Fake progress bar animation using JS style changes
    let progress = (audio.currentTime / audio.duration) * 100 || 0;
    progressBar.style.width = progress + '%';
    
    // Change background colors over time via JS CSS injections
    videoSource.style.background = `linear-gradient(${audio.currentTime * 20}deg, #1a0033, #001a33)`;

    // Convert the live DOM container element into a Canvas frame
    html2canvas(videoSource, {
        scale: 2, // Scale up to 2x (1280x720) to eliminate low-res jagged text/edges!
        logging: false,
        useCORS: true
    }).then(domCanvas => {
        // Clear and draw the high-res snapshot onto our master recorder canvas
        recorderCtx.clearRect(0, 0, recorderCanvas.width, recorderCanvas.height);
        recorderCtx.drawImage(domCanvas, 0, 0, recorderCanvas.width, recorderCanvas.height);
    });
}

startBtn.addEventListener('click', async () => {
    recordedChunks = [];
    if (!audioContext) setupAudioRouting();
    await audioContext.resume();
    audio.play();

    // Start running the DOM canvas snapshot loop at roughly 30 FPS
    renderInterval = setInterval(recordLoop, 1000 / 30);

    // Capture visual stream from the hidden canvas
    const canvasStream = recorderCanvas.captureStream(30);
    
    // Mix the Web Audio track together with the canvas track
    const audioTrack = audioDestination.stream.getAudioTracks()[0];
    canvasStream.addTrack(audioTrack);

    let options = { 
        mimeType: 'video/webm;codecs=vp9,opus', // WebM handles high-res DOM transfers efficiently
        videoBitsPerSecond: 6000000 
    };
    
    if (MediaRecorder.isTypeSupported('video/mp4;codecs=h264,aac')) {
        options = { mimeType: 'video/mp4;codecs=h264,aac', videoBitsPerSecond: 6000000 };
    }

    mediaRecorder = new MediaRecorder(canvasStream, options);
    
    mediaRecorder.ondataavailable = (e) => { if (e.data.size > 0) recordedChunks.push(e.data); };
    mediaRecorder.onstop = () => {
        clearInterval(renderInterval);
        audio.pause();
        
        const blob = new Blob(recordedChunks, { type: mediaRecorder.mimeType });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `music-video.${mediaRecorder.mimeType.includes('mp4') ? 'mp4' : 'webm'}`;
        document.body.appendChild(a);
        a.click();
    };

    mediaRecorder.start();
    startBtn.disabled = true;
    stopBtn.disabled = false;
});

stopBtn.addEventListener('click', () => {
    mediaRecorder.stop();
    startBtn.disabled = false;
    stopBtn.disabled = true;
});
</script>
</body>
</html>

I used npx serve . to test it locally and an mp3 in the same folder as the file.

It saves to webm on my browser (Chrome), but you could easily convert that to mp4 using ffmpeg

1

u/BevWeb 18d ago

Appreciate it! I'll see how I go adapting this to fit my own code, and take it as my kick in the pants to learn canvas.

1

u/Different_Pain5781 14d ago

Puppeteer for generating the frames. That's probably the simplest route. freeCodeCamp has decent Node tutorials but if the goal is learning actual backend logic then Boot dev is worth a look. Writing and debugging code beats passively watching another 40 minute YouTube tutorial.

1

u/BevWeb 14d ago

I assume by generating frames you mean getting screenshots to be stitched together? The Puppeteer docs mention something called pupperender which seems to match my use case, but I can definitely see myself struggling to configure it.