Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug fixes: robust release of media streams + memoization of audio/video constraints #133

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 69 additions & 33 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
import { register, MediaRecorder as ExtendableMediaRecorder, IMediaRecorder } from "extendable-media-recorder";
import { ReactElement, useCallback, useEffect, useRef, useState } from "react";
import { connect } from 'extendable-media-recorder-wav-encoder';
import {
ReactElement,
useCallback,
useEffect,
useRef,
useState,
useMemo,
} from "react";
import {
register,
MediaRecorder as ExtendableMediaRecorder,
IMediaRecorder,
} from "extendable-media-recorder";
import { connect } from "extendable-media-recorder-wav-encoder";

export type ReactMediaRecorderRenderProps = {
error: string;
Expand Down Expand Up @@ -73,13 +84,20 @@ export function useReactMediaRecorder({
stopStreamsOnStop = true,
askPermissionOnMount = false,
}: ReactMediaRecorderHookProps): ReactMediaRecorderRenderProps {
const mediaRecorder = useRef<IMediaRecorder | null >(null);
const mediaRecorder = useRef<IMediaRecorder | null>(null);
const mediaChunks = useRef<Blob[]>([]);
const mediaStream = useRef<MediaStream | null>(null);
const [status, setStatus] = useState<StatusMessages>("idle");
const [isAudioMuted, setIsAudioMuted] = useState<boolean>(false);
const [mediaBlobUrl, setMediaBlobUrl] = useState<string | undefined>(undefined);
const [mediaBlobUrl, setMediaBlobUrl] = useState<string | undefined>(
undefined,
);
const [error, setError] = useState<keyof typeof RecorderErrors>("NONE");
const mediaStreamTimestamp = useRef<number>(0);

// Memoize the media constraints to avoid re-rendering
video = useMemo(() => video, [JSON.stringify(video)]);
audio = useMemo(() => audio, [JSON.stringify(audio)]);

useEffect(() => {
const setup = async () => {
Expand All @@ -94,11 +112,14 @@ export function useReactMediaRecorder({
audio: typeof audio === "boolean" ? !!audio : audio,
video: typeof video === "boolean" ? !!video : video,
};
const timestamp = Date.now();
mediaStreamTimestamp.current = timestamp;
try {
let stream: MediaStream;
if (customMediaStream) {
mediaStream.current = customMediaStream;
stream = customMediaStream;
} else if (screen) {
const stream = (await window.navigator.mediaDevices.getDisplayMedia({
stream = (await window.navigator.mediaDevices.getDisplayMedia({
video: video || true,
})) as MediaStream;
stream.getVideoTracks()[0].addEventListener("ended", () => {
Expand All @@ -111,14 +132,24 @@ export function useReactMediaRecorder({

audioStream
.getAudioTracks()
.forEach((audioTrack) => stream.addTrack(audioTrack));
.forEach(audioTrack => stream.addTrack(audioTrack));
}
mediaStream.current = stream;
} else {
const stream = await window.navigator.mediaDevices.getUserMedia(
requiredMedia,
);
mediaStream.current = stream;
stream =
await window.navigator.mediaDevices.getUserMedia(requiredMedia);
}
if (stream) {
// Check if another stream was requested since we started acquiring this one
if (mediaStreamTimestamp.current == timestamp) {
// Stop existing stream (if any)
if (mediaStream.current) {
mediaStream.current.getTracks().forEach(track => track.stop());
}
mediaStream.current = stream;
} else {
// Another stream was requested, so stop this one
stream.getTracks().forEach(track => track.stop());
}
}
setStatus("idle");
} catch (error: any) {
Expand All @@ -127,22 +158,32 @@ export function useReactMediaRecorder({
}
}, [audio, video, screen]);

// When component unmounts, stop media streams
useEffect(() => {
return () => {
if (mediaStream.current) {
mediaStream.current.getTracks().forEach(track => track.stop());
}
mediaStreamTimestamp.current = Date.now();
};
}, []);

useEffect(() => {
if (!window.MediaRecorder) {
throw new Error("Unsupported Browser");
}

if (screen) {
if (!window.navigator.mediaDevices.getDisplayMedia) {
throw new Error("This browser doesn\'t support screen capturing");
throw new Error("This browser doesn't support screen capturing");
}
}

const checkConstraints = (mediaType: MediaTrackConstraints) => {
const supportedMediaConstraints =
navigator.mediaDevices.getSupportedConstraints();
const unSupportedConstraints = Object.keys(mediaType).filter(
(constraint) =>
constraint =>
!(supportedMediaConstraints as { [key: string]: any })[constraint],
);

Expand Down Expand Up @@ -173,13 +214,6 @@ export function useReactMediaRecorder({
if (!mediaStream.current && askPermissionOnMount) {
getMediaStream();
}

return () => {
if (mediaStream.current) {
const tracks = mediaStream.current.getTracks();
tracks.forEach((track) => track.clone().stop());
}
};
}, [
audio,
screen,
Expand All @@ -199,7 +233,7 @@ export function useReactMediaRecorder({
if (mediaStream.current) {
const isStreamEnded = mediaStream.current
.getTracks()
.some((track) => track.readyState === "ended");
.some(track => track.readyState === "ended");
if (isStreamEnded) {
await getMediaStream();
}
Expand All @@ -209,7 +243,8 @@ export function useReactMediaRecorder({
return;
}
mediaRecorder.current = new ExtendableMediaRecorder(
mediaStream.current, mediaRecorderOptions || undefined,
mediaStream.current,
mediaRecorderOptions || undefined,
);
mediaRecorder.current.ondataavailable = onRecordingActive;
mediaRecorder.current.onstop = onRecordingStop;
Expand All @@ -235,7 +270,8 @@ export function useReactMediaRecorder({
const [chunk] = mediaChunks.current;
const blobProperty: BlobPropertyBag = Object.assign(
{ type: chunk.type },
blobPropertyBag || (video ? { type: "video/mp4" } : { type: "audio/wav" }),
blobPropertyBag ||
(video ? { type: "video/mp4" } : { type: "audio/wav" }),
);
const blob = new Blob(mediaChunks.current, blobProperty);
const url = URL.createObjectURL(blob);
Expand All @@ -249,7 +285,7 @@ export function useReactMediaRecorder({
if (mediaStream.current) {
mediaStream.current
.getAudioTracks()
.forEach((audioTrack) => (audioTrack.enabled = !mute));
.forEach(audioTrack => (audioTrack.enabled = !mute));
}
};

Expand All @@ -273,7 +309,7 @@ export function useReactMediaRecorder({
mediaRecorder.current.stop();
if (stopStreamsOnStop) {
mediaStream.current &&
mediaStream.current.getTracks().forEach((track) => track.stop());
mediaStream.current.getTracks().forEach(track => track.stop());
}
mediaChunks.current = [];
}
Expand All @@ -291,12 +327,12 @@ export function useReactMediaRecorder({
mediaBlobUrl,
status,
isAudioMuted,
previewStream: mediaStream.current ?
new MediaStream(mediaStream.current.getVideoTracks()) :
null,
previewAudioStream: mediaStream.current ?
new MediaStream(mediaStream.current.getAudioTracks()) :
null,
previewStream: mediaStream.current
? new MediaStream(mediaStream.current.getVideoTracks())
: null,
previewAudioStream: mediaStream.current
? new MediaStream(mediaStream.current.getAudioTracks())
: null,
clearBlobUrl: () => {
if (mediaBlobUrl) {
URL.revokeObjectURL(mediaBlobUrl);
Expand Down