Skip to main content

视频优化

本页面概述了如何在 Next.js 应用中使用视频,展示如何在不影响性能的情况下存储和显示视频文件。

¥This page outlines how to use videos with Next.js applications, showing how to store and display video files without affecting performance.

使用 <video><iframe>

¥Using <video> and <iframe>

可以使用 HTML <video> 标签(对于直接视频文件)和 <iframe>(对于外部平台托管的视频)将视频嵌入到页面上。

¥Videos can be embedded on the page using the HTML <video> tag for direct video files and <iframe> for external platform-hosted videos.

<video>

HTML <video> 标签可以嵌入自托管或直接提供的视频内容,从而可以完全控制播放和外观。

¥The HTML <video> tag can embed self-hosted or directly served video content, allowing full control over the playback and appearance.

export function Video() {
return (
<video width="320" height="240" controls preload="none">
<source src="/path/to/video.mp4" type="video/mp4" />
<track
src="/path/to/captions.vtt"
kind="subtitles"
srcLang="en"
label="English"
/>
Your browser does not support the video tag.
</video>
)
}

常见的 <video> 标签属性

¥Common <video> tag attributes

属性描述示例值
src指定视频文件的来源。<video src="/path/to/video.mp4" />
width设置视频播放器的宽度。<video width="320" />
height设置视频播放器的高度。<video height="240" />
controls如果存在,它会显示默认的播放控件集。<video controls />
autoPlay页面加载时自动开始播放视频。注意:自动播放策略因浏览器而异。<video autoPlay />
loop循环播放视频。<video loop />
muted默认情况下将音频静音。常与 autoPlay 一起使用。<video muted />
preload指定视频的预加载方式。值:none, metadata, auto.<video preload="none" />
playsInline在 iOS 设备上启用内联播放,这通常是在 iOS Safari 上自动播放所必需的。<video playsInline />

很高兴知道:使用 autoPlay 属性时,还必须包含 muted 属性以确保视频在大多数浏览器中自动播放,并包含 playsInline 属性以与 iOS 设备兼容。

¥Good to know: When using the autoPlay attribute, it is important to also include the muted attribute to ensure the video plays automatically in most browsers and the playsInline attribute for compatibility with iOS devices.

有关视频属性的完整列表,请参阅 MDN 文档

¥For a comprehensive list of video attributes, refer to the MDN documentation.

视频最佳实践

¥Video best practices

  • 后备内容:使用 <video> 标签时,请在标签内包含不支持视频播放的浏览器的后备内容。

    ¥Fallback Content: When using the <video> tag, include fallback content inside the tag for browsers that do not support video playback.

  • 字幕或说明文字:为耳聋或听力有困难的用户添加字幕或说明文字。使用 <track> 标签和 <video> 元素来指定字幕文件源。

    ¥Subtitles or Captions: Include subtitles or captions for users who are deaf or hard of hearing. Utilize the <track> tag with your <video> elements to specify caption file sources.

  • 可访问的控件:建议使用标准 HTML5 视频控件来实现键盘导航和屏幕阅读器兼容性。对于高级需求,请考虑 react-playervideo.js 等第三方播放器,它们提供可访问的控件和一致的浏览器体验。

    ¥Accessible Controls: Standard HTML5 video controls are recommended for keyboard navigation and screen reader compatibility. For advanced needs, consider third-party players like react-player or video.js, which offer accessible controls and consistent browser experience.

<iframe>

HTML <iframe> 标签允许你嵌入来自 YouTube 或 Vimeo 等外部平台的视频。

¥The HTML <iframe> tag allows you to embed videos from external platforms like YouTube or Vimeo.

export default function Page() {
return (
<iframe
src="https://www.youtube.com/watch?v=gfU1iZnjRZM"
frameborder="0"
allowfullscreen
/>
)
}

常见的 <iframe> 标签属性

¥Common <iframe> tag attributes

