元素

Video

视频视图用平台自带的播放器播放视频文件或视频流:iOS 和 Mac Catalyst 上是 AVPlayer,Android 上是 MediaPlayer。播放通过属性控制(paused、muted、rate 等),因此播放器会像其他视图一样跟随你的状态。Rust 用 video(url) 创建,TSX 用从 nsh 导入的 <Video>。

el-video.tsx
el-video.tsx运行中
import { mount, signal, Text, Video, View, type YNode } from "nsh";
import { windowSize } from "nsh/device";
import { 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}
      activeStyle={{ opacity: 0.6 }}
      style={{ ...(props.on ? ui().accentFill : ui().raised), paddingHorizontal: 14, paddingVertical: 9, borderRadius: 10 }}
    >
      <Text style={{ fontWeight: "600", color: props.on ? ui().onAccent : ui().text }}>{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!: YNode;

  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}
            resizeMode="contain"
            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::ui::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)
                .resize_mode(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() { "播放" } else { "暂停" })
                        .on_press(move || paused.update(|p| *p = !*p)),
                )
                .child(text("重新播放").on_press(move || player.seek(0.0)))
                .child(text(move || time.get())),
        )
}

在 TSX 中 src 必填(参见 Video API)。另见 Web view 与视频指南。

#属性

视频接受 view 的属性(它没有子元素),另外还有:

属性Rust类型默认值说明
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显示平台的播放控件。
resizeMode.resize_mode(ResizeMode::Contain)"cover" | "contain" | "stretch" | "center"视频如何适配其区域。
progressUpdateInterval.progress_interval(ms)number250onProgress 事件之间的毫秒数。

请通过样式给视频一个尺寸,它的尺寸由样式决定。如果需要视频本身的比例,可以用 onLoad 报告的尺寸设置宽高比。

#事件

事件Rust载荷时机
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 }(&str)加载或播放失败。
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 方法

方法Rust说明
seek(seconds)seek(seconds)跳转到某个时间点。

#能力声明

应用声明了能力时,视频源从 network 允许的主机加载;指向其他主机的视频源显示为空视图。

#平台说明

  • iOS 在 AVPlayerLayer 中绘制视频,设置 controls 时使用系统播放器视图;AVFoundation 在第一次创建视频时才加载。
  • Android 用 MediaPlayer 在 TextureView 上播放,controls 使用 MediaController。