1# 使用AudioCapturer开发音频录制功能 2 3AudioCapturer是音频采集器,用于录制PCM(Pulse Code Modulation)音频数据,适合有音频开发经验的开发者实现更灵活的录制功能。 4 5## 开发指导 6 7使用AudioCapturer录制音频涉及到AudioCapturer实例的创建、音频采集参数的配置、采集的开始与停止、资源的释放等。本开发指导将以一次录制音频数据的过程为例,向开发者讲解如何使用AudioCapturer进行音频录制,建议搭配[AudioCapturer的API说明](../reference/apis/js-apis-audio.md#audiocapturer8)阅读。 8 9下图展示了AudioCapturer的状态变化,在创建实例后,调用对应的方法可以进入指定的状态实现对应的行为。需要注意的是在确定的状态执行不合适的方法可能导致AudioCapturer发生错误,建议开发者在调用状态转换的方法前进行状态检查,避免程序运行产生预期以外的结果。 10 11**图1** AudioCapturer状态变化示意图 12![AudioCapturer status change](figures/audiocapturer-status-change.png) 13 14使用on('stateChange')方法可以监听AudioCapturer的状态变化,每个状态对应值与说明见[AudioState](../reference/apis/js-apis-audio.md#audiostate8)。 15 16### 开发步骤及注意事项 17 181. 配置音频采集参数并创建AudioCapturer实例,音频采集参数的详细信息可以查看[AudioCapturerOptions](../reference/apis/js-apis-audio.md#audiocaptureroptions8)。 19 20 ```ts 21 import audio from '@ohos.multimedia.audio'; 22 23 let audioStreamInfo = { 24 samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, 25 channels: audio.AudioChannel.CHANNEL_2, 26 sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, 27 encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW 28 }; 29 30 let audioCapturerInfo = { 31 source: audio.SourceType.SOURCE_TYPE_MIC, 32 capturerFlags: 0 33 }; 34 35 let audioCapturerOptions = { 36 streamInfo: audioStreamInfo, 37 capturerInfo: audioCapturerInfo 38 }; 39 40 audio.createAudioCapturer(audioCapturerOptions, (err, data) => { 41 if (err) { 42 console.error(`Invoke createAudioCapturer failed, code is ${err.code}, message is ${err.message}`); 43 } else { 44 console.info('Invoke createAudioCapturer succeeded.'); 45 let audioCapturer = data; 46 } 47 }); 48 ``` 49 502. 调用start()方法进入running状态,开始录制音频。 51 52 ```ts 53 audioCapturer.start((err) => { 54 if (err) { 55 console.error(`Capturer start failed, code is ${err.code}, message is ${err.message}`); 56 } else { 57 console.info('Capturer start success.'); 58 } 59 }); 60 ``` 61 623. 指定录制文件地址,调用read()方法读取缓冲区的数据。 63 64 ```ts 65 let file = fs.openSync(path, 0o2 | 0o100); 66 let bufferSize = await audioCapturer.getBufferSize(); 67 let buffer = await audioCapturer.read(bufferSize, true); 68 fs.writeSync(file.fd, buffer); 69 ``` 70 714. 调用stop()方法停止录制。 72 73 ```ts 74 audioCapturer.stop((err) => { 75 if (err) { 76 console.error(`Capturer stop failed, code is ${err.code}, message is ${err.message}`); 77 } else { 78 console.info('Capturer stopped.'); 79 } 80 }); 81 ``` 82 835. 调用release()方法销毁实例,释放资源。 84 85 ```ts 86 audioCapturer.release((err) => { 87 if (err) { 88 console.error(`capturer release failed, code is ${err.code}, message is ${err.message}`); 89 } else { 90 console.info('capturer released.'); 91 } 92 }); 93 ``` 94 95 96### 完整示例 97 98下面展示了使用AudioCapturer录制音频的完整示例代码。 99 100```ts 101import audio from '@ohos.multimedia.audio'; 102import fs from '@ohos.file.fs'; 103 104const TAG = 'AudioCapturerDemo'; 105 106export default class AudioCapturerDemo { 107 private audioCapturer = undefined; 108 private audioStreamInfo = { 109 samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, 110 channels: audio.AudioChannel.CHANNEL_1, 111 sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, 112 encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW 113 } 114 private audioCapturerInfo = { 115 source: audio.SourceType.SOURCE_TYPE_MIC, // 音源类型 116 capturerFlags: 0 // 音频采集器标志 117 } 118 private audioCapturerOptions = { 119 streamInfo: this.audioStreamInfo, 120 capturerInfo: this.audioCapturerInfo 121 } 122 123 // 初始化,创建实例,设置监听事件 124 init() { 125 audio.createAudioCapturer(this.audioCapturerOptions, (err, capturer) => { // 创建AudioCapturer实例 126 if (err) { 127 console.error(`Invoke createAudioCapturer failed, code is ${err.code}, message is ${err.message}`); 128 return; 129 } 130 131 console.info(`${TAG}: create AudioCapturer success`); 132 this.audioCapturer = capturer; 133 this.audioCapturer.on('markReach', 1000, (position) => { // 订阅markReach事件,当采集的帧数达到1000时触发回调 134 if (position === 1000) { 135 console.info('ON Triggered successfully'); 136 } 137 }); 138 this.audioCapturer.on('periodReach', 2000, (position) => { // 订阅periodReach事件,当采集的帧数达到2000时触发回调 139 if (position === 2000) { 140 console.info('ON Triggered successfully'); 141 } 142 }); 143 144 }); 145 } 146 147 // 开始一次音频采集 148 async start() { 149 let stateGroup = [audio.AudioState.STATE_PREPARED, audio.AudioState.STATE_PAUSED, audio.AudioState.STATE_STOPPED]; 150 if (stateGroup.indexOf(this.audioCapturer.state) === -1) { // 当且仅当状态为STATE_PREPARED、STATE_PAUSED和STATE_STOPPED之一时才能启动采集 151 console.error(`${TAG}: start failed`); 152 return; 153 } 154 await this.audioCapturer.start(); // 启动采集 155 156 let context = getContext(this); 157 const path = context.filesDir + '/test.wav'; // 采集到的音频文件存储路径 158 159 let file = fs.openSync(path, 0o2 | 0o100); // 如果文件不存在则创建文件 160 let fd = file.fd; 161 let numBuffersToCapture = 150; // 循环写入150次 162 let count = 0; 163 while (numBuffersToCapture) { 164 let bufferSize = await this.audioCapturer.getBufferSize(); 165 let buffer = await this.audioCapturer.read(bufferSize, true); 166 let options = { 167 offset: count * bufferSize, 168 length: bufferSize 169 }; 170 if (buffer === undefined) { 171 console.error(`${TAG}: read buffer failed`); 172 } else { 173 let number = fs.writeSync(fd, buffer, options); 174 console.info(`${TAG}: write date: ${number}`); 175 } 176 numBuffersToCapture--; 177 count++; 178 } 179 } 180 181 // 停止采集 182 async stop() { 183 // 只有采集器状态为STATE_RUNNING或STATE_PAUSED的时候才可以停止 184 if (this.audioCapturer.state !== audio.AudioState.STATE_RUNNING && this.audioCapturer.state !== audio.AudioState.STATE_PAUSED) { 185 console.info('Capturer is not running or paused'); 186 return; 187 } 188 await this.audioCapturer.stop(); // 停止采集 189 if (this.audioCapturer.state === audio.AudioState.STATE_STOPPED) { 190 console.info('Capturer stopped'); 191 } else { 192 console.error('Capturer stop failed'); 193 } 194 } 195 196 // 销毁实例,释放资源 197 async release() { 198 // 采集器状态不是STATE_RELEASED或STATE_NEW状态,才能release 199 if (this.audioCapturer.state === audio.AudioState.STATE_RELEASED || this.audioCapturer.state === audio.AudioState.STATE_NEW) { 200 console.info('Capturer already released'); 201 return; 202 } 203 await this.audioCapturer.release(); // 释放资源 204 if (this.audioCapturer.state == audio.AudioState.STATE_RELEASED) { 205 console.info('Capturer released'); 206 } else { 207 console.error('Capturer release failed'); 208 } 209 } 210} 211``` 212