属性描述示例值
src要嵌入的页面的 URL。<iframe src="https://example.com" />
width设置 iframe 的宽度。<iframe width="500" />
height设置 iframe 的高度。<iframe height="300" />
frameborder指定是否在 iframe 周围显示边框。<iframe frameborder="0" />
allowfullscreen允许 iframe 内容以全屏模式显示。<iframe allowfullscreen />
sandbox对 iframe 内的内容启用一组额外的限制。<iframe sandbox />
loading优化加载行为(例如延迟加载)。<iframe loading="lazy" />
title为 iframe 提供标题以支持辅助功能。<iframe title="Description" />

有关 iframe 属性的完整列表,请参阅 MDN 文档

¥For a comprehensive list of iframe attributes, refer to the MDN documentation.

选择视频嵌入方法

¥Choosing a video embedding method

你可以通过两种方式将视频嵌入 Next.js 应用中:

¥There are two ways you can embed videos in your Next.js application:

  • 自托管或直接视频文件:对于需要对播放器功能和外观进行详细控制的场景,使用 <video> 标签嵌入自托管视频。Next.js 中的这种集成方法允许自定义和控制你的视频内容。

    ¥Self-hosted or direct video files: Embed self-hosted videos using the <video> tag for scenarios requiring detailed control over the player's functionality and appearance. This integration method within Next.js allows for customization and control of your video content.

  • 使用视频托管服务(YouTube、Vimeo 等):对于 YouTube 或 Vimeo 等视频托管服务,你将使用 <iframe> 标签嵌入其基于 iframe 的播放器。虽然这种方法限制了对玩家的一些控制,但它提供了这些平台提供的易用性和功能。

    ¥Using video hosting services (YouTube, Vimeo, etc.): For video hosting services like YouTube or Vimeo, you'll embed their iframe-based players using the <iframe> tag. While this method limits some control over the player, it offers ease of use and features provided by these platforms.

选择符合你的应用要求和你想要提供的用户体验的嵌入方法。

¥Choose the embedding method that aligns with your application's requirements and the user experience you aim to deliver.

嵌入外部托管视频

¥Embedding externally hosted videos

要嵌入来自外部平台的视频,你可以使用 Next.js 获取视频信息并使用 React Suspense 处理加载时的回退状态。

¥To embed videos from external platforms, you can use Next.js to fetch the video information and React Suspense to handle the fallback state while loading.

1.

第一步是创建一个 服务器组件,它生成用于嵌入视频的适当 iframe。该组件将获取视频的源 URL 并渲染 iframe。

¥The first step is to create a Server Component that generates the appropriate iframe for embedding the video. This component will fetch the source URL for the video and render the iframe.

export default async function VideoComponent() {
const src = await getVideoSrc()

return <iframe src={src} frameborder="0" allowfullscreen />
}

2.

创建用于嵌入视频的服务器组件后,下一步是使用 React Suspense 对组件进行 stream

¥After creating the Server Component to embed the video, the next step is to stream the component using React Suspense.

import { Suspense } from 'react'
import VideoComponent from '../ui/VideoComponent.jsx'

export default function Page() {
return (
<section>
<Suspense fallback={<p>Loading video...</p>}>
<VideoComponent />
</Suspense>
{/* Other content of the page */}
</section>
)
}

很高兴知道:嵌入来自外部平台的视频时,请考虑以下最佳实践:

¥Good to know: When embedding videos from external platforms, consider the following best practices:

  • 确保视频嵌入具有响应能力。使用 CSS 使 iframe 或视频播放器适应不同的屏幕尺寸。

    ¥Ensure the video embeds are responsive. Use CSS to make the iframe or video player adapt to different screen sizes.

  • 根据网络情况实现 加载视频的策略,特别是对于流量套餐有限的用户。

    ¥Implement strategies for loading videos based on network conditions, especially for users with limited data plans.

这种方法可以带来更好的用户体验,因为它可以防止页面阻塞,这意味着用户可以在视频组件流入时与页面交互。

¥This approach results in a better user experience as it prevents the page from blocking, meaning the user can interact with the page while the video component streams in.

为了获得更具吸引力和信息丰富的加载体验,请考虑使用加载骨架作为后备 UI。因此,你可以显示类似于视频播放器的骨架,而不是显示简单的加载消息,如下所示:

