Skip to main content

Using the SoundRecorder

Recording sounds requires two steps:

  1. Add the SoundRecorder node to the scene.
  2. Control the SoundRecorder node with its start() and stop() methods

Add the SoundRecorder

Create a new SoundRecorder node and specify the preferred MIME type of the recorded audio. The MIME type determines the file type of the audio.

A complication is that the supported audio recorder MIME types vary by browser. Desktop browsers support many more types than mobile browsers. And types vary by platform. For example, Android browsers tend to support audio recording only in WebM, while iOS browsers support audio recording only in MP4.

A good strategy is to specify either WebM or MP4 as the preferred MIME type, and both of them as backups. If the device does not support any of the preferred or backup MIME types, whatever type the device supports will be used as a fallback.

const recorder = new SoundRecorder({
mimeType: "audio/webm",
backupMimeTypes: ["audio/webm", "audio/mp4"],
});
sceneOne.addChild(recorder);

Control the SoundRecorder

To begin recording audio, call the start() method on the SoundPlayer:

  • If this is the first time the user has used this game to record audio, the browser will ask permission to record audio. If the user grants permission, the audio recording will begin. If the user declines permission, it will throw an exception. Thus, it is highly recommended to place the start() method in a try/catch block to handle this possibility.
  • The start() method is asynchronous and should be awaited to ensure the expected order of execution in the code block.

To end recording audio, call the stop() method on the SoundPlayer:

  • The stop() method returns the results of the audio recording. The result is a SoundRecorderResults object, which contains information such as the MIME type that was used, the duration, beginning and ending time stamps, and audio data as both a base64 string and a Blob.
  • The stop() method is asynchronous and must be awaited.
danger

If the stop() method is not awaited, the results will be a Promise and the useable data will be lost.

The example below will record audio when the "START" button is pressed. When "STOP" is pressed, recording will end. In the console, the results of the recording is shown. If you copy the base64 data, you can paste it into a website such as https://base64.guru/converter/decode/audio to hear the audio.

Loading...