audio-recorder.md 8.9 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 used for audio recording, see [js-apis-media.md](../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 28 29 30
import media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary'

let testFdNumber;

W
wusongqing 已提交
31 32 33 34
function SetCallBack(audioRecorder) {
    audioRecorder.on('prepare', () => {              								// Set the 'prepare' event callback.
        console.log('prepare success');    
        // The recording page is ready. You can click the Record button to start recording.
Z
zengyawen 已提交
35
    });
W
wusongqing 已提交
36 37 38
    audioRecorder.on('start', () => {    		     								// Set the 'start' event callback.
    	console.log('audio recorder start success');
        // The Record button is changed to the pausable state.
Z
zengyawen 已提交
39
    });
W
wusongqing 已提交
40 41 42
    audioRecorder.on('pause', () => {    		     								// Set the 'pause' event callback.
        console.log('audio recorder pause success');
        // The Record button is changed to the recordable state.
Z
zengyawen 已提交
43
    });
W
wusongqing 已提交
44 45 46
    audioRecorder.on('resume', () => {    		     								// Set the 'resume' event callback.
        console.log('audio recorder resume success');
        // The Record button is changed to the pausable state.
Z
zengyawen 已提交
47
    });
W
wusongqing 已提交
48 49
    audioRecorder.on('stop', () => {    		     								// Set the 'stop' event callback.
        console.log('audio recorder stop success');
Z
zengyawen 已提交
50
    });
W
wusongqing 已提交
51 52
    audioRecorder.on('release', () => {    		     								// Set the 'release' event callback.
        console.log('audio recorder release success');
Z
zengyawen 已提交
53
    });
W
wusongqing 已提交
54 55 56
    audioRecorder.on('reset', () => {    		     								// Set the 'reset' event callback.
        console.log('audio recorder reset success');
        // You need to reset the recording parameters for another recording.
Z
zengyawen 已提交
57
    });
W
wusongqing 已提交
58 59 60 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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
// pathName indicates the passed recording file name, for example, 01.mp3. The generated file address is /storage/media/100/local/files/Movies/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 function getFd(pathName) {
    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) {
        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');
        fdNumber = "fd://" + fdNumber.toString();
        testFdNumber = fdNumber;
    }
}

await getFd('01.mp3');

W
wusongqing 已提交
90 91 92 93 94 95 96 97 98 99 100
// 1. Create an AudioRecorder instance.
let audioRecorder = media.createAudioRecorder();    
// 2. Set the callbacks.
SetCallBack(audioRecorder);    
// 3. Set the recording parameters.
let audioRecorderConfig = {
    audioEncoder : media.AudioEncoder.AAC_LC ,
    audioEncodeBitRate : 22050,
    audioSampleRate : 22050,
    numberOfChannels : 2,
    format : media.AudioOutputFormat.AAC_ADTS,
W
wusongqing 已提交
101
    uri : testFdNumber,                             // testFdNumber is generated by getFd.
W
wusongqing 已提交
102 103 104 105
    location : { latitude : 30, longitude : 130},
}																					
audioRecorder.prepare(audioRecorderConfig);
// 4. Start recording.
W
wusongqing 已提交
106
audioRecorder.start();                            	// The start API can be called to trigger the 'start' event callback only after the 'prepare' event callback is complete.
W
wusongqing 已提交
107
// 5. Pause recording.
W
wusongqing 已提交
108
audioRecorder.pause();                             	// The pause API can be called to trigger the 'pause' event callback only after the 'start' event callback is complete.
W
wusongqing 已提交
109
// 6. Resume recording.
W
wusongqing 已提交
110
audioRecorder.resume();                             // The resume API can be called to trigger the 'resume' event callback only after the 'pause' event callback is complete.
W
wusongqing 已提交
111
// 7. Stop recording.
W
wusongqing 已提交
112
audioRecorder.stop();                             	// The stop API can be called to trigger the 'stop' event callback only after the 'start' or 'resume' event callback is complete.
W
wusongqing 已提交
113
// 8. Reset recording.
W
wusongqing 已提交
114
audioRecorder.reset();                              // The prepare API can be called for another recording only after the 'reset' event callback is complete.
W
wusongqing 已提交
115 116 117 118 119 120 121 122 123 124
// 9. Release resources.
audioRecorder.release();                           	// The AudioRecorder resource is destroyed.
audioRecorder = undefined;
```

### 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 已提交
125 126 127 128 129
import media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary'

let testFdNumber;

W
wusongqing 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
function SetCallBack(audioPlayer) {
    audioRecorder.on('prepare', () => {              								// Set the 'prepare' event callback.
        console.log('prepare success');    
        // The recording page is ready. You can click the Record button to start recording.
    });
    audioRecorder.on('start', () => {    		     								// Set the 'start' event callback.
    	console.log('audio recorder start success');
        // The Record button is changed to the pausable state.
    });  
    audioRecorder.on('stop', () => {    		     								// Set the 'stop' event callback.
        console.log('audio recorder stop success');
    });    
    audioRecorder.on('release', () => {    		     								// Set the 'release' event callback.
        console.log('audio recorder release success');
    });    
}
W
wusongqing 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171

// pathName indicates the passed recording file name, for example, 01.mp3. The generated file address is /storage/media/100/local/files/Movies/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 function getFd(pathName) {
    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) {
        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');
        fdNumber = "fd://" + fdNumber.toString();
        testFdNumber = fdNumber;
    }
}

await getFd('01.mp3');

W
wusongqing 已提交
172 173 174 175 176 177 178 179 180 181 182
// 1. Create an AudioRecorder instance.
let audioRecorder = media.createAudioRecorder();   
// 2. Set the callbacks.
SetCallBack(audioRecorder);       
// 3. Set the recording parameters.
let audioRecorderConfig = {
    audioEncoder : media.AudioEncoder.AAC_LC ,
    audioEncodeBitRate : 22050,
    audioSampleRate : 22050,
    numberOfChannels : 2,
    format : media.AudioOutputFormat.AAC_ADTS,
W
wusongqing 已提交
183
    uri : testFdNumber,                             // testFdNumber is generated by getFd.
W
wusongqing 已提交
184 185 186 187
    location : { latitude : 30, longitude : 130},
}
audioRecorder.prepare(audioRecorderConfig)
// 4. Start recording.
W
wusongqing 已提交
188
audioRecorder.start();                            	// The start API can be called to trigger the 'start' event callback only after the 'prepare' event callback is complete.
W
wusongqing 已提交
189
// 5. Stop recording.
W
wusongqing 已提交
190
audioRecorder.stop();                             	// The stop API can be called to trigger the 'stop' event callback only after the 'start' or 'resume' event callback is complete.
W
wusongqing 已提交
191 192 193 194
// 6. Release resources.
audioRecorder.release();                           	// The AudioRecorder resource is destroyed.
audioRecorder = undefined;
```