audio-recorder.md 9.6 KB
Newer Older
W
wusongqing 已提交
1
# Audio Recording Development
Z
zengyawen 已提交
2

W
wusongqing 已提交
3
## When to Use
Z
zengyawen 已提交
4

W
wusongqing 已提交
5
During audio recording, audio signals are captured, encoded, and saved to files. You can specify parameters such as the sampling rate, number of audio channels, encoding format, encapsulation format, and file path for audio recording.
Z
zengyawen 已提交
6

W
wusongqing 已提交
7
**Figure 1** Audio recording state transition
Z
zengyawen 已提交
8

W
wusongqing 已提交
9
![en-us_image_audio_recorder_state_machine](figures/en-us_image_audio_recorder_state_machine.png)
Z
zengyawen 已提交
10 11 12



W
wusongqing 已提交
13
**Figure 2** Layer 0 diagram of audio recording
Z
zengyawen 已提交
14

W
wusongqing 已提交
15
![en-us_image_audio_recorder_zero](figures/en-us_image_audio_recorder_zero.png)
Z
zengyawen 已提交
16

W
wusongqing 已提交
17
## How to Develop
Z
zengyawen 已提交
18

W
wusongqing 已提交
19
For details about the APIs, see [AudioRecorder in the Media API](../reference/apis/js-apis-media.md).
Z
zengyawen 已提交
20

W
wusongqing 已提交
21
### Full-Process Scenario
Z
zengyawen 已提交
22

W
wusongqing 已提交
23
The full audio recording process includes creating an instance, setting recording parameters, starting, pausing, resuming, and stopping recording, and releasing resources.
Z
zengyawen 已提交
24

W
wusongqing 已提交
25
```js
W
wusongqing 已提交
26 27
import media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary'
W
wusongqing 已提交
28 29 30 31 32 33 34 35
export class AudioRecorderDemo {
  private testFdNumber; // Used to save the FD address.

  // Set the callbacks related to audio recording.
  setCallBack(audioRecorder) {
    audioRecorder.on('prepare', () => {              					       	// Set the 'prepare' event callback.
      console.log('prepare success');
      audioRecorder.start();                                         			// Call the start API to start recording and trigger the 'start' event callback.
Z
zengyawen 已提交
36
    });
W
wusongqing 已提交
37 38 39
    audioRecorder.on('start', () => {    		     						   	// Set the 'start' event callback.
      console.log('audio recorder start success');
      audioRecorder.pause();                                         			// Call the pause API to pause recording and trigger the 'pause' event callback.
Z
zengyawen 已提交
40
    });
W
wusongqing 已提交
41 42 43
    audioRecorder.on('pause', () => {    		     							// Set the 'pause' event callback.
      console.log('audio recorder pause success');
      audioRecorder.resume();                                        			// Call the resume API to resume recording and trigger the 'resume' event callback.
Z
zengyawen 已提交
44
    });
W
wusongqing 已提交
45 46 47
    audioRecorder.on('resume', () => {    		     							// Set the 'resume' event callback.
      console.log('audio recorder resume success');
      audioRecorder.stop();                                          			// Call the stop API to stop recording and trigger the 'stop' event callback.
Z
zengyawen 已提交
48
    });
W
wusongqing 已提交
49 50 51
    audioRecorder.on('stop', () => {    		     							// Set the 'stop' event callback.
      console.log('audio recorder stop success');
      audioRecorder.reset();                                         			// Call the reset API to reset the recorder and trigger the 'reset' event callback.
Z
zengyawen 已提交
52
    });
W
wusongqing 已提交
53 54 55
    audioRecorder.on('reset', () => {    		     							// Set the 'reset' event callback.
      console.log('audio recorder reset success');
      audioRecorder.release();                                       			// Call the release API to release resources and trigger the 'release' event callback.
Z
zengyawen 已提交
56
    });
W
wusongqing 已提交
57 58 59
    audioRecorder.on('release', () => {    		     							// Set the 'release' event callback.
      console.log('audio recorder release success');
      audioRecorder = undefined;
Z
zengyawen 已提交
60
    });
W
wusongqing 已提交
61 62 63 64
    audioRecorder.on('error', (error) => {             							// Set the 'error' event callback.
      console.info(`audio error called, errName is ${error.name}`);
      console.info(`audio error called, errCode is ${error.code}`);
      console.info(`audio error called, errMessage is ${error.message}`);
W
wusongqing 已提交
65
    });
W
wusongqing 已提交
66
  }
W
wusongqing 已提交
67

W
wusongqing 已提交
68 69 70
  // pathName indicates the passed recording file name, for example, 01.mp3. The generated file address is /storage/media/100/local/files/Video/01.mp3.
  // To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA.
  async getFd(pathName) {
W
wusongqing 已提交
71 72 73 74 75 76 77
    let displayName = pathName;
    const mediaTest = mediaLibrary.getMediaLibrary();
    let fileKeyObj = mediaLibrary.FileKey;
    let mediaType = mediaLibrary.MediaType.VIDEO;
    let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO);
    let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath);
    if (dataUri != undefined) {
W
wusongqing 已提交
78 79 80 81 82 83 84 85 86
      let args = dataUri.id.toString();
      let fetchOp = {
        selections : fileKeyObj.ID + "=?",
        selectionArgs : [args],
      }
      let fetchFileResult = await mediaTest.getFileAssets(fetchOp);
      let fileAsset = await fetchFileResult.getAllObject();
      let fdNumber = await fileAsset[0].open('Rw');
      this.testFdNumber = "fd://" + fdNumber.toString();
W
wusongqing 已提交
87
    }
W
wusongqing 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
  }

  async audioRecorderDemo() {
    // 1. Create an AudioRecorder instance.
    let audioRecorder = media.createAudioRecorder();
    // 2. Set the callbacks.
    this.setCallBack(audioRecorder);
    await this.getFd('01.mp3'); 							// Call the getFd method to obtain the FD address of the file to be recorded.
    // 3. Set the recording parameters.
    let audioRecorderConfig = {
      audioEncodeBitRate : 22050,
      audioSampleRate : 22050,
      numberOfChannels : 2,
      uri : this.testFdNumber,                             	// testFdNumber is generated by getFd.
      location : { latitude : 30, longitude : 130},
      audioEncoderMime : media.CodecMimeType.AUDIO_AAC,
      fileFormat : media.ContainerFormatType.CFT_MPEG_4A,
    }
    audioRecorder.prepare(audioRecorderConfig); 			// Call the prepare method to trigger the 'prepare' event callback.
  }
W
wusongqing 已提交
108
}
W
wusongqing 已提交
109 110 111 112 113 114 115
```

