本頁由機器翻譯,可能有錯誤。 閱讀英文原文

元素

Video

video view 會使用平台的播放器來播放影片檔案或串流:在 iOS 和 Mac Catalyst 上使用 AVPlayer,在 Android 上使用 MediaPlayer。播放是透過 props(paused、muted、rate 等)來控制,因此播放器會像其他 view 一樣跟隨你的狀態。Rust 使用 video(url) 建立,TSX 則使用來自 nsh 的 <Video>。

el-video.tsx
el-video.tsxLive
import { mount, signal, Text, Video, type VideoRef, View } from "nsh";
import { windowSize } from "nsh";
import { button, buttonText, ui } from "./palette";

// A short CC0 clip from MDN's examples.
const FLOWER = "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4";

function Toggle(props: { label: string; on: boolean; onPress: () => void }) {
  return (
    <View
      onPress={props.onPress}
      {...button("secondary", { on: () => props.on, size: "sm" })}
    >
      <Text style={buttonText("secondary", { on: () => props.on })}>{props.label}</Text>
    </View>
  );
}

function App() {
  const paused = signal(true);
  const muted = signal(true);
  const repeat = signal(true);
  const controls = signal(false);
  const fast = signal(false);
  const time = signal(0);
  const duration = signal(0);
  const ratio = signal(16 / 9);
  const status = signal("loading");
  const ends = signal(0);
  let video!: VideoRef;

  const wide = () => windowSize().width >= 700;

  return (
    <View style={{ flex: 1, backgroundColor: ui().page, padding: 20, paddingTop: 24, gap: 14 }}>
      <Text style={{ fontSize: 22, fontWeight: "700", color: ui().text }}>video</Text>
      <View style={{ flex: 1, flexDirection: wide() ? "row" : "column", gap: 16 }}>
        <View style={{ flex: wide() ? 1 : undefined, justifyContent: "center" }}>
          <Video
            ref={video}
            src={FLOWER}
            paused={paused()}
            muted={muted()}
            repeat={repeat()}
            controls={controls()}
            rate={fast() ? 2 : 1}
            progressUpdateInterval={100}
            style={{ width: "100%", aspectRatio: ratio(), borderRadius: 14, overflow: "hidden", backgroundColor: "#000000" }}
            onLoadStart={() => status.set("onLoadStart")}
            onLoad={(e) => {
              duration.set(e.duration);
              ratio.set(e.size.width / e.size.height);
              status.set(`onLoad ${e.size.width} × ${e.size.height}`);
            }}
            onProgress={(e) => time.set(e.currentTime)}
            onBuffer={(e) => status.set(e.isBuffering ? "buffering" : "playing")}
            onEnd={() => ends.update((n) => n + 1)}
            onError={(e) => status.set(`onError ${e.message}`)}
          />
        </View>

        <View style={{ gap: 12, width: wide() ? 300 : undefined, justifyContent: "center" }}>
          <View style={{ ...ui().inset, height: 6, borderRadius: 3, overflow: "hidden" }}>
            <View style={{ height: 6, width: `${duration() ? (time() / duration()) * 100 : 0}%`, backgroundColor: ui().accent }} />
          </View>
          <Text style={{ color: ui().text, fontFamily: "monospace" }}>
            onProgress {time().toFixed(1)} / {duration().toFixed(1)} s
          </Text>
          <Text style={{ color: ui().muted, fontFamily: "monospace", fontSize: 13 }}>
            {status()} · onEnd {ends()}×
          </Text>
          <View style={{ flexDirection: "row", flexWrap: "wrap", gap: 8 }}>
            <Toggle label={paused() ? "Play" : "Pause"} on={!paused()} onPress={() => paused.set(!paused())} />
            <Toggle label="muted" on={muted()} onPress={() => muted.set(!muted())} />
            <Toggle label="repeat" on={repeat()} onPress={() => repeat.set(!repeat())} />
            <Toggle label="rate 2" on={fast()} onPress={() => fast.set(!fast())} />
            <Toggle label="controls" on={controls()} onPress={() => controls.set(!controls())} />
            <Toggle label="seek(0)" on={false} onPress={() => video.seek(0)} />
          </View>
        </View>
      </View>
    </View>
  );
}

