Skip to content

Mux 和 Astro

Mux 是一个托管媒体服务,为各种规模的企业提供视频流媒体基础设施和性能分析。

¥Mux is a hosted media service that provides video streaming infrastructure and performance analytics for businesses of all scales.

当你使用 Mux 存储和托管视频内容时,你可以访问 Astro 原生视频组件 Mux 播放器(用于在 Astro 项目中添加 Mux 视频的即插即用组件)和 Mux 上传器(用于从你的网站上传视频到 Mux)。这些组件与 Mux Data 无缝集成,用于跟踪视频互动和效果。

¥When you use Mux to store and host your video content, you’ll have access to Astro-native video components for Mux Player, a drop-in component for adding Mux videos in your Astro project, and Mux Uploader for uploading videos to Mux from your website. These components integrate seamlessly with Mux Data to track your video engagement and performance.

你还可以通过 Mux 节点 SDK 与内容进行交互。

¥You can also interact with your content through the Mux Node SDK.

¥Using Mux in Astro

Mux 的 API 和 Web 组件与 Astro 配合使用,可压缩和优化你的视频和流媒体,使其更适合网络环境,并根据网络状况调整视频质量,以及集成字幕、缩略图和分析等附加功能。Mux 节点 SDK 同时支持 Mux Data 和 Mux Video API。

¥Mux’s APIs and web components work in Astro to compress and optimize your videos and streams for the web, adapt the quality of your video to network conditions, and integrate additional features like captions, thumbnails, and analytics. The Mux Node SDK supports both Mux Data and the Mux Video API.

¥Prerequisites

  • 一个现有的 Astro 项目。某些功能可能还需要安装 按需服务器渲染 适配器。

  • 一个 Mux 账户。如果你没有账户,可以使用代码 ASTRO 注册 注册 Mux 账户 以获得 50 美元的信用额度。

¥Mux Player

在 Astro 中,你可以将功能齐全的 Mux 播放器 用作原生 Astro 组件,以实现优化的响应式视频播放和直播。

¥In Astro, you can use the full-featured Mux Player as a native Astro component for optimized, responsive video playback and live streams.

Mux Player 提供基于视频播放器尺寸和流类型的响应式 UI、自动缩略图预览和海报图片,以及现代视频播放器功能(例如全屏、画中画、Chromecast、AirPlay)。

¥Mux Player provides a responsive UI based on video player dimensions and stream type, automatic thumbnail previews and poster images, and modern video player capabilities (e.g. fullscreen, picture-in-picture, Chromecast, AirPlay).

src/components/MyMuxVideoPlayer.astro
---
import { MuxPlayer } from "@mux/mux-player-astro";
---
<MuxPlayer
playbackId="DS00Spx1CV902MCtPj5WknGlR102V5HFkDe"
metadata={{ video_title: 'My Astro Video' }}
/>

Mux Player 内置对 Mux 数据分析的支持,一旦你的视频在已部署的网站上获得观看次数,它将在你的仪表板中自动显示访客互动和视频质量指标。

¥Mux Player has built-in support for Mux Data analytics, and will automatically show visitor engagement and video quality metrics in your dashboard once your video has views on your deployed site.

¥Installation

使用你首选的包管理器安装 Astro 版本的 Mux Player:

¥Install the Astro version of Mux Player using your preferred package manager:

终端窗口
npm install @mux/mux-player-astro

Mux Player 也可在你的 Astro 项目中用作:

