最近需要將m4a檔案轉檔為mp3,所以寫python程式來處理。希望將很多的m4a放進input資料夾內,只要點兩下滑鼠就能將這些m4a 通通轉檔為 mp3。
Recently, I needed to convert M4A files into MP3 format, so I wrote a Python program to handle it. The idea is to place multiple M4A files into an input folder, then simply double-click the program to automatically convert all the M4A files into MP3 files.
下載檔案。解壓密碼:demo1234
Here is the website where you can download the program and find instructions:
Download。Extraction Password: demo1234使用教學(Instructional videos):
以下是開發過程與原始碼 (Development process and code):
01.安裝 python 套件(Install Python packages.)
pip install pydub
02.下載 ffmpeg 並加入 PATH (Download FFmpeg and add it to the system PATH.)
程式名稱(Program name):install_ffmpeg.bat
程式內容(Code):
@echo off
:: 檢查是否為系統管理員
net session >nul 2>&1
if %errorLevel% neq 0 (
echo 正在要求系統管理員權限...
powershell -Command "Start-Process '%~f0' -Verb RunAs"
exit /b
)
setlocal
echo.
echo ===== 安裝 FFmpeg =====
echo.
REM 建立 ffmpeg 資料夾
if not exist C:\ffmpeg (
mkdir C:\ffmpeg
)
REM 下載 ffmpeg
echo 下載 FFmpeg...
powershell -Command ^
"Invoke-WebRequest -Uri https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.zip -OutFile C:\ffmpeg\ffmpeg.zip"
REM 解壓縮
echo 解壓縮中...
powershell -Command ^
"Expand-Archive -Path C:\ffmpeg\ffmpeg.zip -DestinationPath C:\ffmpeg -Force"
REM 找到 bin 路徑
for /d %%i in (C:\ffmpeg\ffmpeg-*) do (
set "FFMPEG_BIN=%%i\bin"
)
REM 加入系統 PATH
echo 加入 PATH...
setx PATH "%PATH%;%FFMPEG_BIN%" /M
echo.
echo ===== FFmpeg 安裝完成 =====
echo.
echo 請重新開啟 CMD 或 PowerShell
echo 測試指令:
echo ffmpeg -version
echo.
pause
03.python 程式名稱(Python script filename.):pyM4a2Mp3.py
程式內容(Code):
from pydub import AudioSegment
import os
input_folder = "input"
output_folder = "output"
# 如果 output_folder 不存在就建立
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for file in os.listdir(input_folder):
if file.endswith(".m4a"):
m4a_path = os.path.join(input_folder, file)
mp3_filename = os.path.splitext(file)[0] + ".mp3"
mp3_path = os.path.join(output_folder, mp3_filename)
# 讀取 m4a
audio = AudioSegment.from_file(m4a_path, format="m4a")
# 輸出 mp3
audio.export(mp3_path, format="mp3")
print(f"已轉換: {file} -> {mp3_filename}")
print("全部轉換完成")
沒有留言:
張貼留言