• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Using AVRecorder for Audio Recording
2
3You will learn how to use the AVRecorder to develop audio recording functionalities including starting, pausing, resuming, and stopping recording.
4
5During application development, you can use the **state** attribute of the AVRecorder to obtain the AVRecorder state or call **on('stateChange')** to listen for state changes. Your code must meet the state machine requirements. For example, **pause()** is called only when the AVRecorder is in the **started** state, and **resume()** is called only when it is in the **paused** state.
6
7**Figure 1** Recording state transition
8
9![Recording state change](figures/recording-status-change.png)
10
11For details about the state, see [AVRecorderState](../reference/apis/js-apis-media.md#avrecorderstate9).
12
13
14## How to Develop
15
16Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API reference.
17
181. Create an **AVRecorder** instance. The AVRecorder is the **idle** state.
19
20   > **NOTE**
21   >
22   > Perform the subsequent operations after the AV recorder completes value assignment, that is, after **avRecorder = recorder;** is executed.
23
24   ```ts
25   import media from '@ohos.multimedia.media';
26
27   let avRecorder: media.AVRecorder;
28   media.createAVRecorder().then((recorder: media.AVRecorder) => {
29     avRecorder = recorder;
30   }, (error: Error) => {
31     console.error(`createAVRecorder failed`);
32   })
33   ```
34
352. Set the events to listen for.
36   | Event Type| Description|
37   | -------- | -------- |
38   | stateChange | Mandatory; used to listen for changes of the **state** attribute of the AVRecorder.|
39   | error | Mandatory; used to listen for AVRecorder errors.|
40
41
42   ```ts
43   // Callback function for state changes.
44   avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => {
45     console.log(`current state is ${state}`);
46     // You can add the action to be performed after the state is switched.
47   })
48
49   // Callback function for errors.
50   avRecorder.on('error', (err: BusinessError) => {
51     console.error(`avRecorder failed, code is ${err.code}, message is ${err.message}`);
52   })
53   ```
54
553. Set audio recording parameters and call **prepare()**. The AVRecorder enters the **prepared** state.
56   > **NOTE**
57   >
58   > Pay attention to the following when configuring parameters:
59   >
60   > - In pure audio recording scenarios, set only audio-related parameters in **avConfig** of **prepare()**.
61   > If video-related parameters are configured, an error will be reported in subsequent steps. If video recording is required, follow the instructions provided in [Video Recording Development](video-recording.md).
62   >
63   > - The [recording formats](avplayer-avrecorder-overview.md#supported-formats) in use must be those supported by the system.
64   >
65   > - The recording output URL (URL in **avConfig** in the sample code) must be in the format of fd://xx (where xx indicates a file descriptor). You must call [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement access to the application file. For details, see [Application File Access and Management](../file-management/app-file-access.md).
66
67
68   ```ts
69   let avProfile: media.AVRecorderProfile = {
70     audioBitrate: 100000, // Audio bit rate.
71     audioChannels: 2, // Number of audio channels.
72     audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format. Currently, only AAC is supported.
73     audioSampleRate: 48000, // Audio sampling rate.
74     fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // Encapsulation format. Currently, only M4A is supported.
75   }
76   let avConfig: media.AVRecorderConfig = {
77     audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // Audio input source. In this example, the microphone is used.
78     profile: avProfile,
79     url: 'fd://35', // Obtain the file descriptor of the created audio file by referring to the sample code in Application File Access and Management.
80   }
81   avRecorder.prepare(avConfig).then(() => {
82     console.log('Invoke prepare succeeded.');
83   }, (err: BusinessError) => {
84     console.error(`Invoke prepare failed, code is ${err.code}, message is ${err.message}`);
85   })
86   ```
87
884. Call **start()** to start recording. The AVRecorder enters the **started** state.
89
905. Call **pause()** to pause recording. The AVRecorder enters the **paused** state.
91
926. Call **resume()** to resume recording. The AVRecorder enters the **started** state again.
93
947. Call **stop()** to stop recording. The AVRecorder enters the **stopped** state.
95
968. Call **reset()** to reset the resources. The AVRecorder enters the **idle** state. In this case, you can reconfigure the recording parameters.
97
989. Call **release()** to switch the AVRecorder to the **released** state. Now your application exits the recording.
99
100
101## Sample Code
102
103Refer to the sample code below to complete the process of starting, pausing, resuming, and stopping recording.
104
105```ts
106import media from '@ohos.multimedia.media';
107import { BusinessError } from '@ohos.base';
108
109export class AudioRecorderDemo {
110  private avRecorder: media.AVRecorder | undefined = undefined;
111  private avProfile: media.AVRecorderProfile = {
112    audioBitrate: 100000, // Audio bit rate.
113    audioChannels: 2, // Number of audio channels.
114    audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format. Currently, only AAC is supported.
115    audioSampleRate: 48000, // Audio sampling rate.
116    fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // Encapsulation format. Currently, only M4A is supported.
117  };
118  private avConfig: media.AVRecorderConfig = {
119    audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // Audio input source. In this example, the microphone is used.
120    profile: this.avProfile,
121    url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management.
122  };
123
124  // Set AVRecorder callback functions.
125  setAudioRecorderCallback() {
126    if (this.avRecorder != undefined) {
127      // Callback function for state changes.
128      this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => {
129        console.log(`AudioRecorder current state is ${state}`);
130      })
131      // Callback function for errors.
132      this.avRecorder.on('error', (err: BusinessError) => {
133        console.error(`AudioRecorder failed, code is ${err.code}, message is ${err.message}`);
134      })
135    }
136  }
137
138  // Process of starting recording.
139  async startRecordingProcess() {
140    if (this.avRecorder != undefined) {
141      // 1. Create an AVRecorder instance.
142      this.avRecorder = await media.createAVRecorder();
143      this.setAudioRecorderCallback();
144      // 2. Obtain the file descriptor of the recording file and assign it to the URL in avConfig. For details, see FilePicker.
145      // 3. Set recording parameters to complete the preparations.
146      await this.avRecorder.prepare(this.avConfig);
147      // 4. Start recording.
148      await this.avRecorder.start();
149    }
150  }
151
152  // Process of pausing recording.
153  async pauseRecordingProcess() {
154    if (this.avRecorder != undefined && this.avRecorder.state === 'started') { // pause() can be called only when the AVRecorder is in the started state .
155      await this.avRecorder.pause();
156    }
157  }
158
159  // Process of resuming recording.
160  async resumeRecordingProcess() {
161    if (this.avRecorder != undefined && this.avRecorder.state === 'paused') { // resume() can be called only when the AVRecorder is in the paused state .
162      await this.avRecorder.resume();
163    }
164  }
165
166  // Process of stopping recording.
167  async stopRecordingProcess() {
168    if (this.avRecorder != undefined) {
169      // 1. Stop recording.
170      if (this.avRecorder.state === 'started'
171        || this.avRecorder.state ==='paused') { // stop() can be called only when the AVRecorder is in the started or paused state.
172        await this.avRecorder.stop();
173      }
174      // 2. Reset the AVRecorder.
175      await this.avRecorder.reset();
176      // 3. Release the AVRecorder instance.
177      await this.avRecorder.release();
178      // 4. Close the file descriptor of the recording file.
179    }
180  }
181
182  // Complete sample code for starting, pausing, resuming, and stopping recording.
183  async audioRecorderDemo() {
184    await this.startRecordingProcess(); // Start recording.
185    // You can set the recording duration. For example, you can set the sleep mode to prevent code execution.
186    await this.pauseRecordingProcess(); // Pause recording.
187    await this.resumeRecordingProcess(); // Resume recording.
188    await this.stopRecordingProcess(); // Stop recording.
189  }
190}
191```
192