¥Mux Player can also be used in your Astro project as:

  • 一个 Web 组件(来自 @mux/mux-player<mux-player>

  • 一个 React 组件(来自 @mux/mux-player-react<MuxPlayer />

  • 一个 HTML 网页嵌入(<iframe>

¥Play a video from Mux

你可以像使用其他 Astro 组件一样,直接在 .astro 文件中导入并使用原生 <MuxPlayer /> Astro 组件。

¥Import and use the native <MuxPlayer /> Astro component directly in your .astro files like any other Astro component.

你需要资源的 playbackId,可以在 Mux 控制面板或 从其 ASSET_ID 获取 中找到。

¥You will need the playbackId for your asset, which can be found in your Mux dashboard or retrieved from its ASSET_ID.

所有其他 控制 Mux Web 播放器的选项(例如,隐藏或显示控件、样式元素、禁用 Cookie)均为可选:

¥All other options to control the Mux web player (e.g. hide or display controls, style elements, disable cookies) are optional:

src/components/StarlightVideo.astro
<MuxPlayer
playbackId="FOTbeIxKeMPzyhrob722wytaTGI02Y3zbV00NeFQbTbK00"
metadata={{
video_title: 'Starlight by Astro',
}}
style={{
display: 'block',
aspectRatio: '16/9',
backgroundColor: '#000',
margin: '1rem 0 2rem',
}}
primaryColor="#f2ec3a"
secondaryColor="#0caa09"
accentColor="#6e1e99"
defaultShowRemainingTime={true}
/>

如果你的 playbackId 属于直播流而不是预录制的点播视频,则 Mux Player 将允许你通过启用或禁用 DVR 模式 等选项进一步自定义播放器。

¥If your playbackId belongs to a live stream instead of a prerecorded video on demand, then the Mux Player will allow you to further customize the player with options such as whether or not to enable DVR mode.

<MuxPlayer
playbackId="FOTbeIxKeMPzyhrob722wytaTGI02Y3zbV00NeFQbTbK00"
metadata={{
video_title: 'Starlight stream with Astro',
}}
streamType="live:dvr"
/>

所有直播流都会被录制并保存到 Mux 上,作为视频资源供日后点播播放。

¥Every live stream is recorded and saved on Mux as a video asset for future on-demand playback.

¥Mux video Element

Mux 视频元素 是 HTML5 <video> 元素的直接替代品,它为浏览器提供 HLS 播放支持,并自动配置 Mux 数据以显示访客和性能指标。当你不需要或不想要 Mux 播放器 的所有功能时,请使用此选项。

¥The Mux video element is a drop-in replacement for the HTML5 <video> element that provides browser support for HLS playback, and has Mux Data automatically configured to show visitor and performance metrics. Use this when you do not need or want all the features of Mux Player.

要使用 <mux-video> Web 组件,请先使用你首选的包管理器安装 mux-video

¥To use the <mux-video> web component, first install mux-video using your preferred package manager:

终端窗口
npm install @mux/mux-video

然后,你可以在 .astro 文件中的 <script> 标签中导入并渲染 Web 组件。

¥Then, you can import and render the web component in a <script> tag in your .astro file.

你需要视频资源的 playback-id,它可以在你的 Mux 控制面板或 从其 ASSET_ID 获取 中找到。

¥You will need the playback-id for your video asset, which can be found in your Mux dashboard or retrieved from its ASSET_ID.

HTML 5 <video> 元素的所有属性(例如 postercontrolsmuted)均可用,此外还提供 Mux 视频播放器控件(例如,用于提供元数据、控制分辨率、禁用 Cookie):

¥All attributes for the HTML 5 <video> element (e.g. poster, controls, muted) are available, as well as additional Mux video player controls (e.g. to provide metadata, control the resolution, disable cookies):

src/components/StarlightVideo.astro
<script>import '@mux/mux-video'</script>
<mux-video
playback-id="FOTbeIxKeMPzyhrob722wytaTGI02Y3zbV00NeFQbTbK00"
metadata-video-title="Starlight by Astro"
controls
disable-tracking
></mux-video>

¥Mux Node SDK

Mux 节点 SDK 提供从服务器端 TypeScript 或 JavaScript 对 Mux REST API 的身份验证访问。这允许你在 .astro 文件的组件脚本中与 Mux 资源和数据进行交互。

¥The Mux Node SDK provides authenticated access to the Mux REST API from server-side TypeScript or JavaScript. This allows you to interact with your Mux assets and data in the component script of your .astro files.

Mux Player 和 Mux Video 组件无需身份验证即可播放任何公开访问的视频(只要其 playbackId 为真),但通过 Node SDK 连接到你托管的 Mux 数据需要 Mux API 访问令牌

¥While the Mux Player and Mux Video components do not require authentication and can play any publicly accessible video given its playbackId, connecting to your hosted Mux data via the Node SDK requires a Mux API access token.

¥Installation

使用你首选的包管理器安装 Mux Node SDK:

¥Install the Mux Node SDK using your preferred package manager:

终端窗口
npm install @mux/mux-node

¥Mux Environment API access

API 令牌与特定的 Mux 环境绑定,该环境​​本质上是存放你的视频和相关数据的容器。注册 Mux 后,系统会自动为你创建一个环境。如果你创建了其他环境,请确保在生成令牌之前选择正确的环境。之后,你可以导出 获取你的 ID 和 SECRET 令牌 并将其提供给 Node SDK。这些令牌可以作为存储在 .env 文件中的环境变量传递给 Astro 组件。

¥API tokens are tied to a specific Mux Environment, which is essentially a container for your videos and related data. When you sign up for Mux, an Environment is created for you automatically. If you’ve created additional Environments, make sure you select the correct one before generating your tokens. From there, you can get your ID and SECRET tokens and provide them to the Node SDK. These tokens can be passed into your Astro components as environment variables stored in a .env file.

这将允许你创建 Mux Node SDK 实例,用于检索视频信息、创建新资源、访问指标和实时性能等:

¥This will allow you to create an instance of the Mux Node SDK for retrieving information about your videos, creating new assets, accessing metrics and real-time performance, and more:

src/components/StarlightVideo.astro
---
import Mux from "@mux/mux-node";
const mux = new Mux ({
tokenId: import.meta.env.MUX_TOKEN_ID,
tokenSecret: import.meta.env.MUX_TOKEN_SECRET,
})
---
Read more about using environment variables in your Astro project, including creating a type-safe schema for your Mux credentials.

¥Retrieve asset data

要获取要在 Astro 项目中使用的视频信息,请将视频的 ASSET_ID(可在 Mux 控制面板中找到)提供给 retrieve() 辅助函数。这将允许你将值传递给 Mux 组件和 HTML 模板,例如视频标题或时长:

¥To fetch information about your video to use in your Astro project, provide the video’s ASSET_ID (available in the Mux dashboard) to the retrieve() helper function. This will allow you to pass values to both your Mux components and your HTML template, such as the video’s title or duration:

---
import Mux from "@mux/mux-node";
import { MuxPlayer } from "@mux/mux-player-astro";
const mux = new Mux({
tokenId: import.meta.env.MUX_TOKEN_ID,
tokenSecret: import.meta.env.MUX_TOKEN_SECRET,
})
const ASSET_ID = "E01irAaN8c6dk1010153uC2mzst7RVbAdJJWtHECAHFvDo";
const asset = await mux.video.assets.retrieve(ASSET_ID);
const playbackId = asset.playback_ids?.find((id)=> id.policy=== "public")?.id;
const videoTitle = asset?.meta?.title;
const createdAt = Number(asset?.created_at);
const duration = Number(asset?.duration)
const date = new Date(createdAt * 1000).toDateString()
const time = new Date(Math.round(duration) * 1000).toISOString().substring(14, 19)
---
<h1>My Video Page</h1>
<p>Title: {videoTitle}</p>
<p>Upload Date: {date}</p>
<p>Length: {time}</p>
<MuxPlayer
playbackId={playbackId}
metadata={{video_title: videoTitle}}
/>

查看 Mux Asset API 文档 中的所有资源属性。

¥See all asset properties in the Mux Asset API documentation.

¥Mux Uploader

Mux 上传器 是一个功能齐全、可定制的视频上传 UI,适用于你的 Astro 网站。Astro 原生 <MuxUpload /> 组件允许你在 Web 应用中构建视频上传功能。

¥Mux Uploader is a fully-functional, customizable video upload UI for your Astro website. The native Astro <MuxUpload /> component allows you to build video upload functionality into your web app.

Mux Uploader 支持手动选择文件和拖放上传文件,支持暂停和恢复上传等功能。

¥Mux Uploader supports both manual file selection and drag and drop for file uploads, optional pausing and resuming of uploads, and more.

¥Installation

使用你首选的包管理器安装 Astro 版本的 Mux Uploader:

¥Install the Astro version of Mux Uploader using your preferred package manager:

终端窗口
npm install @mux/mux-uploader-astro

¥Upload a video to Mux

上传视频前,请确保已配置好 Mux API 访问令牌。完成这些配置后,你可以使用 Mux Node SDK 中的 create() 函数开始新的视频上传:

¥Before uploading a video, make sure you have your Mux API access tokens configured. With those in place, you can use the create() function from the Mux Node SDK to start a new video upload:

---
import Layout from '../../layouts/Layout.astro';
import Mux from "@mux/mux-node";
import { MuxUploader } from "@mux/mux-uploader-astro";
const mux = new Mux({
tokenId: import.meta.env.MUX_TOKEN_ID,
tokenSecret: import.meta.env.MUX_TOKEN_SECRET
});
const upload = await mux.video.uploads.create({
new_asset_settings: {
playback_policy: ['public'],
video_quality: 'basic'
},
cors_origin: '*',
});
---
<Layout title="Upload a video to Mux">
<MuxUploader endpoint={upload.url} />
</Layout>

¥Customize the uploader

你可以使用额外的组件属性自定义 <MuxUploader /> 的功能和外观。除了设置元素样式外,你还可以控制诸如暂停下载或设置最大文件大小等选项。

¥You can customize the functionality and appearance of the <MuxUploader /> with additional component attributes. In addition to styling your element, this allows you to control options such as the ability to pause a download or set a maximum file size.

---
import { MuxUploader } from '@mux/mux-uploader-astro';
---
<MuxUploader
endpoint="https://my-authenticated-url/storage?your-url-params"
pausable
maxFileSize={1000000000}
chunkSize={8192}
style={{
'--progress-bar-fill-color': '#7e22ce',
'--button-background-color': '#f0f0f0',
}}
/>

有关更多选项,请参阅 Mux Uploader 自定义指南

¥See the Mux Uploader customization guide for more options.

¥Event handling for uploads

Mux Uploader 提供功能丰富的动态 UI,该 UI 会根据你媒体上传的当前状态而变化。上传器的行为会响应用户驱动事件(例如,选择文件、出错后重试)和状态驱动事件(例如,上传进行中、上传成功完成)。

¥Mux Uploader provides a feature-rich, dynamic UI that changes based on the current state of your media upload. The uploader’s behavior responds to both user-driven events (e.g. selecting a file, retrying after an error) and state-driven events (e.g. upload in-progress, upload successfully completed).

你可以使用 客户端脚本 在 Astro 组件中监听和处理这些事件。也提供 MuxUploaderElement 类型。

¥You can listen for these events and handle them in your Astro component with client-side scripts. A MuxUploaderElement type is also available.

---
import { MuxUploader } from '@mux/mux-uploader-astro';
---
<MuxUploader
id="my-uploader"
endpoint="https://my-authenticated-url/storage?your-url-params"
pausable
/>
<script>
import type { MuxUploaderElement } from '@mux/mux-uploader-astro';
const uploader = document.getElementById('my-uploader') as MuxUploaderElement;
uploader.addEventListener('uploadstart', (event) => {
console.log('Upload started!', event.detail);
});
uploader.addEventListener('success', (event) => {
console.log('Upload successful!', event.detail);
});
uploader.addEventListener('uploaderror', (event) => {
console.error('Upload error!', event.detail);
});
uploader.addEventListener('progress', (event) => {
console.log('Upload progress: ', event.detail);
});
</script>

¥Official Resources

有关完整的 API 和 Webhook 参考、使用指南以及其他主题(例如与 CMS 集成、构建自定义视频工作流等)的信息,请参阅:

¥For the full API and webhook reference, usage guides, and information about additional topics, such as integrating with a CMS, building custom video workflows, and more, please see:

更多托管媒体指南

Astro v5.16 中文网 - 粤ICP备13048890号