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 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 ```ts 21 import media from '@ohos.multimedia.media'; 22 23 let avRecorder = undefined; 24 media.createAVRecorder().then((recorder) => { 25 avRecorder = recorder; 26 }, (err) => { 27 console.error(`Invoke createAVRecorder failed, code is ${err.code}, message is ${err.message}`); 28 }) 29 ``` 30 312. Set the events to listen for. 32 | Event Type| Description| 33 | -------- | -------- | 34 | stateChange | Mandatory; used to listen for changes of the **state** attribute of the AVRecorder.| 35 | error | Mandatory; used to listen for AVRecorder errors.| 36 37 38 ```ts 39 // Callback function for state changes. 40 avRecorder.on('stateChange', (state, reason) => { 41 console.log(`current state is ${state}`); 42 // You can add the action to be performed after the state is switched. 43 }) 44 45 // Callback function for errors. 46 avRecorder.on('error', (err) => { 47 console.error(`avRecorder failed, code is ${err.code}, message is ${err.message}`); 48 }) 49 ``` 50 513. Set audio recording parameters and call **prepare()**. The AVRecorder enters the **prepared** state. 52 > **NOTE** 53 > 54 > Pay attention to the following when configuring parameters: 55 > 56 > - In pure audio recording scenarios, set only audio-related parameters in **avConfig** of **prepare()**. 57 > 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). 58 > 59 > - The [recording formats](avplayer-avrecorder-overview.md#supported-formats) in use must be those supported by the system. 60 > 61 > - 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). 62 63 64 ```ts 65 let avProfile = { 66 audioBitrate: 100000, // Audio bit rate. 67 audioChannels: 2, // Number of audio channels. 68 audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format. Currently, only AAC is supported. 69 audioSampleRate: 48000, // Audio sampling rate. 70 fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // Encapsulation format. Currently, only M4A is supported. 71 } 72 let avConfig = { 73 audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // Audio input source. In this example, the microphone is used. 74 profile: avProfile, 75 url: 'fd://35', // Obtain the file descriptor of the created audio file by referring to the sample code in Application File Access and Management. 76 } 77 avRecorder.prepare(avConfig).then(() => { 78 console.log('Invoke prepare succeeded.'); 79 }, (err) => { 80 console.error(`Invoke prepare failed, code is ${err.code}, message is ${err.message}`); 81 }) 82 ``` 83 844. Call **start()** to start recording. The AVRecorder enters the **started** state. 85 865. Call **pause()** to pause recording. The AVRecorder enters the **paused** state. 87 886. Call **resume()** to resume recording. The AVRecorder enters the **started** state again. 89 907. Call **stop()** to stop recording. The AVRecorder enters the **stopped** state. 91 928. Call **reset()** to reset the resources. The AVRecorder enters the **idle** state. In this case, you can reconfigure the recording parameters. 93 949. Call **release()** to switch the AVRecorder to the **released** state. Now your application exits the recording. 95 96 97## Sample Code 98 99 Refer to the sample code below to complete the process of starting, pausing, resuming, and stopping recording. 100 101```ts 102import media from '@ohos.multimedia.media'; 103 104export class AudioRecorderDemo { 105 private avRecorder; 106 private avProfile = { 107 audioBitrate: 100000, // Audio bit rate. 108 audioChannels: 2, // Number of audio channels. 109 audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format. Currently, only AAC is supported. 110 audioSampleRate: 48000, // Audio sampling rate. 111 fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // Encapsulation format. Currently, only M4A is supported. 112 }; 113 private avConfig = { 114 audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // Audio input source. In this example, the microphone is used. 115 profile: this.avProfile, 116 url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management. 117 }; 118 119 // Set AVRecorder callback functions. 120 setAudioRecorderCallback() { 121 // Callback function for state changes. 122 this.avRecorder.on('stateChange', (state, reason) => { 123 console.log(`AudioRecorder current state is ${state}`); 124 }) 125 // Callback function for errors. 126 this.avRecorder.on('error', (err) => { 127 console.error(`AudioRecorder failed, code is ${err.code}, message is ${err.message}`); 128 }) 129 } 130 131 // Process of starting recording. 132 async startRecordingProcess() { 133 // 1. Create an AVRecorder instance. 134 this.avRecorder = await media.createAVRecorder(); 135 this.setAudioRecorderCallback(); 136 // 2. Obtain the file descriptor of the recording file and assign it to the URL in avConfig. For details, see FilePicker. 137 // 3. Set recording parameters to complete the preparations. 138 await this.avRecorder.prepare(this.avConfig); 139 // 4. Start recording. 140 await this.avRecorder.start(); 141 } 142 143 // Process of pausing recording. 144 async pauseRecordingProcess() { 145 if (this.avRecorder.state ==='started') { // pause() can be called only when the AVRecorder is in the started state . 146 await this.avRecorder.pause(); 147 } 148 } 149 150 // Process of resuming recording. 151 async resumeRecordingProcess() { 152 if (this.avRecorder.state === 'paused') { // resume() can be called only when the AVRecorder is in the paused state . 153 await this.avRecorder.resume(); 154 } 155 } 156 157 // Process of stopping recording. 158 async stopRecordingProcess() { 159 // 1. Stop recording. 160 if (this.avRecorder.state === 'started' 161 || this.avRecorder.state ==='paused') { // stop() can be called only when the AVRecorder is in the started or paused state. 162 await this.avRecorder.stop(); 163 } 164 // 2. Reset the AVRecorder. 165 await this.avRecorder.reset(); 166 // 3. Release the AVRecorder instance. 167 await this.avRecorder.release(); 168 // 4. Close the file descriptor of the recording file. 169 } 170 171 // Complete sample code for starting, pausing, resuming, and stopping recording. 172 async audioRecorderDemo() { 173 await this.startRecordingProcess(); // Start recording. 174 // You can set the recording duration. For example, you can set the sleep mode to prevent code execution. 175 await this.pauseRecordingProcess(); // Pause recording. 176 await this.resumeRecordingProcess(); // Resume recording. 177 await this.stopRecordingProcess(); // Stop recording. 178 } 179} 180``` 181