ionic 压缩和上传视频文件

ionic 压缩和上传视频文件

通过 Video Editor 插件压缩视频文件,然后使用 File 插件 转为 Blob 文件

依赖

  1. 安装File插件
ionic cordova plugin add cordova-plugin-file

npm install @ionic-native/file
复制代码
  1. 安装Video Editor插件
ionic cordova plugin add cordova-plugin-video-editor

npm install @ionic-native/video-editor
复制代码

使用

  1. 导入 VideoEditor 插件和 File 插件
import { VideoEditor } from '@ionic-native/video-editor';
import { File } from '@ionic-native/file';

constructor(private videoEditor: VideoEditor,private file: File) { }

复制代码
  1. 使用 Camera 选择视频或 MediaCapture 录制视频

  2. 传入视频文件路径,返回压缩后视频文件的路径

   async transcodeVideo(path: string):Promise<string>{
    const fileUri = path.startsWith('file://') ? path : `file://${path}`;

    const videoInfo = await this.videoEditor.getVideoInfo({ fileUri });
    let width: number;
    let height: number;

    // 视频比例
    const ratio = videoInfo.width / videoInfo.height;

    if (ratio > 1) {
      width = videoInfo.width > 480 ? 480 : videoInfo.width;
    } else if (ratio < 1) {
      width = videoInfo.width > 360 ? 360 : videoInfo.width;
    } else if (ratio === 1) {
      width = videoInfo.width > 480 ? 480 : videoInfo.width;
    }

    height = +(width / ratio).toFixed(0);

    return this.videoEditor.transcodeVideo({
      fileUri,
      outputFileName: `${Date.now()}`,
      outputFileType: this.videoEditor.OutputFileType.MPEG4,
      width,
      height
    });

  }
复制代码
  1. 把压缩后的视频转成 Blob
  async readAsDataURL(path: string): Promise<string> {
    const paths = path.split(/\//);
    const fileName = paths[paths.length - 1];

    let url = path.replace(fileName, '');

    url = url.startsWith('file://') ? url : `file://${url}`;

    return this.file.readAsDataURL(url, fileName);
  }
复制代码
  dataURLtoBlob(dataURL: string): Blob {
    const arr = dataURL.split(',');
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);

    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }

    const type = arr[0].match(/:(.*?);/)[1];
    return new Blob([u8arr], { type });
  }
复制代码
  1. 使用 FormData 上传视频文件
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值