You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python批量将MP4转同名WAV遇问题:输出均为out.wav求解决方案

Fixing Batch MP4 to WAV Conversion with Unique Filenames

Got it, let's sort out this batch conversion issue for you! The core problem right now is that you're using a fixed output filename (out.wav) for every file, so each conversion overwrites the last one. The fix is straightforward: generate a unique WAV filename that matches each input MP4's name.

Here are two practical solutions using popular Python libraries, both with configurable audio parameters like sample rate:


Solution 1: Using ffmpeg-python (Flexible & Powerful)

This library wraps FFmpeg, the industry-standard tool for media processing, and lets you fine-tune audio parameters easily.

First, install the library if you haven't:

pip install ffmpeg-python

Then use this code:

import os
import ffmpeg

# Configure your directories and audio settings
input_directory = "inputdir"
output_directory = "outputdir"
target_sample_rate = 16000  # Adjust to your needs (e.g., 44100 for CD quality)
target_channels = 1         # 1 for mono, 2 for stereo

# Create output directory if it doesn't exist
os.makedirs(output_directory, exist_ok=True)

# Loop through all files in the input directory
for filename in os.listdir(input_directory):
    # Only process MP4 files (case-insensitive)
    if filename.lower().endswith(".mp4"):
        # Build full paths for input and output
        input_file_path = os.path.join(input_directory, filename)
        
        # Generate matching WAV filename: strip .mp4 extension and add .wav
        file_base_name = os.path.splitext(filename)[0]
        output_file_name = f"{file_base_name}.wav"
        output_file_path = os.path.join(output_directory, output_file_name)
        
        # Run the conversion with your desired audio parameters
        try:
            (
                ffmpeg
                .input(input_file_path)
                .output(
                    output_file_path,
                    ar=target_sample_rate,
                    ac=target_channels,
                    format="wav"
                )
                .run(quiet=True)  # Set to False if you want to see FFmpeg logs
            )
            print(f"Successfully converted: {filename} → {output_file_name}")
        except Exception as e:
            print(f"Failed to convert {filename}: {str(e)}")

Key Fix:

The line file_base_name = os.path.splitext(filename)[0] extracts your MP4's name without the .mp4 extension. We use this to create a matching .wav file—so video001.mp4 becomes video001.wav, no more overwrites.


Solution 2: Using pydub (Simpler, Pythonic API)

If you prefer a more high-level, beginner-friendly interface, pydub is a great choice. Note that it requires FFmpeg to be installed on your system (add it to your PATH, or specify its location in code).

Install pydub first:

pip install pydub

Here's the code:

import os
from pydub import AudioSegment

input_directory = "inputdir"
output_directory = "outputdir"
target_sample_rate = 16000

os.makedirs(output_directory, exist_ok=True)

for filename in os.listdir(input_directory):
    if filename.lower().endswith(".mp4"):
        input_path = os.path.join(input_directory, filename)
        file_base_name = os.path.splitext(filename)[0]
        output_path = os.path.join(output_directory, f"{file_base_name}.wav")
        
        # Load the MP4 audio
        audio = AudioSegment.from_file(input_path, format="mp4")
        
        # Adjust audio parameters
        audio = audio.set_frame_rate(target_sample_rate)
        # Uncomment below to set mono/stereo
        # audio = audio.set_channels(1)
        
        # Export as WAV
        audio.export(output_path, format="wav")
        print(f"Converted: {filename} → {file_base_name}.wav")

Quick Note for pydub:

If FFmpeg isn't in your system PATH, specify its location at the start of your code:

AudioSegment.converter = "path/to/your/ffmpeg.exe"  # Windows example

Either solution will ensure each MP4 gets converted to a uniquely named WAV file. Just tweak the sample rate, channels, and directories to match your exact needs.

内容的提问来源于stack exchange,提问作者megha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:04:28