¥For a more engaging and informative loading experience, consider using a loading skeleton as the fallback UI. So instead of showing a simple loading message, you can show a skeleton that resembles the video player like this:

import { Suspense } from 'react'
import VideoComponent from '../ui/VideoComponent.jsx'
import VideoSkeleton from '../ui/VideoSkeleton.jsx'

export default function Page() {
return (
<section>
<Suspense fallback={<VideoSkeleton />}>
<VideoComponent />
</Suspense>
{/* Other content of the page */}
</section>
)
}

自托管视频

¥Self-hosted videos

由于以下几个原因,自托管视频可能更受欢迎:

¥Self-hosting videos may be preferable for several reasons:

  • 完全控制和独立:自托管使你可以直接管理视频内容,从播放到外观,确保完全的所有权和控制权,不受外部平台的限制。

    ¥Complete control and independence: Self-hosting gives you direct management over your video content, from playback to appearance, ensuring full ownership and control, free from external platform constraints.

  • 针对特定需求的定制:它非常适合独特的要求,例如动态背景视频,它允许量身定制以符合设计和功能需求。

    ¥Customization for specific needs: Ideal for unique requirements, like dynamic background videos, it allows for tailored customization to align with design and functional needs.

  • 性能和可扩展性考虑因素:选择高性能且可扩展的存储解决方案,以有效支持不断增加的流量和内容大小。

    ¥Performance and scalability considerations: Choose storage solutions that are both high-performing and scalable, to support increasing traffic and content size effectively.

  • 成本和集成:平衡存储和带宽成本与轻松集成到 Next.js 框架和更广泛的技术生态系统的需求。

    ¥Cost and integration: Balance the costs of storage and bandwidth with the need for easy integration into your Next.js framework and broader tech ecosystem.

使用 Vercel Blob 进行视频托管

¥Using Vercel Blob for video hosting

维塞尔斑点 提供了一种有效的视频托管方式,提供了可与 Next.js 良好配合的可扩展云存储解决方案。以下是使用 Vercel Blob 托管视频的方法:

¥Vercel Blob offers an efficient way to host videos, providing a scalable cloud storage solution that works well with Next.js. Here's how you can host a video using Vercel Blob:

1.

在 Vercel 仪表板中,导航到 "贮存" 选项卡并选择你的 维塞尔斑点 存储。在 Blob 表的右上角,找到并单击 "上传" 按钮。然后,选择你要上传的视频文件。上传完成后,视频文件将出现在 Blob 表中。

¥In your Vercel dashboard, navigate to the "Storage" tab and select your Vercel Blob store. In the Blob table's upper-right corner, find and click the "Upload" button. Then, choose the video file you wish to upload. After the upload completes, the video file will appear in the Blob table.

或者,你可以使用服务器操作上传视频。有关详细说明,请参阅 服务器端上传 上的 Vercel 文档。Vercel 还支持 客户端上传。对于某些用例,此方法可能更佳。

¥Alternatively, you can upload your video using a server action. For detailed instructions, refer to the Vercel documentation on server-side uploads. Vercel also supports client-side uploads. This method may be preferable for certain use cases.

2.

视频上传并存储后,你可以在 Next.js 应用中显示它。以下是如何使用 <video> 标签和 React Suspense 执行此操作的示例:

¥Once the video is uploaded and stored, you can display it in your Next.js application. Here's an example of how to do this using the <video> tag and React Suspense:

import { Suspense } from 'react'
import { list } from '@vercel/blob'

export default function Page() {
return (
<Suspense fallback={<p>Loading video...</p>}>
<VideoComponent fileName="my-video.mp4" />
</Suspense>
)
}

async function VideoComponent({ fileName }) {
const { blobs } = await list({
prefix: fileName,
limit: 1,
})
const { url } = blobs[0]

return (
<video controls preload="none" aria-label="Video player">
<source src={url} type="video/mp4" />
Your browser does not support the video tag.
</video>
)
}

