audio-recorder.md 9.1 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
export class AudioRecorderDemo {
  private testFdNumber; // Used to save the FD address.

  // Set the callbacks related to audio recording.
  setCallBack(audioRecorder) {
W
wusongqing 已提交
33
    audioRecorder.on('prepare', () => {              					       	// Set the prepare event callback.
W
wusongqing 已提交
34
      console.log('prepare success');
W
wusongqing 已提交
35
      audioRecorder.start();                                         			// Call the start API to start recording and trigger the start event callback.
Z
zengyawen 已提交
36
    });
W
wusongqing 已提交
37
    audioRecorder.on('start', () => {    		     						   	// Set the start event callback.
W
wusongqing 已提交
38
      console.log('audio recorder start success');
W
wusongqing 已提交
39
      audioRecorder.pause();                                         			// Call the pause API to pause recording and trigger the pause event callback.
Z
zengyawen 已提交
40
    });
W
wusongqing 已提交
41
    audioRecorder.on('pause', () => {    		     							// Set the pause event callback.
W
wusongqing 已提交
42
      console.log('audio recorder pause success');
W
wusongqing 已提交
43
      audioRecorder.resume();                                        			// Call the resume API to resume recording and trigger the resume event callback.
Z
zengyawen 已提交
44
    });
W
wusongqing 已提交
45
    audioRecorder.on('resume', () => {    		     							// Set the resume event callback.
W
wusongqing 已提交
46
      console.log('audio recorder resume success');
W
wusongqing 已提交
47
      audioRecorder.stop();                                          			// Call the stop API to stop recording and trigger the stop event callback.
Z
zengyawen 已提交
48
    });
W
wusongqing 已提交
49
    audioRecorder.on('stop', () => {    		     							// Set the stop event callback.
W
wusongqing 已提交
50
      console.log('audio recorder stop success');
W
wusongqing 已提交
51
      audioRecorder.reset();                                         			// Call the reset API to reset the recorder and trigger the reset event callback.
Z
zengyawen 已提交
52
    });
W
wusongqing 已提交
53
    audioRecorder.on('reset', () => {    		     							// Set the reset event callback.
W
wusongqing 已提交
54
      console.log('audio recorder reset success');
W
wusongqing 已提交
55
      audioRecorder.release();                                       			// Call the release API to release resources and trigger the release event callback.
Z
zengyawen 已提交
56
    });
W
wusongqing 已提交
57
    audioRecorder.on('release', () => {    		     							// Set the release event callback.
W
wusongqing 已提交
58 59
      console.log('audio recorder release success');
      audioRecorder = undefined;
Z
zengyawen 已提交
60
    });
W
wusongqing 已提交
61
    audioRecorder.on('error', (error) => {             							// Set the error event callback.
W
wusongqing 已提交
62 63 64
      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
  }

  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,
    }
W
wusongqing 已提交
106
    audioRecorder.prepare(audioRecorderConfig); 			// Call the prepare method to trigger the prepare event callback.
W
wusongqing 已提交
107
  }
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
export class AudioRecorderDemo {
  private testFdNumber; // Used to save the FD address.

  // Set the callbacks related to audio recording.
  setCallBack(audioRecorder) {
W
wusongqing 已提交
123
    audioRecorder.on('prepare', () => {              					       // Set the prepare event callback.
W
wusongqing 已提交
124
      console.log('prepare success');
W
wusongqing 已提交
125
      audioRecorder.start();                                         			// Call the start API to start recording and trigger the start event callback.
W
wusongqing 已提交
126
    });
W
wusongqing 已提交
127
    audioRecorder.on('start', () => {    		     							// Set the start event callback.
W
wusongqing 已提交
128
      console.log('audio recorder start success');
W
wusongqing 已提交
129
      audioRecorder.stop();                                          			// Call the stop API to stop recording and trigger the stop event callback.
W
wusongqing 已提交
130
    });
W
wusongqing 已提交
131
    audioRecorder.on('stop', () => {    		     							// Set the stop event callback.
W
wusongqing 已提交
132
      console.log('audio recorder stop success');
W
wusongqing 已提交
133
      audioRecorder.release();                                       			// Call the release API to release resources and trigger the release event callback.
W
wusongqing 已提交
134
    });
W
wusongqing 已提交
135
    audioRecorder.on('release', () => {    		     							// Set the release event callback.
W
wusongqing 已提交
136 137 138
      console.log('audio recorder release success');
      audioRecorder = undefined;
    });
W
wusongqing 已提交
139
    audioRecorder.on('error', (error) => {             							// Set the error event callback.
W
wusongqing 已提交
140 141 142 143 144
      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
  }

  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,
    }
W
wusongqing 已提交
184
    audioRecorder.prepare(audioRecorderConfig); 			// Call the prepare method to trigger the prepare event callback.
W
wusongqing 已提交
185
  }
W
wusongqing 已提交
186
}
W
wusongqing 已提交
187
```
W
wusongqing 已提交
188