SoFunction
Updated on 2025-04-11

Python scripts implement audio and video format conversion

1. Complete code for audio format conversion

from pydub import AudioSegment
import os
 
 
def convert_audio(input_dir, output_dir, target_format):
    if not (output_dir):
        (output_dir)
 
    for filename in (input_dir):
        if (('.mp3', '.wav', '.ogg')):
            input_path = (input_dir, filename)
            output_filename = (filename)[0] + f".{target_format}"
            output_path = (output_dir, output_filename)
 
            audio = AudioSegment.from_file(input_path)
            (output_path, format=target_format)
            print(f"Converted {filename} to {output_filename}")
 
 
convert_audio("./input_audio", "./output_audio", "mp3")

2. Convert the complete code of video format

from moviepy import *
 
def convert_video_format(input_path, output_path):
    """Convert video to different formats"""
    try:
        video = VideoFileClip(input_path)
        video.write_videofile(output_path)
        ()
        print(f"Conversion is complete: {output_path}")
    except Exception as e:
        print(f"Conversion failed: {str(e)}")
 
#User Exampleconvert_video_format("input.mp4", "")

3. Supplementary method

Python scripts implement batch format conversion (video to audio)

Use ffmpeg tool and Python to realize batch video/audio format conversion. This example only gives the video to audio (.wav) method. For more format conversion, you can use Baidu ffmpeg usage and modify the corresponding statements in the code.

# coding=UTF-8
import os, sys
import subprocess
from  import wavfile

def ffmpeg_VideoToAudio(VideoPath, WavPath):
    # Extract all file names in the video path    videos = (VideoPath)
    count = 0
    for video in videos:
        # Extract the full path name of the video (including path + file name)        video_path = VideoPath + "\\" + video
        # The full path name of the synthesized output audio (excluding the suffix)        wav_path = WavPath + "\\" + (video)[0]
        # Extract audio information from video        strcmd = "ffmpeg -i " + video_path + " -f wav " + wav_path + ".wav"
        (strcmd, shell=True)

VideoPath = r'D:\videos'
WavPath = r'D:\audios'
ffmpeg_VideoToAudio(VideoPath,WavPath)

Python integrates ffmpeg to realize batch conversion of video files

Our idea is to set a folder to store the source video file, python reads all files in the folder, analyzes the files through ffmpeg, modify the encoding, resolution, etc. of the target file according to needs, and call ffmpeg conversion.

My need this time is that my LCD TV only supports discrimination, both length and width are less than 720, the encoding only supports divx/xvid Avi files, and the fps can only be less than 25-it was summarized after many practices, and the TV manual did not say anything! !

The following program converts all files present in /root//root2/video/origin to the avi format movie required by LCD TV.

The following are the latest changes, introducing the OptionParser parameter analysis tool. Can specify maximum width, audio and video encoding, video quality, original path, destination path, working path, etc.

# coding=gb2312
import string
import os
import time
import re
import sys
from optparse import OptionParser
parser = OptionParser()
#parser.add_option("-i", "--input", dest="input",action="store_true",help="input x y for each file by user")
parser.add_option("-q", "--quality", dest="q",action="store",help="input xvid q arg",default="24")
parser.add_option("-v", "--vcodec", dest="vcodec",action="store",help="input video codec",default="x264")
parser.add_option("-n", "--noaudio", dest="an",action="store_true",help="no audio")
parser.add_option("-p", "--preset", dest="preset",action="store",help="",default="")
parser.add_option("-m", "--maxWidth", dest="maxWidth",action="store",help="input max width for output video",default="")
parser.add_option("-f", "--fileType", dest="fileType",action="store",help="",default="mp4")
parser.add_option("-o", "--ogg", dest="ogg",action="store_true",help="user ogg instead of aac",default="")
parser.add_option("-3", "--mp3", dest="mp3",action="store_true",help="user mp3 instead of aac",default="")
parser.add_option("-1", "--pad", dest="pad",action="store_true",help="pad to 16:9",default="")
parser.add_option("-s", "--src", dest="srcD",action="store",help="source dir",default="/usr/disk2/root/video/origin")
parser.add_option("-t", "--target", dest="targetD",action="store",help="target dir",default="/usr/disk2/root/video/ok")
parser.add_option("-w", "--workdir", dest="workdir",action="store",help="work dir",default="/root/root2/video")
(options, args) = parser.parse_args()
if ==None or [0:1]=='-':
print 'srcD Err, quit'
exit()
if ==None or [0:1]=='-':
print 'targetD Err, quit'
exit()
if ==None or [0:1]=='-':
print 'fileType Err, quit'
exit()
if ==None or [0:1]=='-':
print 'workdir Err, quit'
exit()
#Travel over files under originfor root,dirs,files in ():
for name in files:
name= ('[','''\[''')#Escape [ in the file namenewname =name[0: ('.')]
#Run ffmpeg once to get resolution(si, so, se) = os.popen3('cd '++';mkdir -p ffm; rm -f ffm/ ; csh -c "(ffmpeg -i '++'/' +name+ ' >& ffm/)"; grep Stream ffm/')
t=()
ti=0
for line in () :
print line
width=0
height=0
reg='''^\s*Stream.*,\s*(\d+)x(\d+)(?: \[SAR|,)'''
#Stream #0.0: Video: RV40 / 0x30345652, 1020x572, 23 fps, 23 tbr, 23 tbn, 23 tbc
for line in t:
result = (reg).findall(line)
for c in result:
print name+' '+c[0] + 'x' + c[1]
width=(c[0])
height=(c[1])
if name[0:3]=='M2U' and width==720 and height==576:#m2U starts with width 720x576, is 4:3 stored 16:9, convert it to 16:9width=1024
if width==0:
print 'error parsing width and height'
exit()
vc=''
qstr=''
astr=''
vpre=''
s=''
if !='':
if width>():
height = height * () / width
width = ()
padStr=''
if ==True:
if height*16/9 - width>10:#The width is not enoughpadStr=' -vf "pad='+str(height*16/9)+':'+str(height)+':'+str((height*16/9 - width)/2)+':0:black"'
elif width - height*16/9 >10:#The height is not enoughpadStr=' -vf "pad='+str(width)+':'+str(width*9/16)+':0:'+str((width - height*16/9)/2)+':black"'
s=' -s '+str(width)+'x'+str(height)+padStr
print 'adjust',s
if !='':
vpre=' -vpre '+
if ==True:
astr=' -an'
elif ==True:
astr=' -acodec libvorbis -ar 44100 -ab 64K'
elif options.mp3==True:
astr=' -acodec libmp3lame -ar 44100 -ab 64K'
else:
astr=' -acodec libfaac -ar 44100 -ab 64K'
if =='vp8':
vc='libvpx'
qstr=" -qmin "++" -qmax "+
elif =='x264':
vc='libx264'
qstr=" -crf "+
elif =='xvid':
vc='libxvid'
qstr=" -qmin "++" -qmax "+
cmd ='csh -c "' + "cd "++";touch ffm/;(ffmpeg -y -i "++"/"+name+astr+" -vcodec "+vc+vpre+qstr+s+" -r 25 -threads 8 "++"/"+newname+"."+ + ' >>& ffm/)"'
print cmd
#run(si, so, se) = os.popen3(cmd)
for line in () :#Print Outprint line
for line in () :#Print Outprint line
#print cmd,' finish'#Show command again

This is the article about Python scripts implementing audio and video format conversion. For more related Python format conversion content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!