1. 问题描述
最近在学习英语的时候发现视频只有音频资源,没有字幕,这时需要将音频资源转化为文本资源,方便后续温习的时候看资料。在网上找了很多工具,发现,要么是付费资源,要么就是无法转化,于是萌生了自己写脚本转化的念头。因此,在 AI 工具的加持下,实现此功能。
2. 代码
import os
import whisper
import subprocess
# Step 1: Define the YouTube video URL
youtube_url = "https://www.youtube.com/watch?v=Mr_L_owrCP8&list=PLTiMgEXm7hVbPxGFRiQY_HzkxwDsKssRh&index=1"
# Step 2: Download audio using yt-dlp
audio_filename = "video_audio.mp3"
command = [
"yt-dlp", "-x", "--audio-format", "mp3",
"-o", audio_filename, youtube_url
]
print("Downloading audio from YouTube...")
subprocess.run(command, check=True)
print("Download complete!")
# Step 3: Load Whisper model
print("Loading Whisper model...")
model = whisper.load_model("base") # You can change "base" to "small", "medium", or "large" for better accuracy
# Step 4: Transcribe audio
print("Transcribing audio...")
result = model.transcribe(audio_filename)
# Step 5: Save transcription to a file
transcription_file = "transcription.txt"
with open(transcription_file, "w", encoding="utf-8") as f:
f.write(result["text"])
print(f"Transcription complete! Check {transcription_file}")
此功能基本已经实现转化为文本资源,后续还可以优化,比如,将 txt 文件自动放到文件夹中,不过目前已经可以使用,此外,目的主要是学习英语,因此,暂时不做优化。