AudioRecorder
The AudioRecorder
class allows you to record audio data to a file. It provides functionalities to start, stop, pause, and manage audio recordings, with configurable settings for audio quality, sample rate, format, and more.
Features
- Record audio from the system’s active input device.
- Record for a specified duration or until manually stopped.
- Pause and resume recordings.
- Delete recorded audio files.
Usage
Setup SharedAudioSesion
Before create an AudioRecorder instance, we need to setup the SharedAudioSession
, the audio session is hardware-related and should be properly activated.
1await SharedAudioSession.setActive(true)
2await SharedAudioSession.setCategory(
3 "playAndRecord",
4 ["defaultToSpeaker"]
5)
Creating an AudioRecorder Instance
To create an audio recorder, use the create
method:
1async function createRecorder() {
2 try {
3 const filePath = Path.join(
4 FileManager.documentsDirectory,
5 "recording.m4a"
6 )
7 const recorder = await AudioRecorder.create(filePath, {
8 format: "MPEG4AAC",
9 sampleRate: 44100,
10 numberOfChannels: 2,
11 encoderAudioQuality: AVAudioQuality.high
12 })
13 return recorder
14 } catch (error) {
15 console.error("Failed to create recorder: ", error)
16 }
17}
Recording Audio
You can start recording using the record()
method:
1async function startRecording() {
2 const recorder = await createRecorder()
3 if (recorder) {
4 const success = recorder.record()
5 console.log("Recording started: ", success)
6 }
7}
You can also provide options to control when to start recording and for how long:
1function startSynchronizedRecording(recorderOne, recorderTwo) {
2 let timeOffset = recorderOne.deviceCurrentTime + 0.01
3
4 // Synchronize the recording time of both recorders.
5 recorderOne.record({ atTime: timeOffset })
6 recorderTwo.record({ atTime: timeOffset })
7}
Pausing and Stopping the Recording
To pause a recording:
1function pauseRecording(recorder) {
2 recorder.pause()
3 console.log("Recording paused.")
4}
To stop a recording:
1function stopRecording(recorder) {
2 recorder.stop()
3 console.log("Recording stopped.")
4}
Deleting a Recording
To delete the recorded file:
1function deleteRecording(recorder) {
2 const success = recorder.deleteRecording()
3 console.log("Recording deleted: ", success)
4}
Disposing of the Recorder
You should call dispose()
when the recorder is no longer needed to free up resources:
1function disposeRecorder(recorder) {
2 recorder.dispose()
3 console.log("Recorder disposed.")
4}
Event Handling
You can use the onFinish
and onError
callbacks to handle recording completion and errors:
1async function setupRecorder() {
2 const recorder = await createRecorder()
3 if (recorder) {
4 recorder.onFinish = (success) => {
5 console.log("Recording finished successfully: ", success)
6 }
7
8 recorder.onError = (message) => {
9 console.error("Recording error: ", message)
10 }
11 }
12}
API Reference
AudioRecorder.create(filePath, settings?)
Creates an AudioRecorder
instance with specified settings.
- filePath (string): The file system location to record to.
- settings (optional object): The audio settings for the recording:
- format (AudioFormat): The format of the audio data. Options: "LinearPCM", "MPEG4AAC", "AppleLossless", "AppleIMA4", "iLBC", "ULaw".
- sampleRate (number): The sample rate in hertz (8000 to 192000).
- numberOfChannels (number): The number of channels (1 to 64).
- encoderAudioQuality (AVAudioQuality): The quality of the audio encoding (from
AVAudioQuality.min
to AVAudioQuality.max
).
Returns: A Promise
that resolves with an AudioRecorder
instance.
AudioRecorder.isRecording
A boolean indicating whether the recorder is recording.
AudioRecorder.currentTime
The time, in seconds, since the beginning of the recording.
AudioRecorder.deviceCurrentTime
The current time of the host audio device, in seconds.
AudioRecorder.record(options?)
Starts recording audio.
- options (optional object): Recording options:
- atTime (number): The time at which to start recording, relative to
deviceCurrentTime
.
- duration (number): The duration of the recording, in seconds.
Returns: A boolean indicating whether recording started successfully.
AudioRecorder.pause()
Pauses the current recording.
AudioRecorder.stop()
Stops recording and closes the audio file.
AudioRecorder.deleteRecording()
Deletes the recorded audio file.
Returns: A boolean indicating whether the deletion was successful.
AudioRecorder.dispose()
Releases resources used by the recorder.
AudioRecorder.onFinish
Callback function invoked when the recording finishes.
- success (boolean): Indicates whether the recording finished successfully.
AudioRecorder.onError
Callback function invoked when an encoding error occurs.
- message (string): Describes the error.
Example Usage
1import { Path } from 'scripting'
2
3async function run() {
4
5 await SharedAudioSession.setActive(true)
6 await SharedAudioSession.setCategory(
7 "playAndRecord",
8 ["defaultToSpeaker"]
9 )
10
11 try {
12 const filePath = Path.join(
13 FileManager.documentsDirectory,
14 "recording.m4a"
15 )
16 const recorder = await AudioRecorder.create(filePath, {
17 format: "MPEG4AAC",
18 sampleRate: 48000,
19 numberOfChannels: 2,
20 encoderAudioQuality: AVAudioQuality.high
21 })
22
23 recorder.onFinish = (success) => console.log("Recording finished successfully: ", success)
24 recorder.onError = (message) => console.error("Recording error: ", message)
25
26 recorder.record()
27 setTimeout(() => {
28 recorder.stop()
29 }, 5000) // Stop recording after 5 seconds
30 } catch (error) {
31 console.error("Error: ", String(error))
32 }
33}
34
35run()
Use the AudioRecorder
class to easily manage audio recording operations in your scripts, providing flexibility and control over the audio recording process.