工作中没有任何有趣的事情感到无聊吗?好吧,就在那时,我决定抓紧时间修补浏览器 API 的当前状态。我们可以直接通过 Web API 压缩视频吗?在这篇博客中,我将向您展示如何使用现代浏览器功能将 MP4 视频压缩为 WebM 格式 - 所有这些都在 React 应用程序中进行。
在我们深入之前,请确保您已经:
快速设置:
<p>npm install antd</p>
让我们使用所有 React 导入来设置 React 组件:
<p>import { useState, useRef, useEffect, ChangeEvent } from "react";<br> import { Button, Progress, message, Flex } from "antd";</p> <p>const VideoCompression = () => {<br> const [sourceVideo, setSourceVideo] = useState<File | null>(null);<br> const [compressedVideo, setCompressedVideo] = useState<Blob | null>(null);<br> const [isCompressing, setIsCompressing] = useState(false);<br> const [progress, setProgress] = useState(0);<br> const [width, setWidth] = useState<string>("");<br> const [height, setHeight] = useState<string>("");<br> const videoRef = useRef<HTMLVideoElement>(null);<br> const inputRef = useRef<HTMLInputElement>(null);</p>
我们需要一种方法来选择 MP4 文件:
<p>const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => {<br> if (!event.target.files) return;<br> const file = event.target.files[0];<br> if (file && file.type.startsWith("video/")) {<br> setSourceVideo(file);<br> setCompressedVideo(null);<br> } else {<br> message.error("Please select a valid video file.");<br> }<br> };</p>
让我们获取视频元数据:
<p>useEffect(() => {<br> if (sourceVideo) {<br> const video = document.createElement("video");<br> video.onloadedmetadata = () => {<br> setWidth(video.videoWidth.toString());<br> setHeight(video.videoHeight.toString());<br> };<br> video.src = URL.createObjectURL(sourceVideo);<br> }<br> }, [sourceVideo]);</p>
这就是奇迹发生的地方:
<p>const compressVideo = async () => {<br> if (!sourceVideo) {<br> message.error("Please upload a video first.");<br> return;<br> }<br> setIsCompressing(true);<br> setProgress(0);<br> try {<br> const stream = videoRef.current?.captureStream();<br> const mediaRecorder = new MediaRecorder(stream, {<br> mimeType: "video/webm",<br> videoBitsPerSecond: 1000000,<br> });<br> const chunks: BlobPart[] = [];<br> mediaRecorder.ondataavailable = (event) => {<br> if (event.data.size > 0) {<br> chunks.push(event.data);<br> }<br> };<br> mediaRecorder.onstop = () => {<br> const blob = new Blob(chunks, { type: "video/webm" });<br> setCompressedVideo(blob);<br> setIsCompressing(false);<br> setProgress(100);<br> };<br> if (!videoRef.current) return;<br> videoRef.current.onloadedmetadata = () => {<br> videoRef.current!.muted = true;<br> videoRef.current?.play();<br> mediaRecorder.start();<br> };<br> videoRef.current.onended = () => {<br> mediaRecorder.stop();<br> videoRef.current?.pause();<br> };<br> videoRef.current.ontimeupdate = () => {<br> if (!videoRef.current) return;<br> const progress =<br> (videoRef.current.currentTime / videoRef.current.duration) * 100;<br> setProgress(progress);<br> };<br> if (!videoRef.current) return;<br> videoRef.current.width = Number.parseFloat(width);<br> videoRef.current.height = Number.parseFloat(height);<br> videoRef.current.src = URL.createObjectURL(sourceVideo);<br> } catch (err) {<br> message.error("Error compressing video: " + (err as Error).message);<br> setIsCompressing(false);<br> }<br> };</p>
<p>const downloadCompressedVideo = () => {<br> if (compressedVideo) {<br> const url = URL.createObjectURL(compressedVideo);<br> const a = document.createElement("a");<br> a.href = url;<br> a.download = "compressed_video.webm";<br> document.body.appendChild(a);<br> a.click();<br> document.body.removeChild(a);<br> URL.revokeObjectURL(url);<br> }<br> };</p>
以下是我们完整作品的预览:
部署链接:
https://abhirup-99.github.io/browser-compression-webm/
代码链接:
https://github.com/Abhirup-99/browser-compression-webm
恭喜!您刚刚使用 React 构建了一个功能强大的 MP4 到 WebM 视频压缩器。现在,您的网络视频加载速度将比以往更快,从而取悦用户并提高网站的性能。
以上是在浏览器中将视频压缩为 webm的详细内容。更多信息请关注PHP中文网其他相关文章!