从API version 9开始,支持后台长时任务开发功能。应用配置后台长时任务可以支持应用后台录音。
后台录音是指应用在前台启动录音任务后,退至后台仍持续采集音频的场景。典型场景包括会议记录、语音备忘、采访录音等需要长时间录制的业务。
后台录音涉及麦克风采集和后台运行。应用需要同时满足麦克风权限、录音能力实现、后台长时任务声明和系统管控要求,不应在用户无感知或未授权的情况下启动录音。
应用实现录音功能的具体内容请参考使用AudioCapturer开发音频录制功能(ArkTS)、推荐使用OHAudio开发音频录制功能(C/C++)或使用AVRecorder录制音频(ArkTS)。当应用需要退至后台持续录音时,还需要申请录音类型的长时任务(ArkTS)。
声明后台录音模式。
在module.json5配置文件中,为需要执行后台录音的UIAbility声明audioRecording后台模式。
- {
- "abilities": [
- {
- "name": "EntryAbility",
- "backgroundModes": [
- "audioRecording"
- ]
- }
- ]
- }
启动录音任务。
应用需要在前台启动录音任务,启动后可以退至后台继续录音。在后台直接启动录音会失败。
录音开始前,应用需要确认用户已经明确触发录音操作,并处理麦克风权限未授权、设备被占用、存储路径不可用等异常场景。录音开发方式请参考音频录制开发概述。
针对应用在后台录音被其他音频流打断后无法恢复的场景,推荐使用以下解决方案:
申请录音类型长时任务。
当录音需要退至后台持续运行时,应用需要申请AUDIO_RECORDING类型长时任务,使系统识别该后台任务与录音业务匹配。
- import { BusinessError } from '@kit.BasicServicesKit';
- import { backgroundTaskManager } from '@kit.BackgroundTasksKit'
- import { wantAgent, WantAgent } from '@kit.AbilityKit'
- // ...
-
- // 开启长时任务。
- startContinuousTask(context: Context) {
- let wantAgentInfo: wantAgent.WantAgentInfo = {
- // 点击通知后,将要执行的动作列表。
- // 添加需要被拉起应用的bundleName和abilityName。
- wants: [
- {
- bundleName: 'com.example.backgroundmusic',
- abilityName: 'MainAbility'
- }
- ],
- // 指定点击通知栏消息后的动作是拉起ability。
- actionType: wantAgent.OperationType.START_ABILITY,
- // 使用者自定义的一个私有值。
- requestCode: 0,
- // 点击通知后,动作执行属性。
- actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG],
- };
-
- try {
- // 通过wantAgent模块下getWantAgent方法获取WantAgent对象。
- wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => {
- try {
- let list: string[] = ['audioPlayback', 'audioRecording'];
- backgroundTaskManager.startBackgroundRunning(context, list, wantAgentObj)
- .then(() => {
- console.info('Operate startBackgroundRunning succeeded');
- })
- .catch((error: BusinessError) => {
- console.error(`Failed to operate startBackgroundRunning. code is ${error.code} message is ${error.message}`);
- });
- } catch (error) {
- console.error(`Failed to operate startBackgroundRunning. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
- };
- });
- } catch (error) {
- console.error(`Failed to operate getWantAgent. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
- }
- }
长时任务启动失败时,应用需避免继续以后台录音方式运行,应停止录音或引导用户回到前台处理。长时任务的完整申请和取消流程请参考长时任务(ArkTS)。
停止录音并释放资源。
用户停止录音、录音异常中断或业务结束时,应用需要调用AudioCapturer的release接口停止录音、释放音频采集资源,并同步取消录音类型长时任务。
- // 取消长时任务。
- stopContinuousTask(context: Context) {
- backgroundTaskManager.stopBackgroundRunning(context).then(() => {
- console.info(`Succeeded in operating stopBackgroundRunning.`);
- }).catch((err: BusinessError) => {
- console.error(`Failed to operate stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
- });
- }