HarmonyOS 请提供AVRecorder demo示例

HarmonyOS
2024-12-25 15:56:25
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
fox280

参考demo:

import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import { common } from '@kit.AbilityKit';
import fs from '@ohos.file.fs';
import { media } from '@kit.MediaKit';
import { BusinessError } from '@kit.BasicServicesKit';

class AudioRecorderDemo {
  private fd: number

  constructor(fd: number) {
    this.fd = fd;
  }

  private avRecorder: media.AVRecorder | undefined = undefined;
  private avProfile: media.AVRecorderProfile = {
    audioBitrate: 100000, // 音频比特率
    audioChannels: 2, // 音频声道数
    audioCodec: media.CodecMimeType.AUDIO_AAC, // 音频编码格式,当前只支持aac
    audioSampleRate: 48000, // 音频采样率
    fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // 封装格式,当前只支持m4a
  };

  getAVConfig(): media.AVRecorderConfig {
    return {
      audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // 音频输入源,这里设置为麦克风
      profile: this.avProfile,
      url: `fd://${this.fd}`, // 参考应用文件访问与管理开发示例新建并读写一个文件
    };
  }

  // 注册audioRecorder回调函数
  setAudioRecorderCallback() {
    if (this.avRecorder != undefined) {
      // 状态机变化回调函数
      this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => {
        console.log(`AudioRecorder current state is ${state}`);
      })
      // 错误上报回调函数
      this.avRecorder.on('error', (err: BusinessError) => {
        console.error(`AudioRecorder failed, code is ${err.code}, message is ${err.message}`);
      })
    }
  }

  // 开始录制对应的流程
  async startRecordingProcess() {
    try {
      if (this.avRecorder != undefined) {
        await this.avRecorder.release();
        this.avRecorder = undefined;
      }
      // 1.创建录制实例
      this.avRecorder = await media.createAVRecorder();
      this.setAudioRecorderCallback();
      // 2.获取录制文件fd赋予avConfig里的url;参考FilePicker文档
      // 3.配置录制参数完成准备工作
      await this.avRecorder.prepare(this.getAVConfig());
      // 4.开始录制
      await this.avRecorder.start();
    } catch (e) {
      console.error(`test error e: ${JSON.stringify(e)}`)
    }
  }

  // 暂停录制对应的流程
  async pauseRecordingProcess() {
    if (this.avRecorder != undefined && this.avRecorder.state === 'started') { // 仅在started状态下调用pause为合理状态切换
      await this.avRecorder.pause();
    }
  }

  // 恢复录制对应的流程
  async resumeRecordingProcess() {
    if (this.avRecorder != undefined && this.avRecorder.state === 'paused') { // 仅在paused状态下调用resume为合理状态切换
      await this.avRecorder.resume();
    }
  }

  // 停止录制对应的流程
  async stopRecordingProcess() {
    if (this.avRecorder != undefined) {
      // 1. 停止录制
      if (this.avRecorder.state === 'started'
        || this.avRecorder.state === 'paused') { // 仅在started或者paused状态下调用stop为合理状态切换
        await this.avRecorder.stop();
      }
      // 2.重置
      await this.avRecorder.reset();
      // 3.释放录制实例
      await this.avRecorder.release();
      this.avRecorder = undefined;
      // 4.关闭录制文件fd
      fs.close(this.fd)
    }
  }

  // 一个完整的【开始录制-暂停录制-恢复录制-停止录制】示例
  async audioRecorderDemo() {
    await this.startRecordingProcess(); // 开始录制
    // 用户此处可以自行设置录制时长,例如通过设置休眠阻止代码执行
    await this.pauseRecordingProcess(); //暂停录制
    await this.resumeRecordingProcess(); // 恢复录制
    await this.stopRecordingProcess(); // 停止录制
  }
}

@Entry
@Component
struct AVRecorderPage {
  @State message: string = 'Hello World';
  av?: AudioRecorderDemo
  atManager = abilityAccessCtrl.createAtManager();
  permissions: Array<Permissions> = [
    'ohos.permission.MICROPHONE',
    'ohos.permission.WRITE_MEDIA',
    'ohos.permission.READ_MEDIA',
    'ohos.permission.MEDIA_LOCATION',
  ];
  @State path: string = "";
  async start() {
    let result = await this.requestPermissions();
    if (result) {
      let context = getContext() as common.UIAbilityContext;
      this.path = context.filesDir + "/" + "AV_" + Date.parse(new Date().toString()) + ".m4a";
      let file = this.createOrOpen(this.path);
      this.av = new AudioRecorderDemo(file.fd)
      this.av.startRecordingProcess()
    }
  }

  createOrOpen(path: string): fs.File {
    let isExist = fs.accessSync(path);
    let file: fs.File;
    if (isExist) {
      file = fs.openSync(path, fs.OpenMode.READ_WRITE);
    } else {
      file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
    }
    return file;
  }

  //第1步:请求权限
  async requestPermissions(): Promise<boolean> {
    return await new Promise((resolve: Function) => {
      try {
        let context = getContext() as common.UIAbilityContext;
        this.atManager.requestPermissionsFromUser(context, this.permissions)
          .then(async () => {
            console.log(`test info : ${JSON.stringify("权限请求成功")}`)
            resolve(true)
          }).catch(() => {
          console.error(`test info : ${JSON.stringify("权限请求异常")}`)
          resolve(false)
        });
      } catch (err) {
        console.error(`test info : ${JSON.stringify("权限请求err")}` + err)
        resolve(false)
      }
    });
  }

  build() {
    Column() {
      Button('start').onClick(() => {
        this.start()
      })
      Button('pause').onClick(() => {
        this.av?.pauseRecordingProcess()
      })
      Button('resume').onClick(() => {
        this.av?.resumeRecordingProcess()
      })
      Button('stop').onClick(() => {
        this.av?.stopRecordingProcess()
      })
    }
    .height('100%')
    .width('100%')
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151.
  • 152.
  • 153.
  • 154.
  • 155.
  • 156.
  • 157.
  • 158.
  • 159.
  • 160.
  • 161.
  • 162.
  • 163.
  • 164.
  • 165.
  • 166.
  • 167.
  • 168.
  • 169.
  • 170.
  • 171.
  • 172.
  • 173.
  • 174.
  • 175.
  • 176.
  • 177.
  • 178.
  • 179.
  • 180.
分享
微博
QQ
微信
回复
2024-12-25 18:53:12
相关问题
HarmonyOS 请提供音频编码示例
688浏览 • 1回复 待解决
HarmonyOS 请提供个路由跳转Demo
1206浏览 • 1回复 待解决
请提供HarmonyOS硬编硬解demo
1306浏览 • 1回复 待解决
HarmonyOS 如何实现下列功能,请提供demo
1512浏览 • 1回复 待解决
HarmonyOS 请提供自定义组件封装demo
1346浏览 • 2回复 待解决
请提供一个简单示例
2788浏览 • 1回复 待解决
请提供HarmonyOS短视频实例代码
1170浏览 • 1回复 待解决
HarmonyOS 请提供dsbridge样例代码
858浏览 • 1回复 待解决
HarmonyOS 请提供RAS加解密的文档
1009浏览 • 1回复 待解决
HarmonyOS 消息通知使用示例demo
1191浏览 • 1回复 待解决