如何用脚本批量转换音频采样率?

wen 实用脚本 2

本文目录导读:

如何用脚本批量转换音频采样率?

  1. 使用 FFmpeg(最推荐)
  2. 使用 SoX
  3. 使用 Python (pydub)
  4. FFmpeg 高级选项
  5. 注意事项
  6. 安装依赖

可以使用多种脚本方法批量转换音频采样率,以下是几种常用方案:

使用 FFmpeg(最推荐)

Windows (PowerShell)

# 将当前目录下所有.wav文件转换为44100Hz
Get-ChildItem -Path "C:\audio" -Filter "*.wav" | ForEach-Object {
    $output = "C:\audio_converted\" + $_.BaseName + "_44100.wav"
    ffmpeg -i $_.FullName -ar 44100 $output
}

Linux/macOS (Bash)

#!/bin/bash
# 转换当前目录所有.mp3文件为48000Hz
for file in *.mp3; do
    ffmpeg -i "$file" -ar 48000 "converted_${file%.*}.wav"
done

递归处理子目录

#!/bin/bash
find ./audio -name "*.wav" -exec sh -c '
    for file do
        dir=$(dirname "$file")
        name=$(basename "$file" .wav)
        ffmpeg -i "$file" -ar 44100 "${dir}/${name}_44100.wav"
    done
' sh {} +

使用 SoX

批量转换

#!/bin/bash
for file in *.wav; do
    output="${file%.*}_44100.wav"
    sox "$file" -r 44100 "$output"
done

保持原文件名(覆盖原文件)

#!/bin/bash
for file in *.wav; do
    sox "$file" -r 44100 "$file" # 直接覆盖
done

使用 Python (pydub)

import os
from pydub import AudioSegment
input_dir = "./audio"
output_dir = "./converted"
target_sr = 44100
os.makedirs(output_dir, exist_ok=True)
for filename in os.listdir(input_dir):
    if filename.endswith(('.wav', '.mp3', '.flac')):
        filepath = os.path.join(input_dir, filename)
        audio = AudioSegment.from_file(filepath)
        audio = audio.set_frame_rate(target_sr)
        output_path = os.path.join(output_dir, filename)
        audio.export(output_path, format=filename.split('.')[-1])

FFmpeg 高级选项

保持原有格式和质量

#!/bin/bash
# 同时转换采样率并保持音频质量
for file in *.mp3; do
    ffmpeg -i "$file" -ar 44100 -sample_fmt s16 -acodec pcm_s16le "converted_${file%.*}.wav"
done

多线程处理

#!/bin/bash
# 使用GNU Parallel并行处理
parallel ffmpeg -i {} -ar 44100 converted_{.}.wav ::: *.wav

注意事项

  1. 备份原文件:建议先复制到新目录,避免误操作
  2. 格式兼容:某些格式可能不支持采样率转换
  3. 质量损失:先降采样再升采样会损失质量
  4. 文件大小:采样率降低会减小文件体积

安装依赖

  • FFmpeg官网下载
  • SoXapt install sox (Linux) 或 brew install sox (macOS)
  • Python pydubpip install pydub

选择最适合你操作系统的方案,一般推荐FFmpeg方案,功能最全面且跨平台支持好。

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