脚本怎样截取音频片段

wen 实用脚本 24

本文目录导读:

脚本怎样截取音频片段

  1. 使用 FFmpeg(最常用)
  2. Python + pydub
  3. Python + librosa
  4. 批处理脚本(多个文件)
  5. Python 批量处理
  6. 快速安装

使用 FFmpeg(最常用)

# 截取指定时间段(从30秒开始,截取10秒)
ffmpeg -i input.mp3 -ss 00:00:30 -t 00:00:10 output.mp3
# 或指定结束时间
ffmpeg -i input.mp3 -ss 00:00:30 -to 00:00:40 output.mp3
# 精确裁剪(先截取再编码,提高精度)
ffmpeg -ss 00:00:30 -t 00:00:10 -i input.mp3 -c copy output.mp3

Python + pydub

from pydub import AudioSegment
# 加载音频文件
audio = AudioSegment.from_file("input.mp3")
# 截取片段(毫秒为单位)
start_time = 30000  # 30秒
end_time = 40000    # 40秒
clip = audio[start_time:end_time]
# 导出
clip.export("output.mp3", format="mp3")

Python + librosa

import librosa
import soundfile as sf
# 加载音频
y, sr = librosa.load("input.mp3", sr=None)
# 截取片段
start_sample = int(30 * sr)  # 30秒
end_sample = int(40 * sr)    # 40秒
clip = y[start_sample:end_sample]
# 保存
sf.write("output.wav", clip, sr)

批处理脚本(多个文件)

Windows Batch:

@echo off
for %%f in (*.mp3) do (
    ffmpeg -i "%%f" -ss 00:01:00 -t 00:00:30 "clip_%%f"
)

Linux/Mac Shell:

for f in *.mp3; do
    ffmpeg -i "$f" -ss 00:01:00 -t 00:00:30 "clip_$f"
done

Python 批量处理

import os
from pydub import AudioSegment
def batch_trim(input_dir, output_dir, start_ms, end_ms):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    for file in os.listdir(input_dir):
        if file.endswith(('.mp3', '.wav', '.m4a')):
            audio = AudioSegment.from_file(os.path.join(input_dir, file))
            clip = audio[start_ms:end_ms]
            clip.export(os.path.join(output_dir, file), format=file.split('.')[-1])
# 使用示例
batch_trim("./input", "./output", 30000, 40000)

快速安装

# FFmpeg
# Ubuntu/Debian
sudo apt install ffmpeg
# Mac
brew install ffmpeg
# Python库
pip install pydub librosa soundfile

选择方法时考虑:FFmpeg 适合批量处理pydub 适合精确控制librosa 适合对音频质量要求高的场景。

抱歉,评论功能暂时关闭!