本文へスキップ
レシピ番号132

レシピ集 · 第10章 · 出力と組み込み

画面とEPUBで動画が再生される実験シート

独自のMP4ファイルを使う2つの動画リソース。印刷では最初のフレームにQRコードを付けて組み、renderToHtmlとpostext-epubはファイルそのものを再生します。

このページの内容

1ページ(全2ページ)

  • 英語の見本:日本語版はまだありません
  • 仕上がり210 × 297 mm
  • 2段, 段間7 mm
  • Source Serif 4 9.4/13.2
  • Red Hat Display
  • Red Hat Mono
  • 2ページ
  • レベル
  • Postext 1.65.0
  • 組版時間144 ms
  • コード239行

かんたんな説明

振り子の短い動画が2本入った物理のワークシートです。紙ではどちらの動画も読み取り用のコードの付いた静止画になり、画面と電子書籍ではページの上で再生されます。

できあがり

『Bench Physics』の実験シート4.2です。16歳から18歳の生徒向けのA4判のワークブックで、テーマは振り子の周期です。赤錆色の帯に題名と、名前、グループ、日付の欄が載ります。1ページ目の地には、同じ振り子を10°と80°から放した2本の動画が左右に並びます。紙ではどちらの動画も最初のフレームで、再生マークとMP4を開くQRコードが付きます。ページの横にある画面版でも、サンプルが書き出すEPUBでも、同じ2つのリソースが読者の環境のプレーヤーで再生されます。2ページ目には方法、記入用の表、コードで計算した正確な周期、解答欄の付いた4つの問いが入ります。

このレシピが答える質問

  • HTML版とEPUBでは本の動画をどう再生しますか?ダウンロードボタンを隠すには?
  • 印刷した本に動画を入れ、読者がページから開けるようにするには?

手短な答え

script.js · 32〜61行コード全体で見る
const clip = (id, file, poster, caption, altText) => ({
  id, typeId: 'video', kind: 'video', createdAt: 0, updatedAt: 0, caption: t(caption),
  note: t({ en: '8.00 s, 25 frames per second · Postext Cookbook, CC BY 4.0',
    es: '8,00 s, 25 fotogramas por segundo · Postext Cookbook, CC BY 4.0' }),
  altText: t(altText), placement: { position: 'bottom', span: 'column' },
  video: { source: 'file', fileId: file, format: 'mp4', width: 640, height: 360, duration: 8,
    url: asset(file), // the production address: printed as the QR code, linked from the PDF
    poster: { fileId: poster, format: 'jpeg', width: 640, height: 360 }, // the first frame
  },
});
const videoStyle = {
  playMark: { shape: 'rounded', position: 'top-left', size: mm(7), inset: mm(3),
    background: col('ink'), color: col('paper') },
  qr: { position: 'bottom-right', size: mm(19), inset: mm(2.5), // 111 characters: 45 modules
    color: col('ink'), background: col('paper'), radius: mm(1) },
  // The HTML5 player of a file honours every option. download: false writes
  // controlslist="nodownload": it hides the button, and the file stays at its address.
  player: { download: false, loop: true, muted: true, preload: 'auto',
    pictureInPicture: false, remotePlayback: false },
};
const clips = [
  clip('small', 'pendulum-small.mp4', 'pendulum-small-poster.jpg',
    { en: 'Released from rest at 10°.', es: 'Soltado desde el reposo a 10°.' },
    { en: 'A rust bob on a dark string hangs a few degrees off the vertical, under a short bar.',
      es: 'Una lenteja roja cuelga de un hilo oscuro a pocos grados de la vertical.' }),
  clip('large', 'pendulum-large.mp4', 'pendulum-large-poster.jpg',
    { en: 'Released from rest at 80°.', es: 'Soltado desde el reposo a 80°.' },
    { en: 'The same pendulum pulled out almost level with its pivot, a pale arc below it.',
      es: 'El mismo péndulo, casi a la altura de su eje, sobre un arco pálido.' }),
];

材料

種類
Source Serif 4, Red Hat Display, Red Hat Mono (SIL OFL 1.1)
素材
  • pendulum-large-poster.jpg
  • pendulum-large.mp4
  • pendulum-small-poster.jpg
  • pendulum-small.mp4
  • Video 1: a pendulum 1 m long released from 10°, 8 s at 25 frames per second, rendered from an RK4 solution of the pendulum equation (1 ms steps) with Python and encoded with ffmpeg (Postext Cookbook, CC BY 4.0)
  • Video 2: the same pendulum released from 80°, rendered and encoded the same way (Postext Cookbook, CC BY 4.0)
  • The first frame of Video 1, its printed poster (Postext Cookbook, CC BY 4.0)
  • The first frame of Video 2, its printed poster (Postext Cookbook, CC BY 4.0)

作り方

#1 · 動画ごとに公開先のアドレスとファイルを与える

コードは前の手短な答えにあります。自前の動画には2つのアドレスがあります。video.urlは公開された本が動画を見つける場所で、QRコードはこれを刷り、PDFはポスター画像をこれにリンクします。ここでは動画のjsDelivrのアドレスで、スマートフォンで今すぐ開けるものです。video.fileIdはファイルそのものを指し、ファイルはビットマップと同じく本体とは別に保存されます。ファイルを同梱できる出力や、別の場所から再生できる出力がこれを使います(文書形式 › 動画を参照)。videoStyle.playerのプレーヤーオプションはすべての動画に適用されます。ループし、ミュートで始まり、全体を読み込み(27 KBと61 KB)、ダウンロード、ピクチャー・イン・ピクチャー、キャストは提供しないので、動画はシートの上にとどまります。

#2 · 同じソースから画面版をレイアウトする

script.js · 172〜180行コード全体で見る
const [PANE_W, PANE_H] = [400, 640]; // px
const screen = {
  page: { width: px(PANE_W), height: px(PANE_H), dpi: 122, // so the 9.4 pt text is 16 px
    margins: { top: px(28), bottom: px(28), left: px(22), right: px(22), mirror: false } },
  layout: { layoutType: 'single' }, bodyText: { textAlign: 'left' }, // ragged in a narrow pane
  headings: { levels: [{ level: 1, span: 'column', breakBefore: { enabled: false },
    fontSize: px(28), lineHeight: px(32), fontWeight: 800, marginBottom: px(16),
    advancedDesign: { enabled: false } }] }, // the title alone: the band and fields are print's
  header: { elements: [] }, footer: { elements: [] } };

画面版は設定のhtmlViewer.overridesにあり、canvasとPDFはこれを無視します。122 dpiでは、ポイントで指定したサイズはどれも96 dpiのときよりおよそ4分の1大きくなるので、9.4 ptの本文はペインで16 pxになり、キャプション、囲み、表もそれに合わせて大きくなります。冒頭は題名を残し、紙のための帯と記入欄は外します。

#3 · ペインで動画を再生する

script.js · 333〜340行コード全体で見る
// A shadow root keeps the page's styles out, so the pane shows the lines as they were measured.
const pane = desk.querySelector('#screen').attachShadow({ mode: 'open' });
pane.innerHTML = renderToHtml(buildDocument({ markdown, resources },
  applyHtmlViewerOverrides(config())), { mode: 'single', padding: 0, background: '#ffffff',
  resourceImageUrl: imageUrl, // the posters, until a clip plays
  resourceVideoUrl: (fileId) => asset(fileId) }); // the file each <video> plays: the asset here
const top = (el) => el.getBoundingClientRect().top; // open the pane on the first player
pane.host.scrollTop = top(pane.querySelector('video')) - top(pane.host) - 48;

renderToHtmlは各動画リソースをHTML5の<video>として組み、プレーヤーオプションを属性にします。controls、muted、loop、playsinline、preload="auto"、disablepictureinpicture、disableremoteplayback、controlslist="nodownload"です。最後のものはボタンを隠すだけです。アドレスを知っていれば誰でもファイルを保存できるので、保護ではなく体裁を整えるものと考えてください。resourceVideoUrlは、resourceImageUrlがポスター画像に対してするのと同じように、fileIdごとに再生可能なアドレスをバックエンドに渡します。ここでは公開済みのアセットです。アップロードしたファイルを別の場所に置くサイトなら、自分のURLか、バイト列のblob URLを返します。これがないとプレーヤーはvideo.urlを使い、どちらもなければペインはポスター画像を表示します。

#4 · 動画を固定レイアウトのEPUBに同梱する

script.js · 290〜310行コード全体で見る
const bytesOf = async (url) => new Uint8Array(await (await fetch(url)).arrayBuffer());
const media = new Map(await Promise.all(clips.map(async ({ video }) =>
  [video.fileId, { bytes: await bytesOf(asset(video.fileId)), mediaType: 'video/mp4' }])));
// Every face as bytes (gotcha: epub-embeds-given-fonts): the files loadFonts loaded, latin
// for each face and greek for the text face, limited to the Greek block and listed after
// latin, so a reading system tries it first for θ and π.
const faces = Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) =>
  ({ family, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' })));
const fonts = await Promise.all([...faces.map((face) => [face, 'latin']),
  ...faces.filter(({ family }) => family === TEXT)
    .map((face) => [{ ...face, unicodeRange: 'U+0370-03FF' }, 'greek'])]
  .map(async ([face, subset]) => ({ ...face, format: 'woff2', bytes: await bytesOf(
    `https://cdn.jsdelivr.net/npm/@fontsource/${fontsourceId(face.family)}@5/files/`
    + `${fontsourceId(face.family)}-${subset}-${face.weight}-${face.style}.woff2`) })));
const epub = await renderToEpub([doc], { layout: 'fixed', fonts,
  metadata: { title: doc.metadata.title, creators: ['Postext Cookbook'], language: LANG,
    rights: 'CC BY 4.0', modified: new Date('2026-10-05T00:00:00Z') }, // the same bytes each run
  // The clips as video/mp4 and the posters as pictures; the book packs both under media/.
  resourceBytes: (fileId) => media.get(fileId)
    ?? { bytes: imageBytes(fileId), mediaType: 'image/jpeg' },
});

このシートは、左右に並んだ2本の動画と書き込むための空欄を軸に組んであるので、固定レイアウトでその形を保ちます。どのページも印刷と同じで、ポスター画像のあった場所にプレーヤーが入ります。リフロー型のEPUBでも動画は再生されますが、テキストの幅で上下に並びます。resourceBytesは動画ごとにvideo/mp4を、ポスター画像ごとにJPEGを返し、ライターはそれらをmedia/とimages/の下に収めます。EPUBはスキーマにある属性(controls、autoplay、muted、loop、playsinline、preload)だけを残すので、ダウンロードボタンなどはリーディングシステムに任されます。ファイルはEPUBCheckをエラーも警告もなく通ります。

#5 · canvas、PDF、EPUBでθとπを組む

Source Serif 4のギリシャ文字は、Fontsourceではlatinとは別のgreekファイルに入っています。kitFonts(FONTS)は本文にギリシャ文字を見つけると、このファミリーの各書体についてそのファイルも読み込みます。fontsourceProviderは、θやπを組んだ書体ごとに、それをlatinファイルと並べてPDFに埋め込みます。そのため、この2文字のためのコードは要りません。EPUBはコードから渡された書体しか埋め込まないので、手順4で本文書体のgreekファイルをラテン文字のファイルの後に加え、それぞれのunicodeRangeでギリシャ文字のブロックに限っています。

#6 · 表をコードで計算する

script.js · 65〜86行コード全体で見る
// The arithmetic-geometric mean gives the elliptic integral K of the exact period in a few steps.
const T0 = 2 * Math.PI * Math.sqrt(1 / 9.81); // s: L = 1 m, g = 9.81 m/s²
const agm = (a, b) => (Math.abs(a - b) < 1e-15 ? a : agm((a + b) / 2, Math.sqrt(a * b)));
const period = (degrees) => T0 / agm(1, Math.cos((degrees * Math.PI) / 360));
const num = (x, digits) => x.toFixed(digits).replace('.', t({ en: '.', es: ',' }));
const cell = (content, align = 'right') => ({ content, align, verticalAlign: 'middle' });
const table = (id, caption, head, rows, columnWidths) => ({ id, typeId: 'table', kind: 'table',
  createdAt: 0, updatedAt: 0, caption: t(caption), placement: { position: 'here' },
  table: { model: { headerRowCount: 1, columnWidths, rows: [head.map((h, i) =>
    ({ ...cell(h, i ? 'right' : 'left'), isHeader: true })), ...rows] } } });
const periods = table('periods', { en: 'Exact periods of a pendulum 1.00 m long.',
  es: 'Periodos exactos de un péndulo de 1,00 m.' },
['Amplitude|Amplitud', 'T (s)', 'T/T~0~', 'Longer by|Aumento'].map((h) =>
  t({ en: h.split('|')[0], es: h.split('|').at(-1) })),
[5, 10, 20, 30, 45, 60, 80, 90].map((d) => [cell(`${d}°`, 'left'), cell(num(period(d), 3)),
  cell(num(period(d) / T0, 3)), cell(`${num((period(d) / T0 - 1) * 100, 2)} %`)]),
[1.2, 1, 1, 1.1]);
const blank = cell(' \n '); // two empty lines: room to write
const data = table('data', { en: 'Your measurements.', es: 'Tus medidas.' },
  t({ en: ['Clip', 'Swings in 8 s', 'T (s)'], es: ['Vídeo', 'Oscilaciones en 8 s', 'T (s)'] }),
  [10, 80].map((d, i) => [cell(`${t({ en: 'Video', es: 'Vídeo' })} ${i + 1} · ${d}°`, 'left'),
    blank, blank]), [1.2, 1.5, 0.8]);

正確な周期には第1種完全楕円積分Kが必要で、算術幾何平均を使えば数ステップで求まります。式はT = T~0~ / AGM(1, cos ½θ~0~)です。表は小数点以下3桁で、スペイン語版では小数点にコンマを使います。10°と80°の行は動画に一致し、2.010 sと2.282 sで、T~0~ = 2.006 sよりそれぞれ0.2%と13.8%長くなります。8秒の間に振れる回数は、1本目の動画では4往復にわずかに足りず、2本目では3往復半です。

レシピの全体

Sandbox
// ═══ Postext Cookbook · Nº 132 · A lab sheet whose clips play on screen and in the EPUB ════
// https://postext.dev/en/cookbook/pendulum-lab-video-players
// Code: MIT · Text: original (CC BY 4.0) · Clips: rendered in code (CC BY 4.0)
// Fonts: Source Serif 4, Red Hat Display, Red Hat Mono (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import {
  buildDocument, buildDocumentWithFonts, prepareFonts, renderPageToCanvas, renderToHtml,
  applyHtmlViewerOverrides, registerResourceImage, defaultResourceTypes, resourceVideoLink,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
import { renderToEpub, readEpub } from 'https://esm.sh/postext-epub';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'pendulum-lab-video-players';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { // the clips' own colours: a cream ground, the rust bob, warm black ink
  ink: '#22201b', // text, the play mark, the QR modules, table heads
  rust: '#a8432b', // the accent: the band, labels, list numbers (the bob's red, darker)
  cream: '#f6f1e4', rule: '#cbc2ae', // box fills, a shade deeper than the clips; hairlines
  muted: '#68625a', paper: '#ffffff' }; // muted: running heads, notes, prompts
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = Object.entries({ ...palette, 'main-color': palette.rust }) // defaults: rust
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const [TEXT, DISPLAY, MONO] = ['Source Serif 4', 'Red Hat Display', 'Red Hat Mono'];
const [TOP, INNER, OUTER, BAND, LEAD] = [22, 20, 17, 84, 13.2]; // mm, A4; LEAD in pt
const px = (value) => ({ value, unit: 'px' }); // the screen edition's sizes
const at = (to, edge, x, y, size) => ({ anchor: { to, edge }, offset: { x, y }, size });
const label = (size, color = 'rust') => ({ fontFamily: MONO, fontSize: pt(size), fontWeight: 600,
  letterSpacing: pt(size * 0.16), textTransform: 'uppercase', color: col(color) });

// #region answer: two clips of the book's own: a poster and a QR code, or a player
const clip = (id, file, poster, caption, altText) => ({
  id, typeId: 'video', kind: 'video', createdAt: 0, updatedAt: 0, caption: t(caption),
  note: t({ en: '8.00 s, 25 frames per second · Postext Cookbook, CC BY 4.0',
    es: '8,00 s, 25 fotogramas por segundo · Postext Cookbook, CC BY 4.0' }),
  altText: t(altText), placement: { position: 'bottom', span: 'column' },
  video: { source: 'file', fileId: file, format: 'mp4', width: 640, height: 360, duration: 8,
    url: asset(file), // the production address: printed as the QR code, linked from the PDF
    poster: { fileId: poster, format: 'jpeg', width: 640, height: 360 }, // the first frame
  },
});
const videoStyle = {
  playMark: { shape: 'rounded', position: 'top-left', size: mm(7), inset: mm(3),
    background: col('ink'), color: col('paper') },
  qr: { position: 'bottom-right', size: mm(19), inset: mm(2.5), // 111 characters: 45 modules
    color: col('ink'), background: col('paper'), radius: mm(1) },
  // The HTML5 player of a file honours every option. download: false writes
  // controlslist="nodownload": it hides the button, and the file stays at its address.

組み立てたscript.jsはそのまま動きます。任意のページのモジュールスクリプトに貼り付けるか、レシピをCodePenで開いてください。 GitHub上のレシピのフォルダー ↗ (新しいタブで開きます)

アレンジ

#1本の動画だけを自動で始める

動画自身のplayerはvideoStyle.playerの上に重ねられます。ブラウザーの要件どおり、自動再生は常にミュートで始まります。

 ];
+clips[0].video.player = { autoplay: true }; // the 10° clip starts as the pane opens

#印刷用のポスター画像を画面に表示する

html: 'poster'を指定すると、HTML版はプレーヤーの代わりに、再生マークとQRコードを載せ、公開先のアドレスにリンクしたポスター画像を組みます。

 const videoStyle = {
+  html: 'poster',

#YouTubeやVimeoの動画を使う

source: 'youtube'と動画のアドレスを指定すると、youtube-nocookie.comからYouTubeのプレーヤーを埋め込みます(privacyは初期設定でオンです)。このプレーヤーが従うオプションは少なく、コントロール、全画面表示、自動再生、ミュート、ループだけです。Vimeoのプレーヤーはこれに速度メニューとピクチャー・イン・ピクチャーが加わります。どちらもダウンロードは提供しません。EPUBにはWebページのプレーヤーを埋め込めないので、そこでは動画にリンクしたポスター画像になります。オプションとその対応範囲は設定 › 動画スタイルにまとめてあります。

よくあるつまずき

つまずき

renderToEpubは渡されたフォントしか埋め込まない

ブラウザーが読み込んだフォントは、postext-epubが読めるファイルではありません。ページが使うすべてのフォントのバイト列をoptions.fontsで渡してください(ページが読み込んだのと同じFontsourceのwoff2ファイル)。省いたフォントはmissingFontとして報告され、リーディングシステムはそのテキストを独自の書体で組みます。固定レイアウトでは、ページを組んだときの行に収まらなくなります。ライセンスが許すフォントだけを埋め込んでください。 EPUBの書き出し →

つまずき

Fontsourceのファイルは文字を収め、記号は収めない

キットは各書体のFontsourceのlatinファイルを埋め込み、本文にč、ł、†があればlatin-extファイルを、α、χがあればgreekファイル(それを持つファミリーのみ。LoraとGelasioにはない)を、画面でもPDFでも加えます。→、≈、✓、★などの記号はどのファイルにもなく、PDFでは欠けます。図として描くか、数式で書くか、それを収めたファイルを持つ書体を選んでください。 PDFに埋め込むフォント →

MP4はH.264です。Chrome、Edge、Safari、Firefoxはこれを再生でき、キャプチャーが使うChrome for Testingも再生できます。プロプライエタリなコーデックを含めずにコンパイルしたChromium(オープンソース版の初期設定)は再生できません。読者にとってそれが問題になるなら、動画をWebM(format: 'webm')でエンコードしてください。

クレジット

レシピ
Ignacio Ferro
本文
書き下ろしの文章, CC BY 4.0
画像
  • Video 1: a pendulum 1 m long released from 10°, 8 s at 25 frames per second, rendered from an RK4 solution of the pendulum equation (1 ms steps) with Python and encoded with ffmpeg · Postext Cookbook · CC BY 4.0
  • Video 2: the same pendulum released from 80°, rendered and encoded the same way · Postext Cookbook · CC BY 4.0
  • The first frame of Video 1, its printed poster · Postext Cookbook · CC BY 4.0
  • The first frame of Video 2, its printed poster · Postext Cookbook · CC BY 4.0
フォント
Source Serif 4 (SIL OFL 1.1) · Red Hat Display (SIL OFL 1.1) · Red Hat Mono (SIL OFL 1.1)
SandboxPDF