React Native视频压缩求助:react-native-compress失效,求替代库
我之前也碰到过react-native-compress不好用的情况,给你推荐几个React Native里常用的视频压缩替代库,附上简单的调用代码,你可以试试看:
1. react-native-video-compressor
这个库专门做视频压缩,支持iOS和Android双平台,压缩质量可自定义,稳定性还不错,是很多开发者的替代首选。
安装命令:
npm install react-native-video-compressor --save # 或者用yarn yarn add react-native-video-compressor
调用示例:
import { VideoCompressor } from 'react-native-video-compressor'; const compressVideo = async (filePath) => { try { // 可选预设质量:low, medium, high,也能自定义比特率 const compressedResult = await VideoCompressor.compress( filePath, { quality: 'medium', // 如需更精细控制,可添加比特率参数(单位bps) // bitrate: 600000, // 600kbps } ); console.log('压缩完成,输出路径:', compressedResult.path); return compressedResult.path; } catch (error) { console.error('视频压缩失败:', error); } };
2. react-native-ffmpeg
如果需要更灵活的视频处理(比如边压缩边裁剪、转格式),react-native-ffmpeg绝对是首选——它基于强大的FFmpeg工具,功能覆盖几乎所有视频处理场景。
安装命令:
npm install react-native-ffmpeg --save # iOS需额外执行pod安装 cd ios && pod install && cd ..
调用示例(基础视频压缩):
import RNFFmpeg from 'react-native-ffmpeg'; const compressWithFFmpeg = async (inputPath, outputPath) => { try { // CRF值控制画质:0-51,数值越小画质越高(推荐23-28为平衡值) // preset控制压缩速度:medium是速度与压缩率的平衡点,fast更快、slow压缩率更高 const command = `-i ${inputPath} -crf 26 -preset medium ${outputPath}`; const executionResult = await RNFFmpeg.execute(command); if (executionResult.returnCode === 0) { console.log('压缩成功,输出路径:', outputPath); return outputPath; } else { console.error('FFmpeg执行失败:', executionResult); } } catch (error) { console.error('命令执行出错:', error); } };
3. react-native-compressor
这个是多功能压缩工具,支持视频、图片、音频压缩,API设计简洁,上手门槛低,适合不需要复杂处理的场景。
安装命令:
npm install react-native-compressor --save # iOS需执行pod安装 cd ios && pod install && cd ..
调用示例:
import { compressVideo } from 'react-native-compressor'; const handleCompression = async (filePath) => { try { const compressedPath = await compressVideo(filePath, { compressionMethod: 'auto', // 自动选择最优压缩逻辑 quality: 0.6, // 质量系数0-1,数值越大画质越高 }); console.log('压缩后的视频路径:', compressedPath); return compressedPath; } catch (error) { console.error('压缩出错:', error); } };
内容的提问来源于stack exchange,提问作者Punam Maitri




