I currently have a MediaStream which is being recorded using MediaRecorder. At the end of the recording after recorder.stop(), it produce a Blob and I am able to play that video back. My goal is to play not the entire video at the end, but play a chunk while recording. For the moment, a chunk is not playable while recording is not ended.
How can i do that using javascript? The final objective is to send a chunk by websocket that is playable even if recording is in action.
I am not able to bring new solutions. Can anyone help or at least explain me the things ?
What I've tried was
navigator.mediaDevices.getUserMedia().then(function(media_stream) {
var recorder = new MediaRecorder(media_stream);
recorder.ondataavailable = event => {
//How to play each chunk without waiting for recorder.stop() ???
//event.data represent the data of a chunk (i.e. a blob)
};
recorder.start(1000);
});
This is the simplest example I could come up with.
You need a video element for playing the video as you stream it, and a record button to kick off the recording.
The script does the following
- Checks for support
- Creates success and error handlers for when permission is granted / denied
- Ask permission to record
- If permitted, calls onSuccess
- Creates the recorder
- Creates an onclick handler for the record button
- If record is clicked, the onclick handler is called
- The mediaRecorder starts recording
- The video element is set to use the stream
- The video element is set to autoplay so the stream shows immediately
HTML
<video id="player"></video>
<button class="record">Record</button>
JS
<script>
const video = document.querySelector('#player');
const record = document.querySelector('.record');
(function start() {
// 1. check for support
if (! navigator.mediaDevices.getUserMedia) {
return console.log('getUserMedia not supported on your browser!');
}
// 2. create onSuccess handler
// 4. called if permitted
const onSuccess = function (stream) {
// 5. create the recorder
const mediaRecorder = new MediaRecorder(stream);
// 6. create onclick handler for record button
// 7. called if record is clicked
record.onclick = function() {
// 8. starts recording
mediaRecorder.start();
// 9. sets video element to use the stream
video.srcObject = stream;
// 10. sets the video element to autoplay, otherwise user would have to click play
video.autoplay = true;
};
};
// 2. create onError handler
const onError = function (error) {
console.error('The following error occured: ' + error);
};
// 3. ask permission to record audio and video
const constraints = {video: true, audio: true};
navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
})();
</script>
you have to use RequestData for ondataavailable to fire
来源:https://stackoverflow.com/questions/46627364/mediarecorder-how-to-play-chunk-blob-of-video-while-recording