在此方法中,页面使用视频的 @vercel/blob URL 来显示使用 VideoComponent 的视频。React Suspense 用于显示回退,直到获取视频 URL 并且视频准备好显示为止。

¥In this approach, the page uses the video's @vercel/blob URL to display the video using the VideoComponent. React Suspense is used to show a fallback until the video URL is fetched and the video is ready to be displayed.

为你的视频添加字幕

¥Adding subtitles to your video

如果你的视频有字幕,你可以使用 <video> 标签内的 <track> 元素轻松添加字幕。你可以按照与视频文件类似的方式从 维塞尔斑点 中获取字幕文件。以下是更新 <VideoComponent> 以包含字幕的方法。

¥If you have subtitles for your video, you can easily add them using the <track> element inside your <video> tag. You can fetch the subtitle file from Vercel Blob in a similar way as the video file. Here's how you can update the <VideoComponent> to include subtitles.

async function VideoComponent({ fileName }) {
const { blobs } = await list({
prefix: fileName,
limit: 2,
})
const { url } = blobs[0]
const { url: captionsUrl } = blobs[1]

return (
<video controls preload="none" aria-label="Video player">
<source src={url} type="video/mp4" />
<track src={captionsUrl} kind="subtitles" srcLang="en" label="English" />
Your browser does not support the video tag.
</video>
)
}

通过遵循这种方法,你可以有效地自行托管视频并将其集成到你的 Next.js 应用中。

¥By following this approach, you can effectively self-host and integrate videos into your Next.js applications.

资源

¥Resources

要继续了解有关视频优化和最佳实践的更多信息,请参阅以下资源:

¥To continue learning more about video optimization and best practices, please refer to the following resources:

  • 了解视频格式和编解码器:根据你的视频需求选择正确的格式和编解码器,例如用于兼容性的 MP4 或用于网络优化的 WebM。详细信息请参见 Mozilla 的视频编解码器指南

    ¥Understanding video formats and codecs: Choose the right format and codec, like MP4 for compatibility or WebM for web optimization, for your video needs. For more details, see Mozilla's guide on video codecs.

  • 视频压缩:使用 FFmpeg 等工具有效压缩视频,平衡质量与文件大小。在 FFmpeg 的官方网站 了解压缩技术。

    ¥Video compression: Use tools like FFmpeg to effectively compress videos, balancing quality with file size. Learn about compression techniques at FFmpeg's official website.

  • 解析和码率调整:根据观看平台调整 解析和比特率,移动设备设置较低。

    ¥Resolution and bitrate adjustment: Adjust resolution and bitrate based on the viewing platform, with lower settings for mobile devices.

  • 内容交付网络 (CDN):利用 CDN 提高视频传输速度并管理高流量。使用某些存储解决方案(例如 Vercel Blob)时,系统会自动为你处理 CDN 功能。了解更多 关于 CDN 及其优势。

    ¥Content Delivery Networks (CDNs): Utilize a CDN to enhance video delivery speed and manage high traffic. When using some storage solutions, such as Vercel Blob, CDN functionality is automatically handled for you. Learn more about CDNs and their benefits.

探索这些视频流平台,将视频集成到你的 Next.js 项目中:

¥Explore these video streaming platforms for integrating video into your Next.js projects:

开源 next-video 组件

¥Open source next-video component

  • 为 Next.js 提供 <Video> 组件,兼容各种托管服务,包括 维塞尔斑点、S3、Backblaze 和 Mux。

    ¥Provides a <Video> component for Next.js, compatible with various hosting services including Vercel Blob, S3, Backblaze, and Mux.

  • 详细文档 用于将 next-video.dev 与不同的托管服务结合使用。

    ¥Detailed documentation for using next-video.dev with different hosting services.

云集成

¥Cloudinary Integration

多路复用视频 API

¥Mux Video API

快速

¥Fastly

  • 了解有关将 Fastly 的 视频点播 和流式解决方案集成到 Next.js 的更多信息。

    ¥Learn more about integrating Fastly's solutions for video on demand and streaming media into Next.js.