Join

AC
Sh Raj
Published 4d ago on Thu Jun 27 2024

How to Create an Audio Recorder with Pause and Download Functionality Using JavaScript


Creating an audio recorder with pause and download functionality using JavaScript is a great way to add interactive features to your web application. This tutorial will guide you through the steps to build this feature using modern JavaScript APIs.

Prerequisites

Before we begin, make sure you have a basic understanding of HTML, CSS, and JavaScript. You'll also need a modern web browser that supports the Web Audio API and MediaRecorder API.

Step 1: Setting Up the HTML

First, let's create the HTML structure for our audio recorder. We'll need buttons to start, pause, and download the recording, as well as an audio element to play back the recording.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Audio Recorder</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-top: 50px;
    }
    button {
      margin: 10px;
    }
  </style>
</head>
<body>
  <h1>Audio Recorder</h1>
  <button id="startButton">Start Recording</button>
  <button id="pauseButton" disabled>Pause Recording</button>
  <button id="downloadButton" disabled>Download Recording</button>
  <audio id="audioPlayback" controls></audio>

  <script src="recorder.js"></script>
</body>
</html>

Step 2: Accessing the Microphone

Next, we'll use the MediaDevices API to access the user's microphone. We'll request permission to use the microphone and handle the user's response.

// recorder.js

let mediaRecorder;
let recordedChunks = [];

async function getMicrophoneAccess() {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    handleSuccess(stream);
  } catch (err) {
    console.error('Error accessing microphone:', err);
  }
}

function handleSuccess(stream) {
  mediaRecorder = new MediaRecorder(stream);

  mediaRecorder.ondataavailable = (event) => {
    if (event.data.size > 0) {
      recordedChunks.push(event.data);
    }
  };

  mediaRecorder.onstop = () => {
    const blob = new Blob(recordedChunks, {
      type: 'audio/webm'
    });
    const url = URL.createObjectURL(blob);
    const audioPlayback = document.getElementById('audioPlayback');
    audioPlayback.src = url;

    const downloadButton = document.getElementById('downloadButton');
    downloadButton.href = url;
    downloadButton.download = 'recording.webm';
    downloadButton.disabled = false;
  };
}

getMicrophoneAccess();

Step 3: Implementing Start and Pause Functionality

We'll add event listeners to the buttons to control the recording. The start button will start the recording, the pause button will pause or resume the recording depending on its state, and the stop button will stop the recording and enable the download button.

// recorder.js

document.getElementById('startButton').addEventListener('click', () => {
  if (mediaRecorder.state === 'inactive') {
    recordedChunks = [];
    mediaRecorder.start();
    document.getElementById('startButton').disabled = true;
    document.getElementById('pauseButton').disabled = false;
    document.getElementById('downloadButton').disabled = true;
  }
});

document.getElementById('pauseButton').addEventListener('click', () => {
  if (mediaRecorder.state === 'recording') {
    mediaRecorder.pause();
    document.getElementById('pauseButton').textContent = 'Resume Recording';
  } else if (mediaRecorder.state === 'paused') {
    mediaRecorder.resume();
    document.getElementById('pauseButton').textContent = 'Pause Recording';
  }
});

document.getElementById('stopButton').addEventListener('click', () => {
  if (mediaRecorder.state !== 'inactive') {
    mediaRecorder.stop();
    document.getElementById('startButton').disabled = false;
    document.getElementById('pauseButton').disabled = true;
    document.getElementById('pauseButton').textContent = 'Pause Recording';
  }
});

Step 4: Implementing the Download Functionality

Finally, we'll implement the download functionality by creating a Blob from the recorded audio data and generating a download link.

// recorder.js

document.getElementById('downloadButton').addEventListener('click', () => {
  if (recordedChunks.length > 0) {
    const blob = new Blob(recordedChunks, { type: 'audio/webm' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = 'recording.webm';
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
  }
});

Conclusion

You've now created a basic audio recorder with pause and download functionality using JavaScript. This example can be extended and customized to fit the needs of your application, such as adding more controls, improving the UI, or supporting different audio formats.

Feel free to explore the capabilities of the MediaRecorder API and the Web Audio API to enhance your audio recording functionality further. Happy coding!

Email Newsletter

Subscribe to our weekly newsletter to stay up-to-date with the latest articles, tutorials, and news from the dev.to community.

User background
Sh

Sh Raj

Software Engineer

Passionate about building innovative software solutions.

Joined 2 years ago
San Francisco
F1F2F3F4
1.2K Followers
10K Views

Suggested Communities

AC
React Developers
10,000 members
AC
Web Performance
5,000 members
AC
Scalable Apps
3,000 members