HarmonyOS 鸿蒙Next是否有屏幕录制的demo参考

发布于 1周前 作者 phonegap100 来自 鸿蒙OS

HarmonyOS 鸿蒙Next是否有屏幕录制的demo参考

版本 beta1  最好是能包含权限获取的相关代码

2 回复

暂无ArkTS录屏接口的案例,当前只提供了C++侧的文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/using-avscreencapture-for-file-V5

参考以下demo,其中录制的视频存储在沙盒路径,录制结束保存到了相册。

import { media } from '@kit.MediaKit'

import { BusinessError } from '@kit.BasicServicesKit'

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

import { abilityAccessCtrl, common, PermissionRequestResult, Permissions } from '@kit.AbilityKit'

import { photoAccessHelper } from '@kit.MediaLibraryKit';

import { promptAction } from '@kit.ArkUI';

@Entry

@Component

struct Index13 {

  private avScreenCaptureRecorder: media.AVScreenCaptureRecorder | undefined = undefined;

  private context = getContext(this) as common.UIAbilityContext;

  private filesDir: string = this.context.filesDir; // 保存到沙盒路径 data/storage/el2/base/haps/entry/files

  private filesUri:string = this.filesDir + '/Screen_' + new Date().getTime() + '.mp4';

  private curFile = fs.openSync(this.filesUri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);

  private avCaptureConfig: media.AVScreenCaptureRecordConfig = {

  fd: this.curFile.fd, // 文件需要先有调用者创建,赋予写权限,将文件fd传给此参数

  frameWidth: 640,

  frameHeight: 480

}

  aboutToAppear(): void {

    let permissions: Array<Permissions> =['ohos.permission.WRITE_IMAGEVIDEO','ohos.permission.READ_IMAGEVIDEO']

    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();

    //requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗

    atManager.requestPermissionsFromUser(this.context, permissions).then((data: PermissionRequestResult) => {

      let grantStatus: Array<number> = data.authResults;

      let length: number = grantStatus.length;

      for (let i = 0; i < length; i++) {

        if (grantStatus[i] != 0) {

          //用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限

          return;

        }

      }

      console.info(`Success to request permissions from user. authResults is ${grantStatus}.`);

    }).catch((err: BusinessError) => {

      console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);

    })

    this.createAVScreenCapture();

  }

  createAVScreenCapture() {

    media.createAVScreenCaptureRecorder().then((captureRecorder: media.AVScreenCaptureRecorder) => {

      if (captureRecorder != null) {

        this.avScreenCaptureRecorder = captureRecorder;

        console.info('Succeeded in createAVScreenCaptureRecorder');

        this.init();

      } else {

        console.error('Failed to createAVScreenCaptureRecorder');

      }

    }).catch((error: BusinessError) => {

      console.error(`createAVScreenCaptureRecorder catchCallback, error message:${error.message}`);

    });

  }

  async init() {

    if (this.avScreenCaptureRecorder !== undefined) {

      await this.avScreenCaptureRecorder.init(this.avCaptureConfig).then(() => {

        console.info('Succeeded in initing avScreenCaptureRecorder');

      }).catch((err: BusinessError) => {

        console.info('Failed to init avScreenCaptureRecorder, error: ' + err.message);

      })

    }

  }

  build() {

    Column({space:30}) {

      Button('开始录屏')

        .onClick(() => {

          this.startRecord()

        })

        .width('100%')

      Button('结束录屏')

        .onClick(() => {

          this.stopRecord()

        })

        .width('100%')

    }

  }

  async startRecord() {

    if (this.avScreenCaptureRecorder !== undefined) {

      await this.avScreenCaptureRecorder.startRecording().then(() => {

        console.info('Succeeded in starting avScreenCaptureRecorder');

      }).catch((err: BusinessError) => {

        console.info('Failed to start avScreenCaptureRecorder, error: ' + err.message);

      })

    }

  }

  async stopRecord() {

    if (this.avScreenCaptureRecorder !== undefined) {

      await this.avScreenCaptureRecorder.stopRecording().then(() => {

        console.info('Succeeded in stopping avScreenCaptureRecorder');

        this.saveVideo();

      }).catch((err: BusinessError) => {

        console.info('Failed to stop avScreenCaptureRecorder, error: ' + err.message);

      })

    }

  }

  saveVideo() {

    let titleStr = 'testVideo'+ new Date().getTime()

    let context = getContext(this);

    let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);

    console.debug("getPhotoAccessHelper success: ")

    let photoType: photoAccessHelper.PhotoType = photoAccessHelper.PhotoType.VIDEO;

    let extension:string = 'mp4';

    let options: photoAccessHelper.CreateOptions = {

      title:titleStr

    }

    phAccessHelper.createAsset(photoType, extension, options).then(async (uriDes:string)=>{

      // 使用uri打开文件,可以持续写入内容,写入过程不受时间限制

      try {

        // 写到媒体库文件中

        let file_uri =  fs.openSync(this.filesUri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);

        let file =  fs.openSync(uriDes, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);

        // 内容复制到媒体库文件中

        fs.copyFileSync(file_uri.fd, file.fd);

        fs.closeSync(file.fd);

        fs.closeSync(file_uri.fd);

        promptAction.showToast({

          message: '已保存至相册',

          duration: 2500

        });

      }catch (err) {

        console.error("error is "+ JSON.stringify(err))

      }

    }).catch((err:Error)=>{

        console.error("error is "+ JSON.stringify(err))

    });

  }

}

HarmonyOS 鸿蒙Next确实提供了屏幕录制的功能,并且开发者可以基于其API进行相关的开发。虽然官方可能未直接提供一个完整的屏幕录制demo,但开发者可以通过鸿蒙系统的相关文档和API来实现这一功能。

具体来说,屏幕录制通常涉及到对屏幕内容的捕获和编码,以及后续的保存或分享。在HarmonyOS 鸿蒙Next中,开发者可以利用系统提供的多媒体处理API,如CameraKit和AVRecorder等,来实现屏幕内容的捕获和录制。

CameraKit可以用于获取屏幕预览流,而AVRecorder则用于将捕获的内容进行编码并保存到文件中。开发者需要配置AVRecorder的相关参数,如视频编码格式、比特率、分辨率等,以满足不同的录制需求。

由于具体的实现细节可能涉及较多的编程知识和经验,建议开发者参考HarmonyOS的官方文档和API指南,以及相关的开发者社区和论坛来获取更详细的帮助和指导。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部