npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@luqi_test/cordova-plugin-media-capture

v6.0.0

Published

Cordova media-capture Plugin

Readme

cordova-plugin-media-capture

1. 插件介绍

cordova-plugin-media-capture 是 Apache Cordova 生态中用于实现移动应用媒体捕获功能的核心插件,支持调用设备原生的摄像头、麦克风等硬件,实现照片拍摄、视频录制、音频录制等媒体采集操作。该插件遵循 Cordova 跨平台开发规范,封装了不同操作系统的原生媒体捕获接口,开发者无需编写平台特定代码,即可通过统一的 JavaScript API 快速集成媒体捕获能力,大幅降低跨平台应用的开发成本。本文档主要说明该插件在OHOS系统中的应用。

插件具备以下核心特性:

  • 多类型媒体捕获:支持照片(单张 / 多张)、视频、音频三种主流媒体类型的捕获,满足社交分享、内容创作、实时记录等场景需求;

  • 原生体验适配:调用设备原生媒体应用(如系统相机、录音机),保留原生操作逻辑与交互体验,避免自定义界面带来的兼容性问题;

  • 灵活参数配置:支持自定义媒体质量(如照片分辨率、视频码率、音频采样率)、捕获数量、时长限制等参数,适配不同业务场景;

  • 完善的错误处理:提供清晰的错误码与错误信息,覆盖权限拒绝、设备不支持、存储空间不足等异常场景,便于开发者调试与用户引导。

2. 支持平台

插件已针对以下操作系统和设备完成兼容性适配,确保媒体捕获功能稳定运行:

  • Android:API 级别 21 及以上(覆盖 Android 5.0 及更高版本),支持主流品牌手机(如华为、小米、OPPO、三星等)的原生相机与录音机应用;

  • iOS:iOS 11.0 及以上,支持 iPhone、iPad 全系列设备,适配 notch 屏(刘海屏)、动态岛等特殊屏幕布局;

  • Windows:Windows 10 及以上,支持 UWP(通用 Windows 平台)应用,可调用桌面端摄像头与麦克风;

  • Browser:主流桌面及移动浏览器(Chrome 70+、Firefox 65+、Edge 79+、Safari 13+),通过浏览器原生 getUserMedia API 模拟媒体捕获功能(仅支持照片与音频,视频捕获依赖浏览器支持);

  • HamonyOS:5.0 及以上,可调用桌面端摄像头与麦克风。

3. 安装步骤

3.1 前提条件

在安装插件前,需确保开发环境满足以下要求:

  1. 已安装 Node.js(v14.0.0 及以上)和 npm(v6.0.0 及以上),可通过 node -vnpm -v 命令验证版本;

  2. 已全局安装 HCordova CLI(v10.0.0 及以上),若未安装,执行以下命令:

npm install -g hcordova
  1. 已创建 Cordova 项目(若未创建,执行 hcordova create MediaCaptureApp com.example.mediacapture 媒体捕获示例应用 快速创建);

3.2 插件安装命令

在 Cordova 项目根目录下,根据需求选择以下安装方式:

常用安装方法

安装稳定版本,适合大多数开发场景:

#全平台安装
hcordova plugin add cordova-plugin-media-capture

#指定平台安装
hcordova plugin add cordova-plugin-media-capture --platform ohos

从 GitCode 源码安装

hcordova plugin add https://gitcode.com/OpenHarmony-Cordova/cordova-plugin-media-capture.git --platform ohos

安装指定版本

若项目需兼容特定版本,可指定版本号安装:

hcordova plugin add [email protected] --platform ohos

3.3 插件卸载与查看

  • 卸载插件
#全平台卸载
hcordova plugin remove cordova-plugin-media-capture

#指定OHOS系统平台
hcordova plugin remove cordova-plugin-media-capture --platform ohos
  • 查看已安装插件
hcordova plugin list

若输出结果包含 cordova-plugin-media-capture,则表示插件已成功安装。

5. 核心 API 说明

插件通过全局对象 navigator.device.capture 暴露媒体捕获 API,所有 API 需在 deviceready 事件触发后调用(确保 Cordova 环境就绪)。以下是各 API 的详细说明:

5.1 捕获照片(captureImage)

调用设备相机捕获照片,支持单张或多张拍摄,返回照片文件的路径、大小、类型等信息。

方法签名

navigator.device.capture.captureImage(
   successCallback,  // 捕获成功回调
   errorCallback,    // 捕获失败回调
   options           // 配置参数(可选)
);

参数说明

| 参数名 | 类型 | 说明 | | ----------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | successCallback | Function | 捕获成功时触发,参数为 MediaFile 数组(每张照片对应一个 MediaFile 对象) | | errorCallback | Function | 捕获失败时触发,参数为 CaptureError 对象(包含错误码和错误信息) | | options | Object | 可选配置参数,属性如下:- quality:Number,照片质量(0-100,100 为最高,默认 80);),返回是URL |

