1. Overview
This API attempts to make basic recording very simple, while still allowing for
more complex use cases. In the simplest case, the application instantiates a MediaRecorder object, calls start() and then calls stop() or waits
for the MediaStreamTrack(s) to be ended. The contents of the recording will
be made available in the platform’s default encoding via the ondataavailable event. Functions are available to query the platform’s available set of
encodings, and to select the desired ones if the author wishes. The application
can also choose how much data it wants to receive at one time. By default a Blob containing the entire recording is returned when the recording
finishes. However the application can choose to receive smaller buffers of data
at regular intervals.
2. Media Recorder API
[Constructor(MediaStream stream, optional MediaRecorderOptions options)] interface MediaRecorder : EventTarget { readonly attribute MediaStream stream; readonly attribute DOMString mimeType; readonly attribute RecordingState state; attribute EventHandler onstart; attribute EventHandler onstop; attribute EventHandler ondataavailable; attribute EventHandler onpause; attribute EventHandler onresume; attribute EventHandler onerror; readonly attribute unsigned long videoBitsPerSecond; readonly attribute unsigned long audioBitsPerSecond; void start(optional long timeslice); void stop(); void pause(); void resume(); void requestData(); static boolean isTypeSupported(DOMString type); };
2.1. Constructors
MediaRecorder(MediaStream stream, optional MediaRecorderOptions options)-
Parameter Type Nullable Optional Description stream MediaStream✘ ✘ The MediaStreamto be recorded. This will be the value of thestreamattribute.options MediaRecorderOptions✘ ✔ A dictionary of options to for the UA instructing how the recording will take part. options.mimeType, if present, will become the value ofmimeTypeattribute.
2.2. Attributes
stream, of type MediaStream, readonly- The
MediaStreamto be recorded. mimeType, of type DOMString, readonly-
The MIME type [RFC2046] that has been selected as the container
for recording. This entry includes all the parameters to the base
mimeType. The UA should be able to play back any of the MIME types it supports for recording. For example, it should be able to display a video recording in the HTML <video> tag. The default value for this property is platform-specific. state, of type RecordingState, readonly- The current state of the
MediaRecorderobject. When theMediaRecorderis created, the UA MUST set this attribute toinactive. onstart, of type EventHandler- Called to handle the start event.
onstop, of type EventHandler- Called to handle the stop event.
ondataavailable, of type EventHandler- Called to handle the dataavailable event. The
Blobof recorded data is contained in this event and can be accessed via itsdataattribute. onpause, of type EventHandler- Called to handle the pause event.
onresume, of type EventHandler- Called to handle the resume event.
onerror, of type EventHandler- Called to handle a
MediaRecorderErrorEvent. videoBitsPerSecond, of type unsigned long, readonly- The value of the Video encoding target bit rate that was passed to
the Platform (potentially truncated, rounded, etc), or the calculated
one if the user has specified
bitsPerSecond. audioBitsPerSecond, of type unsigned long, readonly- The value of the Audio encoding target bit rate that was passed to
the Platform (potentially truncated, rounded, etc), or the calculated
one if the user has specified
bitsPerSecond.
2.3. Methods
start(optional long timeslice)-
When a
MediaRecorderobject’sstart()method is invoked, the UA MUST run the following steps:- Let target be the MediaRecorder context object.
- Let timeslice be the method’s first argument, if provided,
or
undefined. - If
stateis notinactive, throw anInvalidStateErrorDOMExceptionand abort these steps. - If the
stream's isolation properties disallow access from thisMediaRecorder, throw aSecurityErrorDOMExceptionand abort these steps. -
Set
statetorecording, and run the following steps in parallel:- Once media becomes available from one or more of the
stream's tracks, start gathering the data into aBlobblob and queue a task, using the DOM manipulation task source, to fire an event named start at target. -
If at any point the
stream's isolation properties change so thatMediaRecorderis no longer allowed access to it, the UA MUST immediately stop gathering data, discard any data that it has gathered, and queue a task, using the DOM manipulation task source, that runs the following steps:- Set
statetoinactive. - Fire an error event named
SecurityErrorat target. - Fire a blob event named dataavailable at target with blob.
- Fire an event named stop at target.
- Set
-
If the UA at any point is unable to continue gathering data for
reasons other than isolation properties, it MUST stop gathering data, and
queue a task, using the DOM manipulation task source, that runs the
following steps:
- Set
statetoinactive. - Fire an error event named
UnknownErrorat target. - Fire a blob event named dataavailable at target with blob.
- Fire an event named stop at target.
- Set
-
If timeslice is not
undefined, then once a minimum of timeslice milliseconds of data have been collected, or some minimum time slice imposed by the UA, whichever is greater, start gathering data into a newBlobblob, and queue a task, using the DOM manipulation task source, that fires a blob event named dataavailable at target with blob.Note that an
undefinedvalue of timeslice will be understood as the largestlongvalue. -
If all recorded tracks become
ended, then stop gathering data, and queue a task, using the DOM manipulation task source, that runs the following steps:- Set
statetoinactive. - Fire a blob event named dataavailable at target with blob.
- Fire an event named stop at target.
- Set
- Once media becomes available from one or more of the
- return
undefined.
Note that
stop(),requestData(), andpause()also affect the recording behavior.The UA MUST record
streamin such a way that the original Tracks can be retrieved at playback time. When multipleBlobs are returned (because oftimesliceorrequestData()), the individual Blobs need not be playable, but the combination of all the Blobs from a completed recording MUST be playable.If any Track within the
MediaStreamismutedor notenabledat any time, the UA will only record black frames or silence since that is the content produced by the Track.Parameter Type Nullable Optional Description timeslice long✘ ✔ The minimum number of milliseconds of data to return in a single Blob. stop()-
When a
MediaRecorderobject’sstop()method is invoked, the UA MUST run the following steps:-
If
stateisinactivethrow anInvalidStateErrorDOMExceptionand terminate these steps. Otherwise the UA MUST queue a task, using the DOM manipulation task source, that runs the following steps:- Set
statetoinactiveand stop gathering data. - Let blob be the Blob of collected data so far and let target be the MediaRecorder context object, then fire a blob event named dataavailable at target with blob.
- Fire an event named stop at target.
- Set
- return
undefined.
-
If
pause()-
When a
MediaRecorderobject’spause()method is invoked, the UA MUST run the following steps:-
If
stateisinactivethrow anInvalidStateErrorDOMExceptionand terminate these steps. Otherwise the UA MUST queue a task, using the DOM manipulation task source, that runs the following steps:- Set
statetopaused. - Stop gathering data into blob (but keep it available so that recording can be resumed in the future).
- Let target be the MediaRecorder context object. Fire an event named pause at target.
- Set
- return
undefined.
-
If
resume()-
When a
MediaRecorderobject’sresume()method is invoked, the UA MUST run the following steps:-
If
stateisinactivethrow anInvalidStateErrorDOMExceptionand terminate these steps. Otherwise the UA MUST queue a task, using the DOM manipulation task source, that runs the following steps:- Set
statetorecording. - Resume (or continue) gathering data into the current blob.
- Let target be the MediaRecorder context object. Fire an event named resume at target.
- Set
- return
undefined.
-
If
requestData()-
When a
MediaRecorderobject’srequestData()method is invoked, the UA MUST run the following steps:-
If
stateisinactivethrow anInvalidStateErrorDOMExceptionand terminate these steps. Otherwise the UA MUST queue a task, using the DOM manipulation task source, that runs the following steps:- Let blob be the
Blobof collected data so far and let target be theMediaRecordercontext object, then fire a blob event named dataavailable at target with blob. (Note that blob will be empty if no data has been gathered yet.) - Create a new Blob and gather subsequent data into it.
- Let blob be the
- return
undefined.
-
If
isTypeSupported(DOMString type)-
Check to see whether a
MediaRecordercan record in a specified MIME type. If true is returned from this method, it only indicates that theMediaRecorderimplementation is capable of recordingBlobobjects for the specified MIME type. Recording may still fail if sufficient resources are not available to support the concrete media encoding. When this method is invoked, the User Agent must run the following steps:- If
typeis an empty string, then return true (note that this case is essentially equivalent to leaving up to the UA the choice of container and codecs on constructor). - If
typedoes not contain a valid MIME type string, then return false. - If
typecontains a media type or media subtype that the MediaRecorder does not support, then return false. - If
typecontains a media container that the MediaRecorder does not support, then return false. - If
typecontains a codec that the MediaRecorder does not support, then return false. - If the MediaRecorder does not support the specified combination of media type/subtype, codecs and container then return false.
- Return true.
Parameter Type Nullable Optional Description type DOMString✘ ✘ A MIME Type, including parameters when needed, specifying a container and/or codec formats for recording. - If
2.4. Data handling
To fire a blob event with a Blob blob means to fire an event at target using a BlobEvent with
its data attribute initialized to blob.
2.5. MediaRecorderOptions
dictionary MediaRecorderOptions { DOMString mimeType; unsigned long audioBitsPerSecond; unsigned long videoBitsPerSecond; unsigned long bitsPerSecond; };
2.5.1. Members
mimeType, of type DOMString-
The container and codec format(s) [RFC2046] for the recording, which
may include any parameters that are defined for the format. If the UA does not
support the format or any of the parameters specified, it MUST throw a
NotSupportedErrorDOMException. If this paramater is not specified, the UA will use a platform-specific default format. The container format, whether passed in to the constructor or defaulted, will be used as the value of themimeTypeattribute. audioBitsPerSecond, of type unsigned long- Aggregate target bits per second for encoding of the Audio track(s), if any. This is a hint for the encoder and the value might be surpassed, not achieved, or only be achieved over a long period of time.
videoBitsPerSecond, of type unsigned long- Aggregate target bits per second for encoding of the Video track(s), if any. This is a hint for the encoder and the value might be surpassed, not achieved, or only be achieved over a long period of time.
bitsPerSecond, of type unsigned long- Aggregate target bits per second for encoding of all Video and Audio
Track(s) present. This parameter overrides either
audioBitsPerSecondorvideoBitsPerSecondif present, and might be distributed among the present track encoders as the UA sees fit. This parameter is a hint for the encoder(s) and the total value might be surpassed, not achieved, or only be achieved over a long period of time.
2.6. RecordingState
enum RecordingState {
"inactive",
"recording",
"paused"
};
2.6.1. Values
inactive- Recording is not occuring: Either it has not been started or it has been stopped.
recording- Recording has been started and the UA is capturing data.
paused- Recording has been started, then paused, and not yet stopped or resumed.
3. Blob Event
[Constructor(DOMString type, BlobEventInit eventInitDict)] interface BlobEvent : Event { [SameObject] readonly attribute Blob data; readonly attribute DOMHighResTimeStamp timecode; };
3.1. Constructors
BlobEvent(DOMString type, BlobEventInit eventInitDict)
3.2. Attributes
data, of type Blob, readonly- The encoded
Blobwhosetypeattribute indicates the encoding of the blob data. timecode, of type DOMHighResTimeStamp, readonly- The difference between the timestamp of the first chunk in
dataand the timestamp of the first chunk in the firstBlobEventproduced by this recorder. Note that thetimecodein the first producedBlobEventdoes not need to be zero.
3.3. BlobEventInit
dictionary BlobEventInit { required Blob data; DOMHighResTimeStamp timecode; };
3.3.1. Members
data, of type Blob- A
Blobobject containing the data to deliver viaBlobEvent. timecode, of type DOMHighResTimeStamp- The timecode to be used in initializing
BlobEvent.
4. Error handling
4.1. General principles
This section is non-normative.The UA will throw a DOMException when the error can be detected at the time
that the call is made. In all other cases the UA will fire an event named MediaRecorderErrorEvent. If recording has been started and not yet stopped
when the error occurs, let blob be the Blob of collected data so
far; after raising the error, the UA will fire a
dataavailable event with blob; immediately after the UA will then fire an event named stop.
The UA may set platform-specific limits, such as those for the minimum and
maximum Blob size that it will support, or the number of MediaStreamTracks it will record at once.
It will signal a fatal error if these limits are exceeded.
4.2. MediaRecorderErrorEvent
The MediaRecorderErrorEvent interface is defined for cases when an event is
raised that was caused by an error.
To fire an error event named e with a DOMException named error means that an
event with the name e, which does not bubble (except where otherwise
stated) and is not cancelable (except where otherwise stated), and which uses
the MediaRecorderErrorEvent interface with the error attribute set to error, must be
created and dispatched at
the given target.
dictionary MediaRecorderErrorEventInit : EventInit { required DOMException error; }; [Exposed=Window, Constructor(DOMString type, MediaRecorderErrorEventInit eventInitDict)] interface MediaRecorderErrorEvent : Event { [SameObject] readonly attribute DOMException error; };
4.2.1. Constructors
MediaRecorderErrorEvent(DOMString type, MediaRecorderErrorEventInit eventInitDict)-
Constructs a new
MediaRecorderErrorEvent.Parameter Type Nullable Optional Description type DOMString✘ ✘ eventInitDict MediaRecorderErrorEventInit✘ ✘
4.2.2. Attributes
error, of type DOMException, readonly- The DOMException error that triggered the event.
4.2.3. MediaRecorderErrorEventInit
error, of type DOMException-
The
DOMExceptioncausing the error that triggered the event. An explanatory message about the error circumstances MAY be provided in its message attribute.If an implementation places non-standard properties onDOMException, exposing e.g. stack traces or error line numbers, these are encouraged to point to whichever method call most closely identifies the run-time operation that caused the error, e.g.start().
4.3. Exception Summary
Each of the exceptions defined in this document is a DOMException with a
specific type.
| Name | Description |
|---|---|
InvalidStateError
| An operation was called on an object on which it is not allowed or at a time when it is not allowed, or if a request is made on a source object that has been deleted or removed. |
NotSupportedError
| A MediaRecorder could not be created due to unsupported options
(e.g. MIME type) specification. User agents should provide as much
additional information as possible in the message attribute.
|
SecurityError
| The isolation properties of the MediaStream do not allow the
MediaRecorder access to it.
|
5. Event summary
The following additional events fire on MediaRecorder objects:
| Event name | Interface | Fired when... |
|---|---|---|
| start | Event
| The UA has started recording data from the MediaStream. |
| stop | Event
| The UA has stopped recording data from the MediaStream. |
| dataavailable | BlobEvent
| The UA generates this even to return data to the application. The data attribute of this event contains a Blob of recorded
data.
|
| pause | Event
| The UA has paused recording data from the MediaStream. |
| resume | Event
| The UA has resumed recording data from the MediaStream. |
| error | MediaRecorderErrorEvent
| An error has occurred, e.g. out of memory or a modification to
the stream has occurred that makes it impossible to
continue recording (e.g. a Track has been added to or removed from
the said stream while recording is occurring).
|
6. Examples
6.1. Check for MediaRecorder and content types
This example checks if the implementation supports a few popular codec/container combinations.
if (window.MediaRecorder == undefined) { console.error('MediaRecorder not supported, boo'); } else { var contentTypes = ["video/webm", "video/webm;codecs=vp8", "video/x-matroska;codecs=avc1", "audio/webm", "video/mp4;codecs=avc1", "video/invalid"]; contentTypes.forEach(contentType => { console.log(contentType + ' is ' + (MediaRecorder.isTypeSupported(contentType) ? 'supported' : 'NOT supported ')); }); }
6.2. Recording webcam video and audio
This example captures an video+audio MediaStream using getUserMedia(),
plugs it into a <video> tag and tries to record it,
retrieving the recorded chunks via the ondataavailable event. Note that the
recording will go on forever until either MediaRecorder is stop()ed or all
the MediaStreamTracks of the recorded MediaStream are ended.
<html> <body> <video autoplay/> <script> var recordedChunks = []; function gotMedia(stream) { // |video| shows a live view of the captured MediaStream. var video = document.querySelector('video'); video.src = URL.createObjectURL(stream); var recorder = null; try { recorder = new MediaRecorder(stream, {mimeType : "video/webm"}); } catch (e) { console.error('Exception while creating MediaRecorder: ' + e); return; } recorder.ondataavailable = (event) => { console.log(' Recorded chunk of size ' + event.data.size + "B"); recordedChunks.push(event.data); }; recorder.start(100); } navigator.mediaDevices.getUserMedia({video: true , audio: true}) .then(gotMedia) .catch(e => { console.error('getUserMedia() failed: ' + e); }); </script> </body> </html>
recordedChunks can be saved to a file using e.g. the function download() in the MediaRecorder Web Fundamentals article.