How To Record And Play Audio In JavaScript

    In this article, we will see how to record and play audio in javascript. Here, we will learn about how to record audio from a web page and play recorded audio. First, ask the user for microphone access to the browser and record the audio through the microphone and save the audio data chunks in form of binary values in an array when we play the audio then retrieve chuck data and start playing.

    Also, we will use the getUserMedia() function. The MediaDevices.getUserMedia() method prompts the user for permission to use a media input which produces a MediaStream with tracks containing the requested types of media. That stream can include, for example, a video track, an audio track, and possibly other track types.

    We will also use MediaRecorder() function. The MediaRecorder interface of the MediaStream Recording API provides functionality to easily record media. It is created using the MediaRecorder() constructor.

    So, let's see how to record audio in javascript, how to record audio using jquery, getusermedia example, mediarecorder javascript example, and javascript record audio from web page.

    Step 1: Start recording the audio

    Step 2: While recording, store the audio data chunks

    Step 3: Stop recording the audio

    Step 4: Convert the audio data chunks to a single audio data blob

    Step 5: Create a URL for that single audio data blob

    Step 6: Play the audio

    Example:

<!DOCTYPE html>
<html>
<head>
    <title>How To Record And Play Audio In JavaScript - Websolutionstuff</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>    
<style>
    body{
        margin:50px;
    }
</style>
<body class="text-center">
	<h4>How To Record And Play Audio In JavaScript - Websolutionstuff</h4>
    <p class="mt-5 mb-5">
        <button class="btn btn-dark" id="btnStart">START RECORDING</button>
        <button class="btn btn-dark" id="btnStop">STOP RECORDING</button>	
    </p>
<audio controls></audio>
<audio id="audioPlay" controls></audio>
</body>
</html>
<script>
	let audioIN = { audio: true };
	// audio is true, for recording

	// Access the permission for use
	// the microphone
	navigator.mediaDevices.getUserMedia(audioIN).then(function (mediaStreamObj) {

		// Connect the media stream to the
		// first audio element
		let audio = document.querySelector('audio');
		//returns the recorded audio via 'audio' tag

		// 'srcObject' is a property which
		// takes the media object
		// This is supported in the newer browsers
		if ("srcObject" in audio) {
		    audio.srcObject = mediaStreamObj;
		}
		else {
		audio.src = window.URL
			.createObjectURL(mediaStreamObj);
		}

		// It will play the audio
		audio.onloadedmetadata = function (ev) {

		// Play the audio in the 2nd audio
		// element what is being recorded
		audio.play();
		};

		// Start record
		let start = document.getElementById('btnStart');

		// Stop record
		let stop = document.getElementById('btnStop');

		// 2nd audio tag for play the audio
		let playAudio = document.getElementById('audioPlay');

		// This is the main thing to recorded
		// the audio 'MediaRecorder' API
		let mediaRecorder = new MediaRecorder(mediaStreamObj);
		// Pass the audio stream

		// Start event
		start.addEventListener('click', function (ev) {
		mediaRecorder.start();
		    console.log(mediaRecorder.state);
		})

		// Stop event
		stop.addEventListener('click', function (ev) {
		mediaRecorder.stop();
		    console.log(mediaRecorder.state);
		});

		// If audio data available then push
		// it to the chunk array
		mediaRecorder.ondataavailable = function (ev) {
		dataArray.push(ev.data);
		}

		// Chunk array to store the audio data
		let dataArray = [];

		// Convert the audio data in to blob
		// after stopping the recording
		mediaRecorder.onstop = function (ev) {

		// blob of type mp3
		let audioData = new Blob(dataArray,
					{ 'type': 'audio/mp3;' });
		
		// After fill up the chunk
		// array make it empty
		dataArray = [];

		// Creating audio url with reference
		// of created blob named 'audioData'
		let audioSrc = window.URL
			.createObjectURL(audioData);

		// Pass the audio url to the 2nd video tag
		playAudio.src = audioSrc;
		}
	})

	// If any error occurs then handles the error
	.catch(function (err) {
		console.log(err.name, err.message);
	});
</script>

    Output:

    how_to_record_and_play_audio_in_javascript_output

    You might also like:

Bình luận
Vui lòng đăng nhập để bình luận
Một số bài viết liên quan