示例代码

document.addEventListener('deviceready', function() {
   // 点击“拍摄照片”按钮
   document.getElementById('captureImageBtn').addEventListener('click', function() {
       // 配置参数:捕获3张照片,质量80
       const options = {
           quality: 80
       };

       // 调用捕获照片API
       navigator.device.capture.captureImage(
           function(mediaFiles) {
               // 成功回调:遍历照片列表并展示
               const imageContainer = document.getElementById('imageContainer');
               imageContainer.innerHTML = ''; // 清空原有内容
               mediaFiles.forEach((file, index) => {
                   console.log(`照片${index+1}信息:`, file);
                   // 创建图片元素
                   const img = document.createElement('img');
                   img.src = file.fullPath; // 文件路径(如:file:///storage/emulated/0/DCIM/Camera/IMG_20250101_123456.jpg)
                   img.style.width = '200px';
                   img.style.margin = '10px';
                   
                   // 添加图片到容器
                   imageContainer.appendChild(img);

                   // 可选:获取照片Base64编码(适合小文件,如头像)
                   const reader = new FileReader();

                   reader.onloadend = function() {
                       const base64 = reader.result;
                       console.log(`照片${index+1}Base64:`, base64.substring(0, 50) + '...'); // 打印前50字符避免过长

                   };

                   reader.readAsDataURL(file);
               });

               alert(`成功捕获${mediaFiles.length}张照片!`);

           },

           function(error) {
               // 失败回调:处理错误
               let errorMsg = '';
               switch(error.code) {
                   case CaptureError.PERMISSION_DENIED:
                       errorMsg = '权限被拒绝,请在设置中允许应用访问相机和存储';
                       break;
                   case CaptureError.NO_MEDIA_FILES:
                       errorMsg = '未捕获到照片,请重试';
                       break;
                   case CaptureError.NOT_SUPPORTED:
                       errorMsg = '当前设备不支持照片捕获功能';
                       break;
                   default:
                       errorMsg = `捕获失败:${error.message}(错误码:${error.code})`;
               }
               alert(errorMsg);
               console.error('照片捕获错误:', error);
           },
           options
       );
   });
}, false);

5.2 捕获视频(captureVideo)

调用设备相机录制视频,支持配置录制时长、视频质量等参数,返回视频文件信息。

方法签名

navigator.device.capture.captureVideo(
   successCallback,  // 录制成功回调
   errorCallback,    // 录制失败回调
   options           // 配置参数(可选)
);

参数说明

| 参数名 | 类型 | 说明 | | ----------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | successCallback | Function | 录制成功时触发,参数为 MediaFile 数组(每个视频对应一个 MediaFile 对象) | | errorCallback | Function | 录制失败时触发,参数为 CaptureError 对象 | | options | Object | 鸿蒙使用安全相机,参数配置无效|

示例代码

document.addEventListener('deviceready', function() {
   // 点击“录制视频”按钮
   document.getElementById('captureVideoBtn').addEventListener('click', function() {
       // 鸿蒙使用安全相机,配置参数无效
       const options = {
           limit: 1,
           quality: 'high',
           duration: 30,
           videoEncoding: 'H264'
       };

       // 调用捕获视频API

       navigator.device.capture.captureVideo(
           function(mediaFiles) {
               const video = mediaFiles[0];
               console.log('视频信息:', video);

               // 展示视频
               const videoContainer = document.getElementById('videoContainer');
               videoContainer.innerHTML = '';
               const videoElement = document.createElement('video');
               videoElement.src = video.fullPath;
               videoElement.controls = true; // 显示播放控制
               videoElement.style.width = '300px';
               videoContainer.appendChild(videoElement);

               // 显示视频信息
               const videoInfo = document.createElement('div');
               videoInfo.innerHTML = `
                   <p>视频路径:${video.fullPath}</p>
                   <p>视频大小:${(video.size / (1024 * 1024)).toFixed(2)} MB</p>
                   <p>录制时长:${video.duration} 秒</p>
                   <p>文件类型:${video.type}</p>
               `;

               videoContainer.appendChild(videoInfo);
               alert(`成功录制1段视频(${(video.size / (1024 * 1024)).toFixed(2)} MB)!`);
           },

           function(error) {
               // 失败处理
               let errorMsg = '';
               switch(error.code) {
                   case CaptureError.PERMISSION_DENIED:
                       errorMsg = '权限被拒绝,请允许应用访问相机、麦克风和存储';
                       break;
                   case CaptureError.MEDIA_FILE_SIZE_EXCEEDED:
                       errorMsg = '视频文件过大,建议缩短录制时长或降低质量';
                       break;
                   default:
                       errorMsg = `录制失败:${error.message}(错误码:${error.code})`;
               }

               alert(errorMsg);
               console.error('视频捕获错误:', error);
           },
           options
       );
   });
}, false);

