Code Monkey home page Code Monkey logo

deltacircuit / react-media-recorder Goto Github PK

View Code? Open in Web Editor NEW
448.0 8.0 117.0 114 KB

react-media-recorder is a react component with render prop that can be used to record audio/video streams using MediaRecorder API.

Home Page: https://npmjs.com/react-media-recorder

License: MIT License

JavaScript 0.38% TypeScript 99.62%
react recorder voice-recording video-recording media-recording getusermedia mediarecorder getdisplaymedia screen-recorder record-audio

react-media-recorder's People

Contributors

briangershon avatar danigb avatar databu avatar dcorey05 avatar deltacircuit avatar gezquinndesign avatar github-id01 avatar goontwo avatar grantrules avatar nnaemekaibe avatar pipesnbottles avatar rowadz avatar seawolf42 avatar vinspee avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-media-recorder's Issues

H264 support

I was hoping to use this for H264 recording support, however upon inspecting the code there's no way to pass any options when creating the MediaRecorder.

The supported constraints from getUserMedia reports that h264 is not a supported mimeType, however MediaRecorder.isTypeSupported('video/webm;codecs=H264') return true. I think the solution is to provide the video codec to the MediaRecorder constructor.

See here: https://gist.github.com/kkm/60ce3479ad35d923bbff6e4e8f5ae25c

Cheers

Incomplete blob on Firefox

We're using the useReactMediaRecorder hook in our app. We haven't encountered any issue on Chrome but on Firefox the blobs returned by the hook only contain the first few seconds of the recordings. No errors are thrown.

Here's a Codesandbox that reproduces the behaviour.

Let me know if you need more information!

not working on server

I am using
"react-media-recorder": "^1.4.0",

the package was working fine on local environment when i tried to deploy it, the status is not changing and onStop is not getting invoked.

Is there something I am missing?

this is my code:

