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

HarmonyOS
2024-12-05 15:14:40
838浏览
收藏 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;
      }
    });
    
    • 1.
    • 2.
    • 3.
    • 4.
    • 5.
    • 6.
    • 7.
    • 8.
    • 9.
    • 10.
    • 11.
    • 12.
    • 13.
    • 14.
    • 15.
    • 16.
    • 17.
    • 18.
    • 19.
    • 20.
    • 21.
    • 22.
    • 23.
    • 24.
  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);
    
    • 1.
    • 2.
    • 3.
    • 4.
    • 5.
    • 6.
    • 7.
    • 8.
    • 9.
    • 10.
    • 11.
    • 12.
    • 13.
    • 14.
    • 15.
  3. 开始采集音频

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

    audioCapturer.start((err) => {
      if (err) {
        console.error('Audio capturing start failed.');
      } else {
        console.info('Audio capturing started successfully.');
      }
    });
    
    • 1.
    • 2.
    • 3.
    • 4.
    • 5.
    • 6.
    • 7.
分享
微博
QQ
微信
回复
2024-12-05 16:22:04


相关问题