使用AudioCapturer录制音频

1,初始化AudioCapturer对象

// 初始化录音对象的
  static async init(){
  // 初始化AduioCapture对象
    audio.createAudioCapturer({
      // 描述录音的文件流的相关的参数
      streamInfo:{
        //采样率
        samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_16000,
        //声道3
        channels:audio.AudioChannel.CHANNEL_1,
        // 采样位数
        sampleFormat:audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
        // 编码类型
        encodingType:audio.AudioEncodingType.ENCODING_TYPE_RAW  // PCM  .wav格式的文件

      },
      // 描述录音的属性
      capturerInfo:{
        source: audio.SourceType.SOURCE_TYPE_VOICE_COMMUNICATION, // 语音通话场景的音频源
        // 录音的标志
        capturerFlags:0,

      }
    },(err,capture)=>{
      if(err){
        console.log('mylog->','初始化录音对象出错:'+JSON.stringify(err))
        return
      }

      AduioCaptureServices.currentCapturer = capture
    }
    )
  }

2,准备录音文件

    const fileName = Date.now().toString() + Math.random().toString()
    const filePath = getContext().cacheDir + '/' + fileName +'.wav'

    // 在磁盘上读写文件,如果这个文件没有,则创建
    const file = fs.openSync(filePath,fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)

3,开始录音

// 将录音数据写到磁盘文件 xxxx.wav中
    AduioCaptureServices.isRecording = true

    let count = 0
    // 注意:Capturer对象每次录制的长度都是一样的 644  1288
    let bufferSize = AduioCaptureServices.currentCapturer.getBufferSizeSync()  // 获取到当前录音的缓存大小

    while (AduioCaptureServices.isRecording) {
    // 获取到当前录制对象收集到的录音数据,写入到磁盘中
      let arrayBuffer = await AduioCaptureServices.currentCapturer.read(bufferSize,true) // 读取当前录制的音频流数据
      // 将数据写入到磁盘文件
      fs.writeSync(file.fd,arrayBuffer,{
        offset:count * bufferSize,
        length:bufferSize
      })
      count ++
    }

  // 打印录制音频的长度
    console.log('mylog-> 录制文件的大小:',fs.statSync(file.fd).size)

4,结束录音

//   停止录音
  static async stop(){

    // 停止录制
    AduioCaptureServices.isRecording = false

    // 判断当前录制对象是否是录制中或者是暂停
    if(AduioCaptureServices.currentCapturer.state !== audio.AudioState.STATE_RUNNING
    && AduioCaptureServices.currentCapturer.state !== audio.AudioState.STATE_PAUSED ) {
      console.warn('mylog->','只有状态为【录制中】或【暂停】时才能停止')
      return;
    }

    await AduioCaptureServices.currentCapturer.stop()
    console.log('mylog->','录音已经停止')
  }

5,完整代码


import fs from '@ohos.file.fs';
import { audio } from '@kit.AudioKit';
录音类

export class AduioCaptureServices {
  static currentCapturer:audio.AudioCapturer
  static isRecording:boolean = false


  // 初始化录音对象的
  static async init(){
  // 初始化AduioCapture对象
    audio.createAudioCapturer({
      // 描述录音的文件流的相关的参数
      streamInfo:{
        //采样率
        samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_16000,
        //声道3
        channels:audio.AudioChannel.CHANNEL_1,
        // 采样位数
        sampleFormat:audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
        // 编码类型
        encodingType:audio.AudioEncodingType.ENCODING_TYPE_RAW  // PCM  .wav格式的文件

      },
      // 描述录音的属性
      capturerInfo:{
        source: audio.SourceType.SOURCE_TYPE_VOICE_COMMUNICATION, // 语音通话场景的音频源
        // 录音的标志
        capturerFlags:0,

      }
    },(err,capture)=>{
      if(err){
        console.log('mylog->','初始化录音对象出错:'+JSON.stringify(err))
        return
      }

      AduioCaptureServices.currentCapturer = capture
    }
    )
  }

//  开始录音
  static async start(file:fs.File){

    console.log('mylog->',file.path)

    // 开始录音
    await AduioCaptureServices.currentCapturer.start()

  // 将录音数据写到磁盘文件 xxxx.wav中
    AduioCaptureServices.isRecording = true

    let count = 0
    // 注意:Capturer对象每次录制的长度都是一样的 644  1288
    let bufferSize = AduioCaptureServices.currentCapturer.getBufferSizeSync()  // 获取到当前录音的缓存大小

    while (AduioCaptureServices.isRecording) {
    // 获取到当前录制对象收集到的录音数据,写入到磁盘中
      let arrayBuffer = await AduioCaptureServices.currentCapturer.read(bufferSize,true) // 读取当前录制的音频流数据
      // 将数据写入到磁盘文件
      fs.writeSync(file.fd,arrayBuffer,{
        offset:count * bufferSize,
        length:bufferSize
      })
      count ++
    }

  // 打印录制音频的长度
    console.log('mylog-> 录制文件的大小:',fs.statSync(file.fd).size)
  }


//   停止录音
  static async stop(){

    // 停止录制
    AduioCaptureServices.isRecording = false

    // 判断当前录制对象是否是录制中或者是暂停
    if(AduioCaptureServices.currentCapturer.state !== audio.AudioState.STATE_RUNNING
    && AduioCaptureServices.currentCapturer.state !== audio.AudioState.STATE_PAUSED ) {
      console.warn('mylog->','只有状态为【录制中】或【暂停】时才能停止')
      return;
    }

    await AduioCaptureServices.currentCapturer.stop()
    console.log('mylog->','录音已经停止')
  }

}

import fs from '@ohos.file.fs';

export class FileServices {

  static createFile(){
    const fileName = Date.now().toString() + Math.random().toString()
    const filePath = getContext().cacheDir + '/' + fileName +'.wav'

    // 在磁盘上读写文件,如果这个文件没有,则创建
    const file = fs.openSync(filePath,fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
    return file
  }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值