JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Web Audio Track Recorder</title>
</head>
<body>
<h1>Web Audio Track Recorder</h1>
<button id="recordButton">Start Recording</button>
<script src="script.js"></script>
</body>
</html>
JavaScript
// URLs of the audio tracks:
const track1Url = 'https://archive.org/download/tvtunes_13046/Pirates%20of%20the%20Caribbean%20-%20Hes%20a%20Pirate.mp3';
const track2Url = 'https://archive.org/download/tvtunes_7590/Universal%20Studios.mp3';
// Initialize variables
let audioContext;
let source1, source2;
let mediaRecorder;
let audioChunks = [];
let isRecording = false;
// Function to start the audio context and load tracks
async function startAudio() {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
// Load and decode the audio tracks
const track1Data = await fetch(track1Url).then(response => response.arrayBuffer());
const track2Data = await fetch(track2Url).then(response => response.arrayBuffer());
const track1Buffer = await audioContext.decodeAudioData(track1Data);
const track2Buffer = await audioContext.decodeAudioData(track2Data);
// Create buffer sources
source1 = audioContext.createBufferSource();
source2 = audioContext.createBufferSource();
source1.buffer = track1Buffer;
source2.buffer = track2Buffer;
// Create a gain node to control the volume
const gainNode = audioContext.createGain();
gainNode.gain.setValueAtTime(0.25, audioContext.currentTime);
// Connect sources to the gain node
source1.connect(gainNode);
source2.connect(gainNode);
// Connect gain node to the destination (speakers)
gainNode.connect(audioContext.destination);
// Create a MediaStream from the audio context
const destination = audioContext.createMediaStreamDestination();
gainNode.connect(destination);
// Initialize MediaRecorder with the audio stream
mediaRecorder = new MediaRecorder(destination.stream);
// Event handler for when data is available
mediaRecorder.ondataavailable = event => {
audioChunks.push(event.data);
};
// Event handler for when recording stops
mediaRecorder.onstop = () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
const audioUrl =...