### Normal Recording Scenario

Unlike the full-process scenario, the normal recording scenario does not include the process of pausing and resuming recording.

```js
W
wusongqing 已提交
116 117
import media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary'
W
wusongqing 已提交
118 119 120 121 122 123 124 125
export class AudioRecorderDemo {
  private testFdNumber; // Used to save the FD address.

  // Set the callbacks related to audio recording.
  setCallBack(audioRecorder) {
    audioRecorder.on('prepare', () => {              					       // Set the 'prepare' event callback.
      console.log('prepare success');
      audioRecorder.start();                                         			// Call the start API to start recording and trigger the 'start' event callback.
W
wusongqing 已提交
126
    });
W
wusongqing 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    audioRecorder.on('start', () => {    		     							// Set the 'start' event callback.
      console.log('audio recorder start success');
      audioRecorder.stop();                                          			// Call the stop API to stop recording and trigger the 'stop' event callback.
    });
    audioRecorder.on('stop', () => {    		     							// Set the 'stop' event callback.
      console.log('audio recorder stop success');
      audioRecorder.release();                                       			// Call the release API to release resources and trigger the 'release' event callback.
    });
    audioRecorder.on('release', () => {    		     							// Set the 'release' event callback.
      console.log('audio recorder release success');
      audioRecorder = undefined;
    });
    audioRecorder.on('error', (error) => {             							// Set the 'error' event callback.
      console.info(`audio error called, errName is ${error.name}`);
      console.info(`audio error called, errCode is ${error.code}`);
      console.info(`audio error called, errMessage is ${error.message}`);
    });
  }
W
wusongqing 已提交
145

W
wusongqing 已提交
146 147 148
  // pathName indicates the passed recording file name, for example, 01.mp3. The generated file address is /storage/media/100/local/files/Video/01.mp3.
  // To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA.
  async getFd(pathName) {
W
wusongqing 已提交
149 150 151 152 153 154 155
    let displayName = pathName;
    const mediaTest = mediaLibrary.getMediaLibrary();
    let fileKeyObj = mediaLibrary.FileKey;
    let mediaType = mediaLibrary.MediaType.VIDEO;
    let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO);
    let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath);
    if (dataUri != undefined) {
W
wusongqing 已提交
156 157 158 159 160 161 162 163 164
      let args = dataUri.id.toString();
      let fetchOp = {
        selections : fileKeyObj.ID + "=?",
        selectionArgs : [args],
      }
      let fetchFileResult = await mediaTest.getFileAssets(fetchOp);
      let fileAsset = await fetchFileResult.getAllObject();
      let fdNumber = await fileAsset[0].open('Rw');
      this.testFdNumber = "fd://" + fdNumber.toString();
W
wusongqing 已提交
165
    }
W
wusongqing 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
  }

  async audioRecorderDemo() {
    // 1. Create an AudioRecorder instance.
    let audioRecorder = media.createAudioRecorder();
    // 2. Set the callbacks.
    this.setCallBack(audioRecorder);
    await this.getFd('01.mp3'); 							// Call the getFd method to obtain the FD address of the file to be recorded.
    // 3. Set the recording parameters.
    let audioRecorderConfig = {
      audioEncodeBitRate : 22050,
      audioSampleRate : 22050,
      numberOfChannels : 2,
      uri : this.testFdNumber,                             	// testFdNumber is generated by getFd.
      location : { latitude : 30, longitude : 130},
      audioEncoderMime : media.CodecMimeType.AUDIO_AAC,
      fileFormat : media.ContainerFormatType.CFT_MPEG_4A,
    }
    audioRecorder.prepare(audioRecorderConfig); 			// Call the prepare method to trigger the 'prepare' event callback.
  }
W
wusongqing 已提交
186
}
W
wusongqing 已提交
187
```
W
wusongqing 已提交
188 189 190 191 192 193 194 195

## Samples

The following samples are provided to help you better understand how to develop audio recording:

- [`Recorder`: Recorder (eTS, API 8)](https://gitee.com/openharmony/app_samples/tree/master/media/Recorder)
- [`eTsAudioPlayer`: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets)
- [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)