W3Cschool
恭喜您成為首批注冊用戶
獲得88經驗值獎勵
AudioCapturer是音頻采集器,用于錄制PCM(Pulse Code Modulation)音頻數(shù)據(jù),適合有音頻開發(fā)經驗的開發(fā)者實現(xiàn)更靈活的錄制功能。
使用AudioCapturer錄制音頻涉及到AudioCapturer實例的創(chuàng)建、音頻采集參數(shù)的配置、采集的開始與停止、資源的釋放等。本開發(fā)指導將以一次錄制音頻數(shù)據(jù)的過程為例,向開發(fā)者講解如何使用AudioCapturer進行音頻錄制,建議搭配AudioCapturer的API說明閱讀。
下圖展示了AudioCapturer的狀態(tài)變化,在創(chuàng)建實例后,調用對應的方法可以進入指定的狀態(tài)實現(xiàn)對應的行為。需要注意的是在確定的狀態(tài)執(zhí)行不合適的方法可能導致AudioCapturer發(fā)生錯誤,建議開發(fā)者在調用狀態(tài)轉換的方法前進行狀態(tài)檢查,避免程序運行產生預期以外的結果。
使用on('stateChange')方法可以監(jiān)聽AudioCapturer的狀態(tài)變化,每個狀態(tài)對應值與說明見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 // 音頻采集器標志
- }
- private audioCapturerOptions = {
- streamInfo: this.audioStreamInfo,
- capturerInfo: this.audioCapturerInfo
- }
- // 初始化,創(chuàng)建實例,設置監(jiān)聽事件
- init() {
- audio.createAudioCapturer(this.audioCapturerOptions, (err, capturer) => { // 創(chuàng)建AudioCapturer實例
- 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事件,當采集的幀數(shù)達到1000時觸發(fā)回調
- if (position === 1000) {
- console.info('ON Triggered successfully');
- }
- });
- this.audioCapturer.on('periodReach', 2000, (position) => { // 訂閱periodReach事件,當采集的幀數(shù)達到2000時觸發(fā)回調
- 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) { // 當且僅當狀態(tài)為STATE_PREPARED、STATE_PAUSED和STATE_STOPPED之一時才能啟動采集
- console.error(`${TAG}: start failed`);
- return;
- }
- await this.audioCapturer.start(); // 啟動采集
- let context = getContext(this);
- const path = context.filesDir + '/test.wav'; // 采集到的音頻文件存儲路徑
- 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的時候才可以停止
- 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');
- }
- }
- // 銷毀實例,釋放資源
- 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號-3|閩公網安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: