demo如下:let context = getContext() as common.UIAbilityContext; this.path = context.filesDir + "/" + "VIDEO_" + Date.parse(new Date().toString()) + ".mp4"; let file = FileUtil.createOrOpen(this.path); this.url = "fd://" + file.fd;import fs from '@ohos.file.fs'; import buffer from '@ohos.buffer'; // 大小和单位 const GB_MAGNITUDE: number = 1024 * 1024 * 1024 const MB_MAGNITUDE: number = 1024 * 1024 const KB_MAGNITUDE: number = 1024 const GB_SYMBOL: string = 'GB' const MB_SYMBOL: string = 'MB' const KB_SYMBOL: string = 'KB' const BYTE_SYMBOL: string = 'B' export class FileUtil { /** * 新建并打开文件 */ static 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; } /** * 保存arrayBuffer到文件 * @param path * @param arrayBuffer * @returns */ static writeBufferToFile(path: string, arrayBuffer: ArrayBuffer): number { try { let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); let value = fs.writeSync(file.fd, arrayBuffer); fs.closeSync(file); return value; }catch (err){ console.log("FileUtil", "writeFile err:" + err); return -1; } } /** * 保存文本到文件 * @param path * @param text * @returns */ static writeStrToFile(path: string, text: string): number { try { let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); let value = fs.writeSync(file.fd, text); fs.closeSync(file); return value; }catch (err) { console.log("FileUtil", "writeFile err:" + err); return -1; } } }"requestPermissions": [ { "name": "ohos.permission.CAMERA", "reason": "$string:app_name", "usedScene": { "abilities": [ "FormAbility" ], "when":"always" } }, { "name": "ohos.permission.INTERNET" }, { "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" } },import camera from '@kit.CameraKit'; import media from '@kit.MediaKit'; import { BusinessError,commonEventManager } from '@kit.BasicServicesKit'; import common from '@kit.AbilityKit'; import router from '@kit.ArkUI'; import fileUri from '@kit.CoreFileKit'; import Logger from '../utils/Logger'; import { FileUtil } from '../utils/FileUtil'; /** * 视频录制 */ class routerParams { text:string data:string constructor(str:string, data:string) { this.text = str this.data = data } } @Entry @Component struct Lx { private mXComponentController: XComponentController = new XComponentController; private surfaceId: string = ''; //预览控件宽高 @State xComponentWidth: number = 0; @State xComponentHeight: number = 0; @State videoUri: string = ""; url: string = ""; @State recording: boolean = false; //正在录制视频 @State isFinished: boolean = false; @State path: string = ""; @State cameraManager: camera.CameraManager | undefined = undefined; @State videoOutput: camera.VideoOutput | undefined = undefined; @State captureSession: camera.Session | undefined = undefined; @State cameraInput: camera.CameraInput | undefined = undefined; @State previewOutput: camera.PreviewOutput | undefined = undefined; @State avRecorder: media.AVRecorder | undefined = undefined; controller: VideoController = new VideoController(); aboutToAppear() { let context = getContext() as common.UIAbilityContext; this.path = context.filesDir + "/" + "VIDEO_" + Date.parse(new Date().toString()) + ".mp4"; let file = FileUtil.createOrOpen(this.path); this.url = "fd://" + file.fd; this.videoUri = fileUri.getUriFromPath(this.path); // 用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 let subscriber: commonEventManager.CommonEventSubscriber | null = null; // 订阅飞行模式状态变化公共事件 // 行模式状态变化订阅者信息 let subscribeInfo2: commonEventManager.CommonEventSubscribeInfo = { events: ["usual.event.SCREEN_OFF"], } // 创建飞行模式状态变化订阅者回调 commonEventManager.createSubscriber(subscribeInfo2, (err: BusinessError, data: commonEventManager.CommonEventSubscriber) => { if (err) { console.error(`MayTest Failed to create subscriber. Code is ${err.code}, message is ${err.message}`); return; } console.info('MayTest Succeeded in creating subscriber.'); subscriber = data; // 订阅公共事件回调 if (subscriber !== null) { commonEventManager.subscribe(subscriber, (err: BusinessError, data: commonEventManager.CommonEventData) => { if (err) { console.error(`MayTest订阅锁屏模式状态变化公共事件失败. Code is ${err.code}, message is ${err.message}`); return; } if (data.event == "usual.event.SCREEN_OFF") { this.controller.stop(); this.stopRecord(); let options: router.RouterOptions = { url: '', params: new routerParams("沙箱路径", this.path) } router.back(options); } console.info('MayTest成功订阅锁屏模式状态变化公共事件') }) } else { console.error(`MayTest Need create subscriber`); } }) } build() { Stack({ alignContent: Alignment.Top }) { if (!this.isFinished) { XComponent({ id: 'componentId', type: 'surface', controller: this.mXComponentController, }).onLoad(async () => { this.surfaceId = this.mXComponentController.getXComponentSurfaceId(); let baseContext = getContext() as common.BaseContext; await this.initCamera(baseContext, this.surfaceId) }).width('100%') .height('100%') } else { Video({ src: this.videoUri, controller: this.controller }).autoPlay(true) } Column() { Button("返回", { type: ButtonType.Circle, stateEffect: false }) .width(80) .height(80) .fontSize(16) .fontColor('#ffffff') .margin({ left: 20, top: 20 }) .onClick(() => { this.controller.stop(); let options: router.RouterOptions = { url: '', params: new routerParams("沙箱路径", this.path) } router.back(options); }) Blank() if (!this.isFinished) { Row() { Button(this.recording ? "停止录制" : "开始录制", { type: ButtonType.Circle, stateEffect: false }) .width(120) .height(120) .fontSize(20) .margin({ left: 20 }) .fontColor('#ffffff') .onClick(() => { if (this.recording) { this.stopRecord(); } else { this.startRecord(); } this.recording = !this.recording; }) } .width('100%') .height(120) .margin({ bottom: 60 }) .justifyContent(FlexAlign.Center) .alignItems(VerticalAlign.Center) } }.width('100%') .height('100%') .justifyContent(FlexAlign.Start) .alignItems(HorizontalAlign.Start) }.width('100%') } }
demo如下: