Skip to content

media.js ​

查看原文件

js
import { Info, Blocks } from '@kodet/content';

/**
 * 在 Content.catalog 的条目中设置 mediaUrl、load: playVideo。
 * 演示数据在本地生成;真实来源可在函数内按需请求、解析后逐条 yield。
 * @param {import('@kodet/content').CatalogContext} ctx
 */
export function playVideo(ctx) {
  if (typeof ctx.item.mediaUrl !== 'string') throw new Error('需要媒体地址');
  return Info.video({ url: ctx.item.mediaUrl, danmaku: { mode: 'full', load: loadDanmaku } });
}

/** @param {import('@kodet/content').DanmakuContext} ctx */
async function* loadDanmaku(ctx) {
  for (let i = 0; i < 100; i++) {
    if (ctx.signal.aborted) return;
    yield { id: String(i), timeMs: i * 1000, text: `弹幕 ${i + 1}` };
  }
}

/**
 * 在 Content.catalog 的条目中设置 imageUrl、load: readComic。
 * @param {import('@kodet/content').CatalogContext} ctx
 */
export function readComic(ctx) {
  if (typeof ctx.item.imageUrl !== 'string') throw new Error('需要图片地址');
  return Info.comic({ images: [{ id: 'source-page-1', load: () => String(ctx.item.imageUrl) }], comments: {
    chapterCount: 0,
    loadChapter: context => Blocks.create()
      .text(`本话:${context.chapter ?? '正文'}`)
      .text(`业务 ID:${String(context.item?.id ?? '')}`)
      .text('这里可组合任意支持的组件,也可以使用 WebView。'),
  } });
}

/**
 * 适用于有限文件、签名传输或来源内解密;普通 URL 保持 playVideo 即可。
 * mediaSize 来自可信媒体元数据;每次读取独立 signal,不能复用 ctx.signal。
 * @param {import('@kodet/content').CatalogContext} ctx
 */
export function playRandomAccessVideo(ctx) {
  const url = String(ctx.item.mediaUrl ?? ''), size = Number(ctx.item.mediaSize);
  if (!url || !Number.isSafeInteger(size) || size <= 0) throw new Error('需要媒体地址和完整字节数');
  return Info.video({ mimeType: 'video/mp4', stream: {
    size,
    async read({ offset, length, signal }) {
      const response = await fetch(url, { signal, headers: { Range: `bytes=${offset}-${offset + length - 1}` } });
      if (response.status !== 206) throw new Error('媒体服务必须支持 Range');
      return response.bytes();
    },
  } });
}