mount(App);
use nsh_core::prelude::*;

fn player() -> impl IntoElement {
    let paused = signal(true);
    let time = signal(String::new());
    let player = element_ref();
    view()
        .gap_3()
        .child(
            video("https://example.com/clip.mp4")
                .element_ref(&player)
                .paused(paused)
                .repeat(true)
                .object_fit(ResizeMode::Contain)
                .h(px(220.0))
                .bg(black())
                .on_progress(move |p: &VideoProgress| {
                    time.set(format!("{:.1} / {:.1} s", p.current_time, p.duration))
                }),
        )
        .child(
            view()
                .flex_row()
                .gap_4()
                .child(
                    text(move || if paused.get() { "Play" } else { "Pause" })
                        .on_press(move || paused.update(|p| *p = !*p)),
                )
                .child(text("Restart").on_press(move || player.seek(0.0)))
                .child(text(move || time.get())),
        )
}

在 TSX 中,src 為必填(請參閱 Video API)。請參閱 web view and video guide。

#Props

video 具備 view 的 props(它沒有子元素),另外還有:

PropRust型別預設值說明
srcvideo(url)string影片的 URL(在 Rust 中也可使用資源的 uri:video(CLIP.uri))。
paused.paused(..)booleanfalse播放已暫停。
muted.muted(..)booleanfalse靜音。
volume.volume(..)number10..1。
rate.rate(..)number1播放速度。
repeat.repeat(..)booleanfalse播放到結尾時會從頭重新播放。
controls.controls(..)booleanfalse顯示平台的播放控制項。
objectFit(style)、object-* classes.object_fit(ResizeMode::Contain)"cover" | "contain" | "fill" | "none" | "scale-down""contain"影片如何填入其容器,與 CSS 的 object-fit 相同(class="object-cover")。iOS、macOS 和 Android 會將 "none" 和 "scale-down" 視為 "contain"播放,Linux 則將兩者都視為 "scale-down"。
progressUpdateInterval.progress_interval(ms)number250onProgress 事件之間相隔的毫秒數。

請透過樣式為影片指定大小;影片的大小就是其樣式所給定的大小。若想使用影片本身的比例,請依據 onLoad 回報的尺寸來設定長寬比。

#Events

事件RustPayload觸發時機
onLoadStart.on_load_start無開始載入。
onLoad.on_load{ duration, size }(VideoInfo:duration、size)影片已就緒:提供以秒為單位的長度與以像素為單位的尺寸。
onProgress.on_progress{ currentTime, duration }(VideoProgress:current_time、duration)播放期間每隔 progressUpdateInterval 觸發一次(單位為秒)。
onBuffer.on_buffer{ isBuffering }(bool)播放因等待資料而停滯/已恢復。
onEnd.on_end無播放已到達結尾(搭配 repeat 時,在每次循環結束時觸發)。
onError.on_error{ message, code? }(&str,即訊息)載入或播放失敗;若來源未被應用程式的 capabilities 授權,code 為 "ERR_ACCESS_DENIED"。
let ratio = signal(16.0_f32 / 9.0);

video(url)
    .w_full()
    .aspect_ratio(ratio)
    .on_load(move |info: &VideoInfo| {
        ratio.set(info.size.width.0 as f32 / info.size.height.0 as f32)
    })

#Ref methods

方法Rust說明
seek(seconds)seek(seconds)跳轉到指定時間。

#Capabilities

當應用程式宣告 capabilities 時,影片來源只會從 network 允許的主機載入;來自其他主機的來源會顯示空白的 view,並以 code "ERR_ACCESS_DENIED" 回報 onError。

#平台備註

  • iOS 會在 AVPlayerLayer 中繪製影片,若使用 controls,則使用系統播放器 view;AVFoundation 會在第一次建立影片時載入。
  • Android 在 TextureView 上使用 MediaPlayer 播放,並以 MediaController 提供 controls。