2026年12月2日 星期三

全景照片一鍵變 4K 漫遊短片:Mac mini M4 外接環境建置、Python + FFmpeg + edge-tts 軟硬字幕實戰

成都行回來,用 Affinity Photo 1.10 把在秦堰樓拍的多行都江堰照片拼成一張 21222 × 7463 px(1.58 億畫素) 的大圖(可參閱前文:Luke 的休閒筆記: 50mm 定焦拍一兩百張怎麼接?Mac mini M4 + Python 自動篩圖 + Affinity Photo 巨幅全景接圖完全攻略)。如下圖(不過 Blog 不支援這麼寬,所以輸出為 6000X2019, 還不曉得 Blogger 會不會再次縮圖?)



原本想做一支約 30 秒的 4K 漫遊短片(從左上角俯瞰帶入中段安瀾索橋與魚嘴,再水平橫移到最右側上游岷江,配上旁白、古風配樂與字幕),卻同時遇到兩個現實問題:

  1. 內接 256GB SSD 空間吃緊:AP 1.10 無法指定外接暫存碟,拼接巨圖時系統 Swap 與暫存全往開機碟寫;未來若再安裝各種 Python 影音與 AI 工具,內接空間很快見底。
  2. 工具選擇兩難:為了一支單純的平移短片打開 Final Cut Pro 略嫌殺雞用牛刀;若丟給生成式影片 AI,辛苦拍出的高畫素江面與古蹟細節又會被重繪失真。

最後的解法走純粹的減法路線:將 Python 虛擬環境與快取全數建在外接 Thunderbolt 4 SSD,用一支可重複使用的 Python 腳本串接 Pillow、FFmpeg 與免費的 edge-tts。以後每趟旅遊只要換圖、改文字稿、放進配樂,敲一行指令,30 秒左右就能自動生成 4K MP4,並同時支援 QuickTime 可開關的「軟字幕」與直接燒錄進畫面的「硬字幕」。

底下附上成品為直接燒錄進畫面的「硬字幕」並上傳 YouTube :


一、環境建置:把 Python 與快取全放外接 SSD(零佔用內接碟)

重要避坑筆記:Python 虛擬環境(venv)建立時會將當時的絕對路徑寫死在執行檔內。切勿先建在桌面或內接碟再直接拖移到外接硬碟,搬移後會因找不到路徑而報錯失效,務必直接在外接 SSD 的目標路徑內原地建立。

以下以 Mac mini M4 搭配外接 SSD(掛載名稱 /Volumes/Gloway2T)為例:

  1. 建立外接 SSD 專用目錄(打開終端機貼上執行):

    Bash

    mkdir -p /Volumes/Gloway2T/AI_Tools/{venvs,cache/pip,cache/huggingface,cache/torch,cache/whisper}
    mkdir -p /Volumes/Gloway2T/Pano_Video
    
  2. 將 Python / AI 套件預設快取導向外接 SSD(避免日後套件越裝越大吃掉內接空間):

    Bash

    cat << 'EOF' >> ~/.zshrc
    export PIP_CACHE_DIR="/Volumes/Gloway2T/AI_Tools/cache/pip"
    export HF_HOME="/Volumes/Gloway2T/AI_Tools/cache/huggingface"
    export TORCH_HOME="/Volumes/Gloway2T/AI_Tools/cache/torch"
    export XDG_CACHE_HOME="/Volumes/Gloway2T/AI_Tools/cache"
    EOF
    source ~/.zshrc
    
  3. 確認系統已安裝 ffmpeg(若無輸出則以 Homebrew 安裝):

    Bash

    which ffmpeg || brew install ffmpeg
    
  4. 在外接 SSD 原地建立影音虛擬環境並安裝套件:

    Bash

    python3 -m venv /Volumes/Gloway2T/AI_Tools/venvs/media_env
    source /Volumes/Gloway2T/AI_Tools/venvs/media_env/bin/activate
    pip install -U edge-tts pillow
    
  5. 驗證安裝路徑:

    Bash

    which edge-tts
    

    輸出為 /Volumes/Gloway2T/AI_Tools/venvs/media_env/bin/edge-tts 即表示完整落在外接 SSD 內。

二、全景圖最佳匯出規格與運鏡構圖規劃

為什麼不直接餵 1.58 億畫素原圖?

這張都江堰全景原圖由 Nikon Zf 搭配 AstrHori 50mm F2 拍攝,尺寸達 21222 × 7463 px(RGBA/16)。直接餵給 Python 逐格做超過 2 倍的大幅度縮圖,不但算圖慢,下方茂密樹林與水波在慢速橫移時更容易產生高頻閃爍(Aliasing / Shimmering)。

實測最佳輸出規格:將高度統一縮為 4000 px(此圖等比例寬度為 11375 px):

  • 守住真 4K 底線:4K 影片高度為 2160 px,即使取景框縮到原圖高度的 0.65~0.75,裁切高度仍有 2600~3000 px,保留超採樣畫質且絕不數位放大。
  • 畫面更純淨、算圖快 2.5 倍:在 AP 1.10 先一次性縮圖並轉為 8-bit JPG,M4 算 30 秒 4K 影片可壓在 30 秒前後完成。

AP 1.10 匯出設定

  1. 檔案(File) → 輸出(Export) → 格式選 JPEG(自動由 16-bit 轉為腳本所需的 8-bit sRGB)。
  2. 鎖定長寬比,高度輸入 4000(寬度自動算出 11375)。
  3. 重新取樣(Resample)選 Bicubic 或 Lanczos 3 (separable)(避開 non-separable,以免銳化光暈在橫移時閃爍)。
  4. 品質設 92%~95%,存為 /Volumes/Gloway2T/Pano_Video/pano.jpg。

依標尺微調運鏡視角

對照 AP 1.10 標尺:中央主山峰頂端約在 Y = 650、魚嘴分水堤在 Y = 4000~4800、安瀾索橋縱跨 Y = 4500~6500,而右下角前景有深色屋瓦入鏡(Y = 6400~7463)。因此將腳本參數設定為:

  • ZOOM_HEIGHT_RATIO = 0.75:兼顧遠山氣勢與江面細節,水平橫移距離仍超過 1.1 倍畫面寬度。
  • Y_MID_END = 0.35:完整留住中央山頭與安瀾索橋,同時自然裁掉右下角前景屋瓦。

三、素材準備與 edge-tts 實戰避坑

在 /Volumes/Gloway2T/Pano_Video/ 資料夾內準備三個檔案:

  1. pano.jpg:上一步匯出的 8-bit 全景圖。

  2. bgm.mp3(亦自動支援 bgm.wav / bgm.m4a):任一首長度大於 30 秒的古風純音樂,不需先剪輯,腳本會自動裁切 30 秒並加上前後淡入淡出。

  3. narration.txt:30 秒旁白文字檔(約 100 字,配合開場 1.2 秒前奏與結尾淡出剛好滿 30 秒):

    Bash

    cat << 'EOF' > /Volumes/Gloway2T/Pano_Video/narration.txt
    從秦堰樓俯瞰都江堰,這座歷經兩千多年仍運作不息的水利奇蹟,在眼前壯闊展開。
    橫跨江面的安瀾索橋旁,魚嘴分水堤順應地勢,巧分內外兩江,自動調節水量,防洪又排沙。
    順流遠望,岷江奔騰而出,穿越層層群山,至今依然生生不息地滋養著天府之國。
    EOF
    

實測避坑:edge-tts 偶發 1006 斷線排查

edge-tts 呼叫的是微軟公開語音端點,偶爾會遇到特定語音節點異常,報出 ConnectionClosedBeforeAudio (close code 1006)(實測台灣男聲 zh-TW-YunJheNeural 當時節點斷線,但台灣女聲 zh-TW-HsiaoChenNeural 秒過)。

遇到斷線時,可用終端機單測語音並以 macOS 內建 afplay 直接試聽音色:

Bash

edge-tts --voice zh-TW-HsiaoChenNeural --text "從秦堰樓俯瞰都江堰,測試語音是否正常。" --write-media /tmp/test_f.mp3 && afplay /tmp/test_f.mp3

確認好喜歡的語音後,直接設為腳本中的第一順位即可。

四、一鍵生成 4K 全景影片腳本(make_pano_video.py)

本腳本整合以下功能:

  • 抗抖動平滑運鏡:以 Pillow 亞像素雙三次插值(Sub-pixel Bicubic)搭配 smootherstep/smoothstep 曲線逐格送入 FFmpeg,消除整數裁切造成的慢速微抖動。
  • 防斷線與語音快取:內建重試與備援語音切換;只要 narration.txt 未更動,日後微調運鏡、音量或切換字幕模式時直接沿用快取,不再重複呼叫微軟端點。
  • 自備旁白接管:若資料夾內放入自己錄製的 voice.mp3 / voice.m4a / voice.wav,自動跳過 edge-tts。
  • 自動時間軸與軟/硬雙字幕:擷取語音時間標記自動斷句產出 output_4k.srt,支援 "soft"(內嵌 mov_text 軟字幕)、"hard"(macOS 繁中字體黑邊燒錄)與 "none" 三種模式。

在終端機貼上以下指令寫入腳本:

Bash

cat << 'EOF' > /Volumes/Gloway2T/Pano_Video/make_pano_video.py
import asyncio
import hashlib
import json
import math
import re
import subprocess
import sys
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont, ImageOps
import edge_tts

# ================= 可調整參數區 =================
WORK_DIR = Path("/Volumes/Gloway2T/Pano_Video")
IMAGE_FILE = WORK_DIR / "pano.jpg"          # 全景圖(建議 11375x4000 8-bit JPG)
TEXT_FILE = WORK_DIR / "narration.txt"      # 旁白文字檔
MANUAL_VOICE_CANDIDATES = ["voice.mp3", "voice.m4a", "voice.wav"]
BGM_CANDIDATES = ["bgm.mp3", "bgm.wav", "bgm.m4a"]
OUTPUT_FILE = WORK_DIR / "output_4k.mp4"    # 輸出影片
SRT_FILE = WORK_DIR / "output_4k.srt"       # 同步輸出的字幕檔

OUT_W, OUT_H = 3840, 2160   # 4K;想快速試跑可先改 1920, 1080
FPS = 30                    # 30fps
TARGET_DURATION = 30.0      # 目標秒數

ZOOM_HEIGHT_RATIO = 0.75    # 取景框高度佔原圖高度比例
Y_START = 0.0               # 起點垂直位置:0.0=最上緣
Y_MID_END = 0.35            # 中後段垂直位置:保留主山峰與安瀾索橋、避開右下屋瓦
DOWN_FINISH_RATIO = 0.38    # 前 38% 時間降至目標高度,後 62% 純水平橫移

# 字幕模式:"soft"(QT 可開關軟字幕)、"hard"(直接燒錄進畫面)、"none"(僅產出 .srt 不入片)
SUBTITLE_MODE = "soft"

VOICE_FALLBACKS = [
    "zh-TW-HsiaoChenNeural", # 台灣女聲(曉臻)
    "zh-TW-HsiaoYuNeural",   # 台灣女聲(曉雨)
    "zh-CN-YunjianNeural",   # 沉穩男聲備援
]
VOICE_RATE = "+0%"          # 語速微調,如 "-5%" 變慢
VOICE_DELAY_SEC = 1.2       # 開場幾秒後開始旁白
BGM_VOLUME = 0.18           # 配樂音量(0.12~0.25 依音樂響度調整)
# ================================================


def smoothstep(t: float) -> float:
    t = max(0.0, min(1.0, t))
    return t * t * (3.0 - 2.0 * t)


def smootherstep(t: float) -> float:
    t = max(0.0, min(1.0, t))
    return t * t * t * (t * (t * 6.0 - 15.0) + 10.0)


def strip_punct(s: str) -> str:
    return re.sub(r"[\s,。!?;、:,.\-!?\"'「」『』()()]+", "", s)


def split_display_clauses(text: str) -> list[str]:
    clauses: list[str] = []
    sentences = [s.strip() for s in re.split(r"[。!?\n]+", text) if s.strip()]
    for sent in sentences:
        parts = [p.strip() for p in re.split(r"[,、;]+", sent) if p.strip()]
        merged: list[str] = []
        i = 0
        while i < len(parts):
            cur = parts[i]
            if len(strip_punct(cur)) < 6:
                if i + 1 < len(parts) and not merged:
                    parts[i + 1] = f"{cur},{parts[i + 1]}"
                elif merged:
                    merged[-1] = f"{merged[-1]},{cur}"
                else:
                    merged.append(cur)
            else:
                merged.append(cur)
            i += 1
        clauses.extend(merged)
    return clauses


def fmt_srt_time(sec: float) -> str:
    ms = int(round(max(0.0, sec) * 1000))
    h, ms = divmod(ms, 3_600_000)
    m, ms = divmod(ms, 60_000)
    s, ms = divmod(ms, 1000)
    return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"


def build_subtitles(
    text: str,
    events: list[dict],
    voice_dur: float,
    delay_sec: float,
    video_dur: float,
) -> list[tuple[float, float, str]]:
    clauses = split_display_clauses(text)
    if not clauses:
        return []

    lens = [max(1, len(strip_punct(c))) for c in clauses]
    total_chars = sum(lens)

    char_times: list[tuple[float, float]] = []
    for ev in events:
        s = strip_punct(ev.get("text", ""))
        if not s:
            continue
        t0 = ev["offset"] / 10_000_000.0
        t1 = (ev["offset"] + ev["duration"]) / 10_000_000.0
        if t1 <= t0:
            t1 = t0 + 0.05
        n = len(s)
        dt = (t1 - t0) / n
        for k in range(n):
            char_times.append((t0 + k * dt, t0 + (k + 1) * dt))

    raw_subs: list[list] = []
    if char_times:
        scale = len(char_times) / max(1, total_chars)
        pos = 0
        for c, n in zip(clauses, lens):
            i0 = min(len(char_times) - 1, int(round(pos * scale)))
            i1 = min(len(char_times) - 1, max(i0, int(round((pos + n) * scale)) - 1))
            raw_subs.append([char_times[i0][0], char_times[i1][1], c])
            pos += n
    else:
        pos = 0
        for c, n in zip(clauses, lens):
            t0 = (pos / max(1, total_chars)) * voice_dur
            t1 = ((pos + n) / max(1, total_chars)) * voice_dur
            raw_subs.append([t0, t1, c])
            pos += n

    result: list[tuple[float, float, str]] = []
    for t0, t1, c in raw_subs:
        start = max(0.0, t0 + delay_sec)
        end = min(video_dur - 0.1, t1 + delay_sec)
        if result and start < result[-1][1]:
            start = result[-1][1]
        if end <= start + 0.25:
            end = min(video_dur - 0.05, start + 0.6)
        result.append((start, end, c))
    return result


def write_srt(subs: list[tuple[float, float, str]], path: Path):
    lines = []
    for idx, (t0, t1, c) in enumerate(subs, start=1):
        lines.append(f"{idx}\n{fmt_srt_time(t0)} --> {fmt_srt_time(t1)}\n{c}\n")
    path.write_text("\n".join(lines), encoding="utf-8")


async def generate_tts_with_timing(text: str, out_mp3: Path, out_json: Path) -> tuple[str, list[dict]]:
    last_err = None
    clean_text = "".join(line.strip() for line in text.splitlines() if line.strip())
    for voice in VOICE_FALLBACKS:
        for attempt in range(1, 4):
            events: list[dict] = []
            try:
                print(f"      嘗試語音 {voice}(第 {attempt}/3 次)...")
                communicate = edge_tts.Communicate(clean_text, voice, rate=VOICE_RATE)
                with open(out_mp3, "wb") as f:
                    async for chunk in communicate.stream():
                        ctype = chunk.get("type")
                        if ctype == "audio":
                            f.write(chunk["data"])
                        elif ctype in ("WordBoundary", "SentenceBoundary"):
                            events.append({
                                "offset": chunk["offset"],
                                "duration": chunk["duration"],
                                "text": chunk["text"],
                            })
                if out_mp3.exists() and out_mp3.stat().st_size > 1000:
                    out_json.write_text(json.dumps(events, ensure_ascii=False), encoding="utf-8")
                    return voice, events
            except Exception as e:
                last_err = e
                if out_mp3.exists():
                    out_mp3.unlink()
                print(f"      連線異常({type(e).__name__}),2 秒後重試...")
                await asyncio.sleep(2)
    raise RuntimeError(f"edge-tts 所有備援語音均失敗(最後錯誤:{last_err})。")


def get_audio_duration(path: Path) -> float:
    cmd = [
        "ffprobe", "-v", "error",
        "-show_entries", "format=duration",
        "-of", "default=noprint_wrappers=1:nokey=1",
        str(path),
    ]
    res = subprocess.run(cmd, capture_output=True, text=True, check=True)
    return float(res.stdout.strip())


def find_first_existing(candidates: list[str]) -> Path | None:
    for name in candidates:
        p = WORK_DIR / name
        if p.exists():
            return p
    return None


def load_cjk_font(size: int) -> ImageFont.FreeTypeFont:
    candidates = [
        Path("/System/Library/Fonts/PingFang.ttc"),
        Path("/System/Library/Fonts/STHeiti Medium.ttc"),
        Path("/System/Library/Fonts/Supplemental/Songti.ttc"),
        Path("/System/Library/Fonts/Hiragino Sans GB.ttc"),
    ]
    assets = Path("/System/Library/AssetsV2")
    if assets.exists():
        for p in assets.glob("com_apple_MobileAsset_Font*/*/AssetData/PingFang.ttc"):
            candidates.insert(0, p)
    for path in candidates:
        if path.exists():
            try:
                return ImageFont.truetype(str(path), size=size, index=0)
            except Exception:
                continue
    sys.exit("找不到可用的 macOS 中文字體,無法燒錄硬字幕。")


def draw_hard_subtitle(frame: Image.Image, text: str, font: ImageFont.FreeTypeFont):
    draw = ImageDraw.Draw(frame)
    stroke_w = max(2, frame.height // 450)
    bbox = draw.textbbox((0, 0), text, font=font, stroke_width=stroke_w)
    tw = bbox[2] - bbox[0]
    th = bbox[3] - bbox[1]
    x = (frame.width - tw) // 2
    y = frame.height - th - int(frame.height * 0.065)
    draw.text(
        (x, y),
        text,
        font=font,
        fill=(255, 255, 255),
        stroke_width=stroke_w,
        stroke_fill=(0, 0, 0),
    )


def main():
    if not IMAGE_FILE.exists():
        sys.exit(f"找不到全景圖:{IMAGE_FILE}")

    text = TEXT_FILE.read_text(encoding="utf-8").strip() if TEXT_FILE.exists() else ""
    manual_voice = find_first_existing(MANUAL_VOICE_CANDIDATES)
    events: list[dict] = []

    if manual_voice:
        print(f"[1/3] 偵測到自備旁白檔:{manual_voice.name}(跳過 edge-tts)")
        voice_file = manual_voice
    else:
        if not text:
            sys.exit(f"找不到旁白檔或內容為空:{TEXT_FILE}")

        cache_sig = hashlib.md5(f"{VOICE_FALLBACKS[0]}|{VOICE_RATE}|{text}".encode("utf-8")).hexdigest()[:10]
        voice_file = WORK_DIR / f"_voice_cache_{cache_sig}.mp3"
        timing_file = WORK_DIR / f"_voice_cache_{cache_sig}.json"

        if voice_file.exists() and voice_file.stat().st_size > 1000 and timing_file.exists():
            print(f"[1/3] 沿用既有的旁白與時間軸快取:{voice_file.name}")
            events = json.loads(timing_file.read_text(encoding="utf-8"))
        else:
            print("[1/3] 正在透過 edge-tts 生成旁白並擷取字幕時間軸...")
            try:
                used_voice, events = asyncio.run(generate_tts_with_timing(text, voice_file, timing_file))
                print(f"      生成成功,使用語音:{used_voice}(取得 {len(events)} 筆時間標記)")
            except RuntimeError as e:
                sys.exit(str(e))

    voice_dur = get_audio_duration(voice_file)
    print(f"      旁白長度:{voice_dur:.2f} 秒")

    min_needed = VOICE_DELAY_SEC + voice_dur + 1.5
    duration = max(TARGET_DURATION, math.ceil(min_needed * 10) / 10)
    if duration > TARGET_DURATION:
        print(f"      旁白較長,影片自動延長為 {duration:.1f} 秒以避免結尾截斷。")

    subs = build_subtitles(text, events, voice_dur, VOICE_DELAY_SEC, duration) if text else []
    if subs:
        write_srt(subs, SRT_FILE)
        print(f"      已產出字幕檔:{SRT_FILE.name}(共 {len(subs)} 句,模式:{SUBTITLE_MODE})")

    print(f"[2/3] 讀取全景圖:{IMAGE_FILE.name}")
    Image.MAX_IMAGE_PIXELS = None
    try:
        img = ImageOps.exif_transpose(Image.open(IMAGE_FILE)).convert("RGB")
    except Exception as e:
        sys.exit(f"圖片讀取失敗(請確認為 8-bit JPG/PNG):{e}")

    img_w, img_h = img.size
    target_aspect = OUT_W / OUT_H

    crop_h = img_h * ZOOM_HEIGHT_RATIO
    crop_w = crop_h * target_aspect
    if crop_w > img_w * 0.80:
        crop_w = img_w * 0.75
        crop_h = crop_w / target_aspect
    if crop_h > img_h:
        crop_h = float(img_h)
        crop_w = min(float(img_w), crop_h * target_aspect)

    max_x = max(0.0, img_w - crop_w)
    max_y = max(0.0, img_h - crop_h)
    total_frames = int(round(duration * FPS))
    print(f"      原圖尺寸:{img_w}x{img_h},取景框:{crop_w:.0f}x{crop_h:.0f},總格數:{total_frames}")

    delay_ms = int(VOICE_DELAY_SEC * 1000)
    fade_out_start = max(0.0, duration - 2.5)
    bgm_file = find_first_existing(BGM_CANDIDATES)

    cmd = [
        "ffmpeg", "-y",
        "-f", "rawvideo",
        "-vcodec", "rawvideo",
        "-pix_fmt", "rgb24",
        "-s", f"{OUT_W}x{OUT_H}",
        "-r", str(FPS),
        "-i", "-",
        "-i", str(voice_file),
    ]

    next_input_idx = 2
    if bgm_file:
        print(f"      偵測到背景音樂:{bgm_file.name}(自動裁切+淡入淡出混音)")
        cmd += ["-stream_loop", "-1", "-i", str(bgm_file)]
        filter_complex = (
            f"[1:a]adelay={delay_ms}:all=1,"
            f"aformat=sample_rates=44100:channel_layouts=stereo[v];"
            f"[2:a]atrim=0:{duration:.2f},asetpts=PTS-STARTPTS,"
            f"volume={BGM_VOLUME},"
            f"afade=t=in:st=0:d=1.5,"
            f"afade=t=out:st={fade_out_start:.2f}:d=2.5,"
            f"aformat=sample_rates=44100:channel_layouts=stereo[b];"
            f"[b][v]amix=inputs=2:duration=first:dropout_transition=2:normalize=0[aout]"
        )
        next_input_idx = 3
    else:
        print("      未偵測到 bgm.mp3 / bgm.wav / bgm.m4a,將僅輸出旁白音軌。")
        filter_complex = (
            f"[1:a]adelay={delay_ms}:all=1,"
            f"apad=whole_dur={duration:.2f},"
            f"aformat=sample_rates=44100:channel_layouts=stereo[aout]"
        )

    use_soft_sub = (SUBTITLE_MODE == "soft" and bool(subs) and SRT_FILE.exists())
    if use_soft_sub:
        cmd += ["-i", str(SRT_FILE)]
        sub_idx = next_input_idx

    cmd += [
        "-filter_complex", filter_complex,
        "-map", "0:v",
        "-map", "[aout]",
    ]
    if use_soft_sub:
        cmd += [
            "-map", f"{sub_idx}:0",
            "-c:s", "mov_text",
            "-metadata:s:s:0", "language=zho",
            "-metadata:s:s:0", "title=繁體中文",
            "-disposition:s:0", "default",
        ]

    cmd += [
        "-c:v", "libx264",
        "-crf", "18",
        "-preset", "fast",
        "-pix_fmt", "yuv420p",
        "-c:a", "aac",
        "-b:a", "192k",
        "-t", f"{duration:.2f}",
        "-movflags", "+faststart",
        str(OUTPUT_FILE),
    ]

    font = load_cjk_font(int(OUT_H * 0.042)) if (SUBTITLE_MODE == "hard" and subs) else None

    print(f"[3/3] 開始渲染 {OUT_W}x{OUT_H} @ {FPS}fps 影片...")
    proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE)

    try:
        for i in range(total_frames):
            u = i / max(1, total_frames - 1)
            x_norm = smootherstep(u)
            if u < DOWN_FINISH_RATIO:
                y_progress = smoothstep(u / DOWN_FINISH_RATIO)
                y_norm = Y_START + (Y_MID_END - Y_START) * y_progress
            else:
                y_norm = Y_MID_END

            x = min(max(0.0, x_norm * max_x), max_x)
            y = min(max(0.0, y_norm * max_y), max_y)
            x2 = min(float(img_w), x + crop_w)
            y2 = min(float(img_h), y + crop_h)

            frame = img.resize(
                (OUT_W, OUT_H),
                resample=Image.Resampling.BICUBIC,
                box=(x, y, x2, y2),
            )

            if font is not None:
                t_sec = i / FPS
                for s0, s1, stext in subs:
                    if s0 <= t_sec <= s1:
                        draw_hard_subtitle(frame, stext, font)
                        break

            proc.stdin.write(frame.tobytes())

            if (i + 1) % max(1, total_frames // 10) == 0 or i == total_frames - 1:
                pct = (i + 1) * 100 // total_frames
                print(f"      進度:{pct}% ({i + 1}/{total_frames})")
    finally:
        if proc.stdin:
            proc.stdin.close()

    stderr_out = proc.stderr.read().decode("utf-8", errors="ignore")
    ret = proc.wait()

    if ret != 0:
        sys.exit(f"FFmpeg 編碼失敗:\n{stderr_out[-1000:]}")

    print(f"\n完成!輸出檔案:{OUTPUT_FILE}")


if __name__ == "__main__":
    main()
EOF

五、執行、軟/硬字幕切換與日常微調速查

一鍵出片指令

Bash

source /Volumes/Gloway2T/AI_Tools/venvs/media_env/bin/activate
python /Volumes/Gloway2T/Pano_Video/make_pano_video.py
open /Volumes/Gloway2T/Pano_Video/output_4k.mp4

軟字幕 vs. 硬字幕如何選?

模式參數技術封裝方式適用場景限制
SUBTITLE_MODE = "soft"MP4 內嵌 mov_text 字幕軌本機典藏、QuickTime / IINA 觀看,需自由開關字幕傳到 LINE、WeChat 或部分手機/電視常不顯示
SUBTITLE_MODE = "hard"Pillow 直接以黑邊繁中字體繪製進影格分享到 LINE、YouTube、部落格或長輩手機觀看字幕固定於畫面,無法關閉

一鍵切換硬字幕並重跑(會沿用已快取的旁白與時間軸,不需重新連線 edge-tts):

Bash

sed -i '' 's/SUBTITLE_MODE = "soft"/SUBTITLE_MODE = "hard"/' /Volumes/Gloway2T/Pano_Video/make_pano_video.py
python /Volumes/Gloway2T/Pano_Video/make_pano_video.py

日後重複使用的微調參數速查

調整需求修改參數建議數值
快速預覽運鏡與節奏OUT_W, OUT_H改 1920, 1080(約 10 秒完成,確認後再改回 4K)
畫面太近或太遠ZOOM_HEIGHT_RATIO0.55(特寫感強)~ 0.80(大景寬廣)
調整橫移段視角高低Y_MID_END0.0(看天空山峰)~ 1.0(看前景河道)
風景解說語速偏快VOICE_RATE"-5%" 或 "-8%"(較有紀錄片沉穩感)
配樂蓋過人聲或太小聲BGM_VOLUME0.12(壓低配樂)~ 0.25(加強音樂氛圍)

沒有留言:

張貼留言

您可以留下意見,但 Luke 可能無法馬上回覆,尚請見諒。