W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
AudioCapturer是音頻采集器,用于錄制PCM(Pulse Code Modulation)音頻數(shù)據(jù),適合有音頻開發(fā)經(jīng)驗(yàn)的開發(fā)者實(shí)現(xiàn)更靈活的錄制功能。
使用AudioCapturer錄制音頻涉及到AudioCapturer實(shí)例的創(chuàng)建、音頻采集參數(shù)的配置、采集的開始與停止、資源的釋放等。本開發(fā)指導(dǎo)將以一次錄制音頻數(shù)據(jù)的過程為例,向開發(fā)者講解如何使用AudioCapturer進(jìn)行音頻錄制,建議搭配AudioCapturer的API說明閱讀。
下圖展示了AudioCapturer的狀態(tài)變化,在創(chuàng)建實(shí)例后,調(diào)用對(duì)應(yīng)的方法可以進(jìn)入指定的狀態(tài)實(shí)現(xiàn)對(duì)應(yīng)的行為。需要注意的是在確定的狀態(tài)執(zhí)行不合適的方法可能導(dǎo)致AudioCapturer發(fā)生錯(cuò)誤,建議開發(fā)者在調(diào)用狀態(tài)轉(zhuǎn)換的方法前進(jìn)行狀態(tài)檢查,避免程序運(yùn)行產(chǎn)生預(yù)期以外的結(jié)果。
使用on('stateChange')方法可以監(jiān)聽AudioCapturer的狀態(tài)變化,每個(gè)狀態(tài)對(duì)應(yīng)值與說明見AudioState。
- import audio from '@ohos.multimedia.audio';
- let audioStreamInfo = {
- samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
- channels: audio.AudioChannel.CHANNEL_2,
- sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
- encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
- };
- let audioCapturerInfo = {
- source: audio.SourceType.SOURCE_TYPE_MIC,
- capturerFlags: 0
- };
- let audioCapturerOptions = {
- streamInfo: audioStreamInfo,
- capturerInfo: audioCapturerInfo
- };
- audio.createAudioCapturer(audioCapturerOptions, (err, data) => {
- if (err) {
- console.error(`Invoke createAudioCapturer failed, code is ${err.code}, message is ${err.message}`);
- } else {
- console.info('Invoke createAudioCapturer succeeded.');
- let audioCapturer = data;
- }
- });
- audioCapturer.start((err) => {
- if (err) {
- console.error(`Capturer start failed, code is ${err.code}, message is ${err.message}`);
- } else {
- console.info('Capturer start success.');
- }
- });
- let file = fs.openSync(path, 0o2 | 0o100);
- let bufferSize = await audioCapturer.getBufferSize();
- let buffer = await audioCapturer.read(bufferSize, true);
- fs.writeSync(file.fd, buffer);
- audioCapturer.stop((err) => {
- if (err) {
- console.error(`Capturer stop failed, code is ${err.code}, message is ${err.message}`);
- } else {
- console.info('Capturer stopped.');
- }
- });
- audioCapturer.release((err) => {
- if (err) {
- console.error(`capturer release failed, code is ${err.code}, message is ${err.message}`);
- } else {
- console.info('capturer released.');
- }
- });
- import audio from '@ohos.multimedia.audio';
- import fs from '@ohos.file.fs';
- const TAG = 'AudioCapturerDemo';
- export default class AudioCapturerDemo {
- private audioCapturer = undefined;
- private audioStreamInfo = {
- samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
- channels: audio.AudioChannel.CHANNEL_1,
- sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
- encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
- }
- private audioCapturerInfo = {
- source: audio.SourceType.SOURCE_TYPE_MIC, // 音源類型
- capturerFlags: 0 // 音頻采集器標(biāo)志
- }
- private audioCapturerOptions = {
- streamInfo: this.audioStreamInfo,
- capturerInfo: this.audioCapturerInfo
- }
- // 初始化,創(chuàng)建實(shí)例,設(shè)置監(jiān)聽事件
- init() {
- audio.createAudioCapturer(this.audioCapturerOptions, (err, capturer) => { // 創(chuàng)建AudioCapturer實(shí)例
- if (err) {
- console.error(`Invoke createAudioCapturer failed, code is ${err.code}, message is ${err.message}`);
- return;
- }
- console.info(`${TAG}: create AudioCapturer success`);
- this.audioCapturer = capturer;
- this.audioCapturer.on('markReach', 1000, (position) => { // 訂閱markReach事件,當(dāng)采集的幀數(shù)達(dá)到1000時(shí)觸發(fā)回調(diào)
- if (position === 1000) {
- console.info('ON Triggered successfully');
- }
- });
- this.audioCapturer.on('periodReach', 2000, (position) => { // 訂閱periodReach事件,當(dāng)采集的幀數(shù)達(dá)到2000時(shí)觸發(fā)回調(diào)
- if (position === 2000) {
- console.info('ON Triggered successfully');
- }
- });
- });
- }
- // 開始一次音頻采集
- async start() {
- let stateGroup = [audio.AudioState.STATE_PREPARED, audio.AudioState.STATE_PAUSED, audio.AudioState.STATE_STOPPED];
- if (stateGroup.indexOf(this.audioCapturer.state) === -1) { // 當(dāng)且僅當(dāng)狀態(tài)為STATE_PREPARED、STATE_PAUSED和STATE_STOPPED之一時(shí)才能啟動(dòng)采集
- console.error(`${TAG}: start failed`);
- return;
- }
- await this.audioCapturer.start(); // 啟動(dòng)采集
- let context = getContext(this);
- const path = context.filesDir + '/test.wav'; // 采集到的音頻文件存儲(chǔ)路徑
- let file = fs.openSync(path, 0o2 | 0o100); // 如果文件不存在則創(chuàng)建文件
- let fd = file.fd;
- let numBuffersToCapture = 150; // 循環(huán)寫入150次
- let count = 0;
- while (numBuffersToCapture) {
- let bufferSize = await this.audioCapturer.getBufferSize();
- let buffer = await this.audioCapturer.read(bufferSize, true);
- let options = {
- offset: count * bufferSize,
- length: bufferSize
- };
- if (buffer === undefined) {
- console.error(`${TAG}: read buffer failed`);
- } else {
- let number = fs.writeSync(fd, buffer, options);
- console.info(`${TAG}: write date: ${number}`);
- }
- numBuffersToCapture--;
- count++;
- }
- }
- // 停止采集
- async stop() {
- // 只有采集器狀態(tài)為STATE_RUNNING或STATE_PAUSED的時(shí)候才可以停止
- if (this.audioCapturer.state !== audio.AudioState.STATE_RUNNING && this.audioCapturer.state !== audio.AudioState.STATE_PAUSED) {
- console.info('Capturer is not running or paused');
- return;
- }
- await this.audioCapturer.stop(); // 停止采集
- if (this.audioCapturer.state === audio.AudioState.STATE_STOPPED) {
- console.info('Capturer stopped');
- } else {
- console.error('Capturer stop failed');
- }
- }
- // 銷毀實(shí)例,釋放資源
- async release() {
- // 采集器狀態(tài)不是STATE_RELEASED或STATE_NEW狀態(tài),才能release
- if (this.audioCapturer.state === audio.AudioState.STATE_RELEASED || this.audioCapturer.state === audio.AudioState.STATE_NEW) {
- console.info('Capturer already released');
- return;
- }
- await this.audioCapturer.release(); // 釋放資源
- if (this.audioCapturer.state == audio.AudioState.STATE_RELEASED) {
- console.info('Capturer released');
- } else {
- console.error('Capturer release failed');
- }
- }
- }
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: