程式語言:Python
套件:yt-dlp 、Deep Translator
功能:這個功能主要的目的是當YT上有國外重要人士在YT上有直播訊而且有英文字幕時,在公司內希望除將YT直播畫面轉到電視頻道上播出,並請將原來的英文字幕將成中文,並且讓公司內部的字幕機去讀取轉換後的TXT檔案,顯示在電視頻道上某一特定區塊。
import yt_dlp
import requests
import time
from deep_translator import GoogleTranslator
def get_live_captions(youtube_url, lang="en"):
"""
透過 yt-dlp 擷取 YouTube 直播字幕的 URL
"""
ydl_opts = {
"writesubtitles": True,
"subtitleslangs": [lang],
"skip_download": True,
"quiet": True
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info_dict = ydl.extract_info(youtube_url, download=False)
subtitles = info_dict.get("subtitles", {}).get(lang, [])
if subtitles:
return subtitles[0]["url"]
return None
def fetch_subtitle_and_translate(subtitle_url, output_file):
"""
持續抓取 YouTube 直播字幕,翻譯成中文,並寫入 TXT 檔案
"""
previous_lines = set()
translator = GoogleTranslator(source="auto", target="zh-TW")
while True:
try:
response = requests.get(subtitle_url)
if response.status_code == 200 and response.text.strip():
text = response.text.split("\n")
new_lines = [line for line in text if line not in previous_lines and line.strip()]
for line in new_lines:
translated = translator.translate(line)
if translated is None:
translated = "[無法翻譯]"
with open(output_file, "a", encoding="utf-8") as f:
f.write(translated + "\n")
previous_lines.add(line)
print(f"翻譯完成: {translated}")
else:
print("⚠️ 無法擷取字幕或字幕為空,請確認直播有開啟字幕功能")
time.sleep(5) # 每 5 秒抓取一次字幕
except Exception as e:
print(f"❌ 發生錯誤: {e}")
time.sleep(10) # 若發生錯誤,稍後再試
if __name__ == "__main__":
youtube_live_url = "https://www.youtube.com/watch?v=你的直播ID" # 替換成你的 YouTube 直播網址
subtitle_url = get_live_captions(youtube_live_url, "en") # 取得英文字幕網址
if subtitle_url:
print(f"📌 字幕網址: {subtitle_url}")
fetch_subtitle_and_translate(subtitle_url, "translated_subtitles.txt") # 下載並翻譯字幕
else:
print("❌ 無法擷取字幕!請確認直播是否開啟字幕功能。")