The HTMLMediaElement API provides the properties and methods required to implement fundamental media-related capabilities that are common to audio and video. The captureStream() method is used to perform a real-time capture of the content being rendered in the media element.
Syntax:
captureStream()
Parameters: This method doesn’t accept any parameter.
Return Value: It returns the MediaStream object, which can be utilized for other media processing code, as a source for audio and/or video.
Example 1: This example illustrates the basic usage of the HTMLMediaElement.captureStream() method.
HTML
<!DOCTYPE html> < html > < body style = "text-align: center;" > < h1 style = "color:green" > neveropen </ h1 > < h3 > HTMLMediaElement API captureStream method </ h3 > < video id = "video" style="height: 250px; width: 400px;" onplay = "playHandler()" crossorigin controls src = "neveropen.mp4" > Browser not supported </ video > < script > function playHandler() { let video = document.getElementById('video'); let stream = video.captureStream(); console.log(stream); } </ script > </ body > </ html > |
Output:
Example 2: This example illustrates the use of the HTMLMediaElement.captureStream() method, where we are extracting the audio from its video.
HTML
<!DOCTYPE html> < html > < body style = "text-align: center;" > < h1 style = "color:green" > neveropen </ h1 > < h3 > HTMLMediaElement API captureStream method </ h3 > < video id = "video" style="height: 250px; width: 400px;" onplay = "playHandler()" crossorigin controls src = "neveropen.mp4" > Browser not supported </ video > < script > function playHandler() { let video = document.getElementById('video'); let videoStream = video.captureStream(); const audioTrack = videoStream.getAudioTracks()[0]; const audioStream = new MediaStream(); audioStream.addTrack(audioTrack); const audio = document.createElement("audio"); audio.controls = true; document.body.append(audio); audio.srcObject = audioStream; audio.volume = 1.0; } </ script > </ body > </ html > |
Output: