HarmonyOS 鸿蒙Next 上传视频 压缩视频 视频处理

HarmonyOS 鸿蒙Next 中经常遇到上传视频 压缩视频的需求,下面我们给大家看看上传视频前如何对视频进行压缩和处理

1、压缩视频可以先安装videocompressor模块

ohpm install @ohos/videocompressor

2、调用videoCompressor.compressVideo实现压缩视频

let videoCompressor = new VideoCompressor();
videoCompressor.compressVideo(getContext(),this.selectFilePath,CompressQuality.COMPRESS_QUALITY_HIGH).then((data) => {
    if (data.code == CompressorResponseCode.SUCCESS) {
        console.log("videoCompressor HIGH message:" + data.message + "--outputPath:" + data.outputPath);
    } else {
        console.log("videoCompressor HIGH code:" + data.code + "--error message:" + data.message);
    }
    }).catch((err) => {
        console.log("videoCompressor HIGH get error message" + err.message);
})

更多关于HarmonyOS 鸿蒙Next 上传视频 压缩视频 视频处理的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS 鸿蒙Next 上传视频 压缩视频 视频处理的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


HarmonyOS 鸿蒙Next 上传视频 压缩视频 视频处理完整代码

import { AppBar } from './widget/AppBar'
import PermissionUtil from '../common/PermissionUtil';
import { Permissions } from '@ohos.abilityAccessCtrl';
import { promptAction } from '@kit.ArkUI';
import { cameraPicker as picker } from '@kit.CameraKit';
import { camera } from '@kit.CameraKit';
import { common } from '@kit.AbilityKit';
import { BusinessError, request } from '@kit.BasicServicesKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import fs from '@ohos.file.fs';
import {VideoCompressor,CompressQuality,CompressorResponseCode} from "@ohos/videocompressor"
//获取context对象
let mContext = getContext(this) as common.Context;

@Builder
export function VideoUploadPageBuilder() {
  VideoUploadPage()
}

@Component
struct VideoUploadPage {
  @State message: string = 'Hello World';
  @State imagePath: string = ""
  @State videoPath: string = ""
  private pathStack = new NavPathStack()

  //录制视频
  takeVideo = async () => {
    try {
      // 创建一个选择器对象,并设置参数
      let pickerProfile: picker.PickerProfile = {
        cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK
      };
      // 调用选择器对象,实现拍照
      let pickerResult: picker.PickerResult = await picker.pick(mContext,
        [picker.PickerMediaType.VIDEO], pickerProfile);
      console.log("the pick pickerResult is:" + JSON.stringify(pickerResult));
      this.convertImgUri(pickerResult.resultUri)
      //图片地址
      this.videoPath = pickerResult.resultUri
    } catch (error) {
      let err = error as BusinessError;
      console.error(`the pick call failed. error code: ${err.code}`);
    }
  }

  //相册选择视频
  pickerVideo = () => {
    try {
      // 创建一个选择器对象,并设置参数
      let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
      PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.VIDEO_TYPE;  //视频
      PhotoSelectOptions.maxSelectNumber = 5;
      //  调用选择器对象,实现选择图片
      let photoPicker = new photoAccessHelper.PhotoViewPicker();
      photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {
        console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
        this.videoPath = PhotoSelectResult.photoUris[0]
        this.convertImgUri(PhotoSelectResult.photoUris[0])
      }).catch((err: BusinessError) => {
        console.error(`PhotoViewPicker.select failed with err: ${err.code}, ${err.message}`);
      });
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(`PhotoViewPicker failed with err: ${err.code}, ${err.message}`);
    }
  }

  //录制视频的权限
  checkTakeVideoPermission = async () => {
    let permissions: Array<Permissions> = ['ohos.permission.CAMERA', 'ohos.permission.MICROPHONE']
    //检测权限
    let hasPermission = await PermissionUtil.checkPermission(permissions)
    if (hasPermission) {
      this.takeVideo()
    } else {
      let grantStatus = await PermissionUtil.requestPermission(permissions)
      if (grantStatus) {
        this.takeVideo()
      } else {
        //跳转到权限设置的引导页面
        PermissionUtil.openPermissionSettings("com.itying.myapplication")
      }
    }

  }
  /*
目标:
   file://media/Photo/229/IMG_1729508435_214/IMG_20241021_185855.jpg 复制到  cache目录     file://com.itying.xxx/data/xxx/cache/xxxxx.png
   转换成  `internal://cache/file.txt`
  */
  convertImgUri=(uri: string)=> {
    //压缩视频
    let videoCompressor = new VideoCompressor();
    videoCompressor.compressVideo(getContext(),uri,CompressQuality.COMPRESS_QUALITY_LOW).then((data) => {
      if (data.code == CompressorResponseCode.SUCCESS) {
        console.log("videoCompressor HIGH message:" + data.message + "--outputPath:" + data.outputPath);
        fs.open(data.outputPath, fs.OpenMode.READ_ONLY).then((file) => {
          //context
          let context = getContext(this);
          let fileName=Date.now()   //获取当前时间戳
          let extName=uri.split(".")[1]
          let newDir=context.cacheDir+"/"+fileName+"."+extName   // file://com.itying.xxx/data/xxx/cache/1232141254.jpg

          fs.copyFile(file.fd, newDir).then(()=>{
            this.uploadFile(newDir,extName)
          })
        });
      } else {
        console.log("videoCompressor HIGH code:" + data.code + "--error message:" + data.message);
      }
    }).catch((err:Error) => {
      console.log("videoCompressor HIGH get error message" + err.message);
    })



  }
  //上传文件
  uploadFile = (uri:string,extName:string) => {
    //比如环境路径  file://com.itying.xxx/data/xxx/cache/xxxxx.png
    let fileName=uri.split("cache/")[1]
    let uploadUri="internal://cache/"+fileName
    let uploadTask: request.UploadTask;
    let uploadConfig: request.UploadConfig = {
      url: 'https://miapp.itying.com/imgupload', // 需要手动将url替换为真实服务器的HTTP协议地址
      header: { 'Accept': '*/*' },
      method: "POST",
      files: [{ filename: fileName, name: "himg", uri: uploadUri, type: extName }], // 建议type填写HTTP协议规范的MIME类型
      data: [{ name: "uid", value: "123" },{ name: "sign", value: "qwfwqrwqrwqtrwqtqt"}],
    };
    try {
      request.uploadFile(getContext(), uploadConfig).then((data: request.UploadTask) => {
        uploadTask = data;
        //监听上传进度
        uploadTask.on('progress', (uploadedSize: number, totalSize: number) => {
          console.info("upload totalSize:" + totalSize + "  uploadedSize:" + uploadedSize);
          this.message="upload totalSize:" + totalSize + "  uploadedSize:" + uploadedSize
        });

        uploadTask.on('headerReceive', (headers) => {
          console.log(headers["body"])
        });
        //{"success":"true","path":"public/upload/h0wncqAQLRj6wcMLcQnC8HFE.jpg"}
        //通过拼接域名可以访问服务器返回的图片地址   				https://miapp.itying.com/public/upload/h0wncqAQLRj6wcMLcQnC8HFE.jpg


      }).catch((err: BusinessError) => {
        console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
      });
    } catch (err) {
      console.error(`Failed to request the upload. err: ${JSON.stringify(err)}`);
    }
  }

  build() {
    NavDestination() {
      Scroll() {
        Column() {

          Text(this.message).fontSize(20)



          Button() {
            Text("录制视频")
              .fontSize(18)
              .fontWeight(FontWeight.Bold)
              .fontColor(Color.White)
          }.onClick(this.checkTakeVideoPermission).margin({
            top: 20
          }).width("80%")
          .height(50)


          Button() {
            Text("相册选择视频")
              .fontSize(18)
              .fontWeight(FontWeight.Bold)
              .fontColor(Color.White)
          }.onClick(this.pickerVideo).margin({
            top: 20
          }).width("80%")
          .height(50)




          if (this.imagePath) {
            Image(this.imagePath)
              .width(120)
              .height(120)
              .backgroundColor(Color.Grey)
              .margin({ top: 20 })
          }


          if (this.videoPath) {
            Video({
              src: this.videoPath
            }).width("100%")
              .height(300)
              .margin({ top: 20 })
          }
        }
        .width('100%')
        .justifyContent(FlexAlign.Start)
      }
    }.onReady((context: NavDestinationContext) => {
      this.pathStack = context.pathStack
    }).title("sha")
  }
}
回到顶部