5.3 捕获音频(captureAudio)

调用设备麦克风录制音频,支持配置录制时长、音频质量等参数,返回音频文件信息。

方法说明

navigator.device.capture.captureAudio(
   successCallback,  // 录制成功回调
   errorCallback,    // 录制失败回调
   options           // 配置参数(可选)
);

参数说明

| 参数名 | 类型 | 说明 | | ----------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | successCallback | Function | 录制成功时触发,参数为 MediaFile 数组(每个音频对应一个 MediaFile 对象) | | errorCallback | Function | 录制失败时触发,参数为 CaptureError 对象 | | options | Object | 鸿蒙使用自定义UI,参数配置无效,具体时长有用户UI决定 |

示例代码

document.addEventListener('deviceready', function() {
   // 点击“录制音频”按钮
   document.getElementById('captureAudioBtn').addEventListener('click', function() {
       //鸿蒙使用自定义UI,参数配置无效,具体时长有用户UI决定
       const options = {
           limit: 1,
           quality: 'high',
           duration: 60,
           audioEncoding: 'AAC'
       };
       // 调用捕获音频API
       navigator.device.capture.captureAudio(
           function(mediaFiles) {
               const audio = mediaFiles[0];
               console.log('音频信息:', audio);

               // 展示音频播放控件
               const audioContainer = document.getElementById('audioContainer');
               audioContainer.innerHTML = '';
               const audioElement = document.createElement('audio');
               audioElement.src = audio.fullPath;
               audioElement.controls = true;
               audioElement.style.width = '300px';
               audioContainer.appendChild(audioElement);

               // 显示音频信息
               const audioInfo = document.createElement('div');
               audioInfo.innerHTML = `
                   <p>音频路径:${audio.fullPath}</p>
                   <p>音频大小:${(audio.size / 1024).toFixed(2)} KB</p>
                   <p>录制时长:${audio.duration} 秒</p>
                   <p>文件类型:${audio.type}</p>
               `;

               audioContainer.appendChild(audioInfo);
               alert(`成功录制1段音频(${audio.duration} 秒)!`);
           },

           function(error) {

               // 失败处理
               let errorMsg = '';
               switch(error.code) {
                   case CaptureError.PERMISSION_DENIED:
                       errorMsg = '权限被拒绝,请允许应用访问麦克风和存储';
                       break;
                   case CaptureError.NOT_SUPPORTED:
                       errorMsg = '当前设备不支持音频录制功能';
                       break;
                   default:
                       errorMsg = `录制失败:${error.message}(错误码:${error.code})`;

               }

               alert(errorMsg);
               console.error('音频捕获错误:', error);
           },
           options
       );
   });
}, false);

5.4 核心对象说明

5.4.1 MediaFile 对象

捕获成功后返回的媒体文件对象,具体参考cordova-plugin-file插件,包含以下关键属性:

| 属性名 | 类型 | 说明 | | ------------------ | ------ | -------------------------------------------------------------------------- | | name | String | 文件名(如 IMG_20250101_123456.jpg) | | fullPath | String | 文件完整路径(如 file:///storage/emulated/0/DCIM/Camera/IMG_20250101_123456.jpg) | | type | String | 文件 MIME 类型(如 image/jpegvideo/mp4audio/aac) | | size | Number | 文件大小(单位:字节) |

5.4.2 CaptureError 对象

捕获失败时返回的错误对象,包含以下关键属性:

| 属性名 | 类型 | 说明 | | --------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | code | Number | 错误码,取值如下:- CaptureError.PERMISSION_DENIED(1):权限被拒绝;- CaptureError.NOT_SUPPORTED(2):设备不支持该功能;- CaptureError.NO_MEDIA_FILES(3):未捕获到媒体文件;- CaptureError.MEDIA_FILE_SIZE_EXCEEDED(4):文件大小超过限制;- CaptureError.INVALID_ARGUMENT(5):传入无效参数 | | message | String | 错误描述信息(平台特定) |

6. 平台特定注意事项

6.1 OHOS 权限

在主工程的module.json5中配置权限

 {
    "name": "ohos.permission.MICROPHONE",
    "reason": "$string:microphoneInfo",
    "usedScene": {
        "abilities": [
        "EntryAbility"
        ],
        "when": "always"
    }
},
{
    "name": "ohos.permission.CAMERA",
    "reason": "$string:cameraInfo",
    "usedScene": {
        "abilities": [
        "EntryAbility"
        ],
        "when": "always"
    }
}

7. 许可证

本插件基于 Apache 许可证 2.0 版 开源。详见 LICENSE 文件。

8 联系我们

  1. Apache Cordova:访问 Apache Cordova 官方仓库

  2. OHOS cordova:访问https://gitcode.com/OpenHarmony-Cordova/cordova-plugin-media-capture