HarmonyOS 自定义相机摄像,关于media.AVRecorderConfig参数url的配置

HarmonyOS
2024-12-27 16:26:47
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
FengTianYa

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%')
  }
}
分享
微博
QQ
微信
回复
2024-12-27 18:08:21
相关问题
HarmonyOS 关于自定义相机功能
190浏览 • 1回复 待解决
HarmonyOS 自定义相机前置摄像头变形
220浏览 • 1回复 待解决
自定义配置参数设定有会吗?
2008浏览 • 1回复 待解决
HarmonyOS 自定义相机demo
482浏览 • 1回复 待解决
HarmonyOS 自定义相机功能
160浏览 • 1回复 待解决
HarmonyOS 如何自定义相机
156浏览 • 1回复 待解决
HarmonyOS 自定义相机预览问题
178浏览 • 1回复 待解决
HarmonyOS 自定义相机演示demo
337浏览 • 1回复 待解决
HarmonyOS 如何自定义相机背景
147浏览 • 1回复 待解决
HarmonyOS 自定义编译构建参数
245浏览 • 1回复 待解决
自定义参数BuildProfile问题汇总
1899浏览 • 1回复 待解决
是否能够自定义router跳转url
953浏览 • 1回复 待解决
HarmonyOS 自定义相机预览拉伸问题
23浏览 • 1回复 待解决
HarmonyOS 关于自定义弹窗封装调用
592浏览 • 2回复 待解决
HarmonyOS 应用名称如何自定义配置
370浏览 • 0回复 待解决
HarmonyOS 应用名称如何自定义配置
433浏览 • 1回复 待解决
HarmonyOS 自定义相机拍照不成功
163浏览 • 1回复 待解决
HarmonyOS 使用自定义相机左边有间距
132浏览 • 1回复 待解决
HarmonyOS 自定义相机拍照后数据展示
934浏览 • 1回复 待解决
能够提供HarmonyOS自定义相机案例吗?
486浏览 • 1回复 待解决
如何在BuildProfile中自定义参数
438浏览 • 1回复 待解决
HarmonyOS 关于自定义协议跳转APP
166浏览 • 1回复 待解决