```
const { status, startRecording, stopRecording, error, mediaBlobUrl, clearBlobUrl } =
useReactMediaRecorder(
	{
		audio: true,
		type: "audio/wav",
onStop: (blobUrl, blob) => {
	console.log("onStop recording")
	const url = URL.createObjectURL(blob)
	let formData = new FormData()

	//person_name-person_id-language_id-sentence.id-date
	const today = new Date()
	// const file_name = `${id}-${language_id}-${sentence.id}-${today.toISOString()}.wav`
	const file_name = `${name}-${id}-${language_id}-${
		sentence.id
	}-${today.toDateString()}-${language_name}.wav`

	console.log("-------------------------------------------------------")
	console.log("file_name :>>", file_name)
	console.log("-------------------------------------------------------")

formData.append("file", blob, file_name)

let upload_url
if (sample) {
	upload_url = "sentence/upload_audio_sample"
} else {
	upload_url = "sentence/upload_audio"
}

console.log(`upload_url`, upload_url)
axios
	.post(upload_url, formData)
	.then((d) => console.log("after post blob :>>", d))
	.catch((e) => console.log("error in post blob :>>", e))

},
},
(error) => console.log("shsdsd", error)
)

const handleStartRecording = () => {
setRecording(!recording)
if (!recording) {
clearBlobUrl()
startRecording()
} else {
stopRecording()
console.log("mediaBlobUrl :>>", mediaBlobUrl)
}
}

const getStartRecordingText = () => {
if (sample !== undefined) {
return "Start Recording Sample"
} else {
return "Start Recording"
}
}

How get an audio blob an OnStop like video

Hello, How can i get the audio blob like video blob in onStop func. I can get a audioStream, but i need an audio as the same form like video, to send it to API. Thanks)
Screenshot_1
Screenshot_2
Screenshot_4

No_constraints error on mobile

When i click to start recording i get this error on mobiles. But in my PC everything is working. Anyone knows what could it be?

Edit: it was chrome that was blocking the microphone on localhost

Video gets flipped in preview

Hi,

  1. While recording I need it to be like a mirror.
  2. After recording, it must play exactly what I recorded and not flip just like we have normally in our smartphones while making videos.

Generate video thumbnail from recorded video

Hey,
Is it feasible to bring in a feature to generate video thumbnail from a recorded video and get it as a jpg/png file so that it can be stored along with the media metadata for better user experience?

How can we get chunk blob, is there any props around this ?

I want to get blob in a chunk, I have checked existing props I just found previewStream to get the current stream but I need a blob so that I can send it to server and store in real-time.

ondataavailable method is available to get blob in a chunk, So can you please add chunk blob props support as well.

mediaRecorder.ondataavailable = function (e: any) {
console.log("blob = ", e.data)
});

Camera Still Active After Leaving Page

I'm working on a basic implementation that I'll be expanding on later. But I'm running into an issue where the following sequence of events occurs on Firefox (other browsers not tested).

  1. Navigate to page ✔️
  2. Component requests media and renders ✔️
  3. Navigate to another page within site ✔️
  4. Camera and microphone are still active ❌

Expose currently used sample rate

Thank you for this my friends

I need the used sample rate as a param to my server, but can't seem to get it (as the supplied sample rate doesn't override anything and I prefer not to rely on it anyway).

Can this be done?

Wait 3-5sec after status is "acquiring_media" and before "recording" so user can get ready when web cam is ON

Hi,

I have to add video recording funtionality in website where before starting recording i want to add counter, means where after clicking on "Start Recording" there should be a display "3 2 1" and then recording should start. Means after status is "acquiring_media" and user is able to view himself at that time counter should come to give him time before recording starts.
But the problem is.. how will i identify for how much time status will be "acquiring_media".
Can anybody help me, how to achive this.

image

Looking forward to hearing from you soon!

Thanks!

First blob comes as text / html. Expected audio/webm

I'm recording and generating the blobUrl, to store I'm turning it into a file, but halfway through I realized that the blob is coming as text / html.

This is my handle code:

 const handleBlob = async () => { 
    let blob = await fetch(mediaBlobUrl).then(r => r.blob());
    console.log("[REC BLOB URL]", blob)

    let fileBlob = new File([blob], new Date().toISOString()+"_recording.webm" ,{ type: "audio/webm" })
    
    return fileBlob
}

The first thing that the "REC BLOB URL" return is this:

image

And render this:

image

If i take that file link, for some reason what comes is a video.

image

Also, when I try to record another audio, the result is an audio / webm, however with the content of the previous audio.

That is, if I record a 10s audio for the first time (when a text / html is returned), when I record again what comes is this 10s audio (regardless of how long I recorded).
And it remains. Audios always come late, always with the content of the previously recorded.

Why does it happen?
OBS: Im using redux and socket to send this to a chat.

Safari is not supported

Hey there,

Not an issue per se but safari is not supported, have you thought of using the polyfill to mend this?

I am happy to help in any shape or form

Audio file can't be played in safari

Descriptions

  • Made the audio file in chrome browser using this library
  • Uploaded the file to firebase and played it in the browser. chrome play it well. But it is not played well on safari

I don't have any clue about this problem. Is there anyone who can help me to solve this problem?

screen share permission call twice.

Hello. I wanna use the screen capture alongside audio. So it's my code:

<ReactMediaRecorder
                screen
                render={({
                  status, startRecording, stopRecording, mediaBlobUrl,
                }) => ((
                  <div>
                    <p>{status}</p>
                    <button type="button" onClick={startRecording}>Start Recording</button>
                    <button type="button" onClick={stopRecording}>Stop Recording</button>
                    <video src={mediaBlobUrl} controls autoPlay loop />
                  </div>
                ))}
 />

but the screen share permission call twice. one after render and one after calling the startRecording.
It is a BUG i think...

audio file format

Hi,

I am trying to record audio in the browser

    const {
        status,
        startRecording,
        stopRecording,
        mediaBlobUrl,
    } = useReactMediaRecorder({
        video: false,
        audio: true,
        blobPropertyBag: {
            type: "audio/wav"
        }
    });

and fetching the file from it

            const audioBlob = await fetch(mediaBlobUrl).then(r => r.blob());

            console.log(audioBlob);

            const audiofile = new File([audioBlob], `${uuidv4()}.wav`, { type: "audio/wav" })

Now i saved this file in disk, and used file audio.wav

and it shows up as as WebM file

$ file b61508fa-9c4e-47fc-bb54-5def7abf9bfc.wav                                                         ─╯
b61508fa-9c4e-47fc-bb54-5def7abf9bfc.wav: WebM

what i need is a wav file ! and it is giving me a WebM file

Can you please provide further information about each values of status props in the render function?

Hi
I'm developing a video recording function in our website, btw, I'm facing some issues in the status props of render function, so I need detailed information about those values.
Anyone can provide further information about these values of status please? :)

media_aborted
media_in_use
invalid_media_constraints
no_constraints
recorder_error
acquiring_media
stopping

Looking forward to hearing from you soon!

Thanks!

Maximum 10min video recording validation

Hi
I'm developing a video recording functionality in our website, I have to add validations, maximum video recording should be 10min after that it should automatically stop recording. So can anybody help me in achieving this.

Looking forward to hearing from you soon!

Thanks!

Bug reports + Questions

Followed a bug from a screen recording app and ended up here.
Think I've narrowed down the issue and possible fixes.

The main one is: Mic not disconnected after screen recording.

MediaStreamTrack.stop() MDN Reference

The other one is: Incorrect default blob type format for screen recording video.

  • When the user enables the screen option without video i.e screen=true, video=false(default) and does not provide a blobPropertyBag the type defaults to audio/wav which may not be ideal for video.
    Happens 👇
    https://github.com/0x006F/react-media-recorder/blob/e0838baf2c833ce0c8b7f3b4d6c3b9f3dd212ce4/src/index.ts#L182-L184

    Another way to obtain defaults may be

    let [sampleChunk] = mediaChunks.current; // <-- chunks are Blobs 🎉
    
    let blobProperty = Object.assign({ 
        type: sampleChunk.type
    }, blobPropertyBag); // <-- If that is undefined/null it uses the default
    // but it also accepts strings & arrays. 
    // Although it shouldn't matter that much since Blob will ignore unknown options anyway.

One question I have is when the component is mounted, it immediately requests for a media source. Is that the intended behavior? Are there downsides to letting the user control that? Maybe exposing the getMediaStream function? No?

Also I could be wrong but this feels a bit redundant
https://github.com/0x006F/react-media-recorder/blob/e0838baf2c833ce0c8b7f3b4d6c3b9f3dd212ce4/src/index.ts#L148-L154

Doubt the extra await step inside loadStream makes any difference since the enclosing function is invoked asynchronously at the top level (inside useEffect), so calling getMediaStream directly (inside useEffect) will have the same outcome but without the unnecessary extra function.

Example test

function timeout(delay, result) { return new Promise(resolve => setTimeout(resolve, delay, result)); }

timeout(2000, 'done'); // <-- Promise {<pending>}
await timeout(2000, 'done'); // <-- Waits 2sec and prints 'done'

async function loadTimeout(...args) { return await timeout(...args); }

loadtimeout(2000, 'done'); // <-- Promise {<pending>} (No different from initial invocation of timeout without await)
await loadTimeout(2000, 'done'); // <-- Waits 2sec and prints 'done'

async function wait() { await timeout(2000, 'just wait'); }

wait(); // <-- Promise {<pending>} (also no different from initial invocation of timeout without await)
await wait(); // <-- Waits 2sec and prints undefined

Otherwise great stuff! 🎉

Got inspired by this repo to roll out a (shameless plug 😁) hooks version for fun and learn about the MediaRecorder API in the process.

It does have its challenges e.g. trying to figure out how to disconnect all connected media sources (camera/mic) when a component is no longer mounted and also compose tests.
Any feedback is welcome 🙂 Cheers.

Unhandled DOMException after first successful screen recording

Hi, thanks for this amazing library. Here is the issue I have and this is how to produce it:

  1. Record my screen (with screen: true prop)
  2. Finish it is successfully
  3. On second attempt to record I deny permission (for screen capture) and I get this error:

2021-11-16 15_12_04-Window

edit: forgot my manners

Ask browser permission only on start recording

Right now it is asking permission on page load and it disappoints the users when we implement this snippet on a large web app.

So can we add a condition to ask permission only on start recording?
@0x006F

How to render audios separately?

I'm using Lib with hook, everything works normally, but how do I get the audio and leave it separate?
I want the audio to be rendered only when the stop button is pressed, for it to stay on the screen and I can click again and record another audio. All recorded audios must remain on the screen. (like a whatsapp conversation)

Currently the site already starts with an empty audio and every time a new one is recorded it replaces

My code:

import React from 'react';
import { useReactMediaRecorder } from "react-media-recorder";

import { Container } from './styles';

const VoideRercorderMedia = () => {

  const {
    status,
    startRecording,
    stopRecording,
    mediaBlobUrl,
  } = useReactMediaRecorder({ video: false,
    audio: true,
    blobPropertyBag: { type: "audio/webm" } 
  });


  return (
    <div>
      <p>{status}</p>
      <button onClick={startRecording}>Start Recording</button>
      <button onClick={stopRecording}>Stop Recording</button>
      <audio src={mediaBlobUrl} controls /> 
    </div>
  );
};

export default VoideRercorderMedia;

Site with empty audio
image

Site after record
image

Toggle mic state during recording

I want to toggle mic state on/off while recording. I tried it by changing the audio value in useReactMediaRecorder but it considers only the initial value.

How could I achieve this?

How do I deactivate camera when I leave page?

When I move to the record page and allow the permission then without recording if I go to the different page still camera get active. So How do I deactivate camera when I go to the another page?

Track not stopping

Since 1.2.0 upgrade, it looks like stream tracks are not stopping, and the chrome red light is left on even after component unmount.
Does anyone have the same issue ?

I tried to stop the stream tracks through a "VideoPreview" function component with no success !

const VideoPreview = ({ stream, status}) => {
  const videoRef = useRef()

  useEffect(() => {
    if (videoRef.current && stream) {
      videoRef.current.srcObject = stream;
    }
    return () => {
      if (status == 'stopped') {
        stream.getTracks().forEach(track => track.stop())
        stream.getTracks().forEach(track => (track.enabled = false))
      }
    }
  }, [stream]);

  if (!stream)
    return null;

  return <video ref={videoRef} id="localVideo" className="video-preview" autoPlay muted/>;
};

Seems like there's a missing opened stream left unstopped somewhere...
Would that be a bug on our side ?

no_specified_media_found issue

Hi there,

A user of mine reports that he gets the issue: no_specified_media_found in Chrome.

However, it works in Firefox.

What can be the reason for this issue, and how to resolve it?

react-media-recorder version 0.7.1.

Problems with videos recorder in Chrome

Hi,

I have several problems with the screen recorder component all the functions are working well but When I record the video on Chrome and save it on the firebase store and try to reproduce the video in another browser it is not reproduced, I tried it with firefox and have this issue. I see that the file is saved as web but the mime-type is video/x-matroska I tried to change it with the properties blobPropetyBag and mediaRecorderOptions but this change not working.

The video is playing fine in Chrome. However, the same video does not open in Firefox. Conversely, a video recorded in Firefox plays fine in both Chrome and Firefox.

image

How could I change the mime-type for these videos ???

Audio recording preview not working

Hi,

I'm trying to create a preview for both audio and video recordings. The video preview works fine but the audio preview doesn't enable the autoplay property, so you've no feedback for the audio recording. I assume that this might be because the MediaStream object is not active (it has the property active: false) even though the recording seems to be active as when I stop the recording the blob is available.

Any hints? Have you ever implemented the audio preview does it work for you?

Regards,
Bogdan

Change video source

Is there already a way to change/select the video source when capturing? i.e - if i have two cameras, select which one to record with?

Also - is there a way to preview the stream/video before actually recording anything?

Thanks!

How to start automatic screen recording

Hi @0x006F Thanks for the repo,

I want to start screen recording implicitly after component loaded

What I tried is <button className="start" onClick={startRecording}>Start Recording</button> after that in componentDIdMount() {$('.start').click();}. screen is recording but the problem is Screen share permission dialog is coming two times. I don't know what to do. Please help me

Unable to use with Snowpack due to multiple versions of React

If your site is using React 17 and you're using Snowpack, if you try to add react-media-recorder, you'll see hook errors due to multiple versions of React. Snowpack will try to include both React 16 and 17.

Solutions may be to ensure React 16 is not considered a dependency for this package.

Can you add the function the get the Blob object?

Hi dude, I was using trying to implement your library but in my app i need the Blob object, can you do something like

<ReactMediaRecorder
video
render={({ status, startRecording, stopRecording, mediaBlobUrl, blobObject, previewStream }) => {
//.... my code
}}
/>

Is not recording the audio of the video that I am playing on my screen

Hi,
I am developing a service to make video calls and record the user screen with this component. I am trying to record the user screen on a page with an Agora.io call, that is a service that runs on top of RTC Stream to allow video calls between clients.
I've succeeded to record my screen with my microphone audio and webcam video, and the video coming from the stream as part of my screen. But the resulting blob comes with no audio coming from the screen, only my microphone audio. There are something that i am doing wrong? i want to record both my mic audio and the video call audio. Is it Possible? Heres my code.

<ReactMediaRecorder screen={true} blobPropertyBag={{type: "video/mp4" }} render={({status, startRecording, stopRecording, mediaBlobUrl, pauseRecording, resumeRecording}) => (


         <div className="ag-header-msg">
           <div style={{width: "45%" }}>
             <p style={{color: "#FFF"}}>

              Room:&nbsp;<span id="room-name">{channel}</span>
             </p>

           </div>

           <div style={{width: "50%", display: 'flex', justifyContent: 'space-between'}}>
             <div style={{display: 'flex', justifyItems: 'center', alignItems: 'center', width: 75}}>

     
          
         </div>
       </div>
       <div className="ag-main">
         <div className="ag-container">
           <AgoraVideoCall
            videoProfile={videoProfile}
            channel={channel}
            transcode={transcode}
            attendeeMode={attendeeMode}
            baseMode={baseMode}
            appId={appId}
            uid={uid}
            
          />
        {/* <video src={mediaBlobUrl} controls autoPlay loop /> */}
        </div>
      </div>
  </div>
  )}
  />

send blob to server

hi
Thanks for creating this package
Where do I access the blob itself?
How can I send the blob as file to the server?

How can I get previewStream back after clearing blob url?

I'm building an app where someone can record a video. The first part is just the preview stream which works great when the initially load the page. They tap the record button and it starts recording while still showing the preview. Once they're done recording they hit the stop button and then we no longer show the preview stream and instead give them the video they recorded. If they decide they don't like it and want to try again, we're clearing the blob url and we go back to the first step.

At this point, the previewStream is no longer working. The MediaStream is no longer active and I'm not sure if there is a good way to reactivate it or if I need to totally re-run the useReactMediaRecorder hook.

Any help is appreciated!

export default function RecordPage() {
  const {
    status,
    startRecording,
    stopRecording,
    mediaBlobUrl,
    previewStream,
    clearBlobUrl,
    error
  } = useReactMediaRecorder({
    video: true
  });

  console.log('status', status);
  console.log('error', error);
  console.log('mediaBlobUrl', mediaBlobUrl);
  console.log('previewStream', previewStream);

  if (status === "idle" || (status === "stopped" && !mediaBlobUrl)) {
    return <Ready previewStream={previewStream} startRecording={startRecording} />;
  } else if (status === "recording") {
    return <Recording previewStream={previewStream} stopRecording={stopRecording} />;
  } else if (status === "stopped" && mediaBlobUrl) {
    return <DoneRecording mediaBlobUrl={mediaBlobUrl} clearBlobUrl={clearBlobUrl} />;
  }

  return <p>hello</p>;
}

Chrome saves file like video/x-matroska

Hi!
I'm recording videos on chrome and firefox but the mimeType is always diferent in each browser, on chrome is saved like video/x-matroska while in firefox is a video/webm.
If I download the video, it is saved like .webm but is a .mkv
My code

`const confVideo = {
width: 1080,
height: 720,
frameRate: 20,
};

const mediaRecorderOptions = {
mimeType: "video/webm",
};

const blobPropertyBag = {
type: "video/webm",
};

const { status, startRecording, stopRecording, mediaBlobUrl } = useReactMediaRecorder({ screen: true, video: confVideo, mediaRecorderOptions: mediaRecorderOptions, blobPropertyBag: blobPropertyBag });`

I read some documentation https://chromium.googlesource.com/chromium/src/+/HEAD/third_party/blink/renderer/modules/mediarecorder/README.md
image

Specify video input device

Hi,

Is it currently possible to specify the input device id? It did not look like it to me but I wanted to confirm.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.