#鸿蒙通关秘籍#如何在HarmonyOS中通过AudioCapturer监听并处理音频数据?

HarmonyOS
7天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
RADIUS寒烟翠

在HarmonyOS中使用AudioCapturer监听和处理音频数据需要按以下步骤操作:

  1. 创建AudioCapturer实例并设置参数

    使用合适的音频参数来创建实例:

    import { audio } from '@kit.AudioKit';
    
    let audioStreamInfo = {
      samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000,
      channels: audio.AudioChannel.CHANNEL_2,
      sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
      encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
    };
    
    let audioCapturerOptions = {
      streamInfo: audioStreamInfo,
      capturerInfo: {
        source: audio.SourceType.SOURCE_TYPE_MIC,
        capturerFlags: 0
      }
    };
    
    audio.createAudioCapturer(audioCapturerOptions, (err, data) => {
      if (err) {
        console.error(`Create AudioCapturer failed: ${err.code}, ${err.message}`);
      } else {
        let audioCapturer = data;
      }
    });
    
  2. 监听音频数据

    利用on('readData')方法监听音频数据并处理:

    let bufferSize = 0;
    let path = getContext().cacheDir;
    let filePath = path + '/output.pcm';
    let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
    
    let readDataCallback = (buffer) => {
      let options = {
        offset: bufferSize,
        length: buffer.byteLength
      };
      fileIo.writeSync(file.fd, buffer, options);
      bufferSize += buffer.byteLength;
    };
    
    audioCapturer.on('readData', readDataCallback);
    
  3. 开始采集音频

    当准备工作完成后,可以开始音频采集:

    audioCapturer.start((err) => {
      if (err) {
        console.error('Audio capturing start failed.');
      } else {
        console.info('Audio capturing started successfully.');
      }
    });
    
分享
微博
QQ
微信
回复
7天前
相关问题
AudioCapturer录音+AudioRenderer播放音频
1279浏览 • 1回复 待解决
使用AudioCapturer开发音频录制功能
1251浏览 • 1回复 待解决
监听音频打断事件,该如何处理
964浏览 • 1回复 待解决