I am currently developing a Chrome extension that records the tab, but I am having difficulty implementing the onpause
and onresume
feature with the Javascript MediaRecorder API.
I’m calling pause()
to change the state to paused
, but the tracks are still being recorded. Any help will be greatly appreciated.
let recorder;
let data = [];
async function stopRecording() {
if (recorder ? .state === "recording") {
recorder.stop()
recorder.stream.getTracks().forEach((t) => t.stop());
window.location.hash = '';
}
}
async function pauseRecording() {
if (recorder ? .state === "recording") {
recorder.pause()
}
}
async function resumeRecording() {
if (recorder ? .state === "paused") {
recorder.resume()
}
}
async function startRecording(streamId) {
try {
if (recorder ? .state === "recording") {
throw new Error("Called startRecording while recording is in progress")
}
const media = await navigator.mediaDevices.getUserMedia({
audio: {
mandatory: {
chromeMediaSource: 'tab',
chromeMediaSourceId: streamId
}
},
video: {
mandatory: {
chromeMediaSource: 'tab',
chromeMediaSourceId: streamId
}
}
});
const microphone = await navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: false
}
})
const mixedContext = new AudioContext();
const mixedDest = mixedContext.createMediaStreamDestination();
mixedContext.createMediaStreamSource(microphone).connect(mixedDest)
mixedContext.createMediaStreamSource(media).connect(mixedDest)
const combinedStream = new MediaStream([
media.getVideoTracks()[0],
mixedDest.stream.getTracks()[0]
])
recorder = new MediaRecorder(combinedStream, {
mimeType: 'video/webm'
});
recorder.ondataavailable = (event) => data.push(event.data);
recorder.onpause = (event) => {
// code for actually pausing the stream goes here
};
recorder.onresume = (event) => {
// code for actually resuming the stream goes here
};
recorder.onstop = async() => {
const blob = new Blob(data, {
type: 'video/webm'
});
const url = URL.createObjectURL(blob)
await chrome.runtime.sendMessage({
type: "open-tab",
url
})
recorder = undefined;
data = [];
};
recorder.start();
} catch (error) {
console.log(error)
}
}