HarmonyOS 后台服务全局录音demo?

开启录音后,app处于任何页面或者后台都能录音并进行保存。

阅读 595
1 个回答

可以使用AVRecord结合长时任务实现。参考链接:

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/using-avrecorder-for-recording-V5

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/continuous-task-V5

可参考如下代码实现录音功能:

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(`tag 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.关闭录制文件
      fs.close(this.fd)
    }
  }

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

@Entry
@Component
struct Index {
  @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";
      console.log(`this.path: ${this.path}`);
      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%')
  }
}

需要在module.json5文件中声明权限:

"requestPermissions": [
      {
        "name": "ohos.permission.MICROPHONE",
        "reason": "$string:app_name",
        "usedScene": {
          "abilities": [
            "FormAbility"
          ],
          "when":"always"
        }
      },
      {
        "name": "ohos.permission.MEDIA_LOCATION",
        "reason": "$string:app_name",
        "usedScene": {
          "abilities": [
            "FormAbility"
          ],
          "when":"always"
        }
      },
      {
        "name": "ohos.permission.WRITE_MEDIA",
        "reason": "$string:app_name",
        "usedScene": {
          "abilities": [
            "FormAbility"
          ],
          "when":"always"
        }
      },
      {
        "name": "ohos.permission.READ_MEDIA",
        "reason": "$string:app_name",
        "usedScene": {
          "abilities": [
            "FormAbility"
          ],
          "when":"always"
        }
      }
    ],
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进