Python腳本實(shí)現(xiàn)音頻和視頻格式轉(zhuǎn)換
一、音頻格式轉(zhuǎn)換完整代碼
from pydub import AudioSegment import os def convert_audio(input_dir, output_dir, target_format): if not os.path.exists(output_dir): os.makedirs(output_dir) for filename in os.listdir(input_dir): if filename.endswith(('.mp3', '.wav', '.ogg')): input_path = os.path.join(input_dir, filename) output_filename = os.path.splitext(filename)[0] + f".{target_format}" output_path = os.path.join(output_dir, output_filename) audio = AudioSegment.from_file(input_path) audio.export(output_path, format=target_format) print(f"Converted {filename} to {output_filename}") convert_audio("./input_audio", "./output_audio", "mp3")
二、視頻格式轉(zhuǎn)換完整代碼
from moviepy import * def convert_video_format(input_path, output_path): """將視頻轉(zhuǎn)換為不同格式""" try: video = VideoFileClip(input_path) video.write_videofile(output_path) video.close() print(f"轉(zhuǎn)換完成: {output_path}") except Exception as e: print(f"轉(zhuǎn)換失敗: {str(e)}") # 使用示例 convert_video_format("input.mp4", "output.avi")
三、方法補(bǔ)充
Python腳本實(shí)現(xiàn)批量格式轉(zhuǎn)換(視頻轉(zhuǎn)音頻)
利用ffmpeg工具和Python,實(shí)現(xiàn)批量視頻/音頻格式轉(zhuǎn)換。本例只給出視頻轉(zhuǎn)音頻(.wav)方法,更多格式轉(zhuǎn)換可百度ffmpeg用法,修改代碼中對應(yīng)語句即可。
# coding=UTF-8 import os, sys import subprocess from scipy.io import wavfile def ffmpeg_VideoToAudio(VideoPath, WavPath): # 提取視頻路徑下所有文件名 videos = os.listdir(VideoPath) count = 0 for video in videos: # 提取視頻的全路徑名(含路徑+文件名) video_path = VideoPath + "\\" + video # 合成輸出音頻的全路徑名(不含后綴) wav_path = WavPath + "\\" + os.path.splitext(video)[0] # 提取視頻中的音頻信息 strcmd = "ffmpeg -i " + video_path + " -f wav " + wav_path + ".wav" subprocess.call(strcmd, shell=True) VideoPath = r'D:\videos' WavPath = r'D:\audios' ffmpeg_VideoToAudio(VideoPath,WavPath)
python整合ffmpeg實(shí)現(xiàn)視頻文件的批量轉(zhuǎn)換
我們的思路是,設(shè)定一個(gè)文件夾存放源視頻文件,python讀取該文件夾下的全部文件,并對文件通過ffmpeg進(jìn)行分析,根據(jù)需要,修改目標(biāo)文件的編碼、分辨率等等,調(diào)用ffmpeg轉(zhuǎn)換。
我這次的需求是,我家液晶電視只支持分辨來,長寬均小于720,編碼只支持divx/xvid的avi文件,且fps只能小于25——多次實(shí)踐,才總結(jié)出來的,電視說明書也沒說??!
下面的程序?qū)?root//root2/video/origin下存在的全部文件轉(zhuǎn)換成液晶電視需要的avi格式電影
以下是最新的修改,引入了OptionParser 參數(shù)分析工具。能指定最大寬度,音視頻編碼,視頻質(zhì)量,原路徑,目的路徑,工作路徑等
# 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 options.srcD==None or options.srcD[0:1]=='-': print 'srcD Err, quit' exit() if options.targetD==None or options.targetD[0:1]=='-': print 'targetD Err, quit' exit() if options.fileType==None or options.fileType[0:1]=='-': print 'fileType Err, quit' exit() if options.workdir==None or options.workdir[0:1]=='-': print 'workdir Err, quit' exit() #遍歷origin下的文件 for root,dirs,files in os.walk(options.srcD): for name in files: name= name.replace('[','''\[''')#對文件名中的[進(jìn)行轉(zhuǎn)義 newname =name[0: name.rindex('.')] #運(yùn)行一次ffmpeg,獲取分辨率 (si, so, se) = os.popen3('cd '+options.workdir+';mkdir -p ffm; rm -f ffm/ffm.txt ; csh -c "(ffmpeg -i '+options.srcD+'/' +name+ ' >& ffm/ffm.txt)"; grep Stream ffm/ffm.txt') t=so.readlines() ti=0 for line in se.readlines() : 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 = re.compile(reg).findall(line) for c in result: print name+' '+c[0] + 'x' + c[1] width=string.atoi(c[0]) height=string.atoi(c[1]) if name[0:3]=='M2U' and width==720 and height==576:#m2U開頭的,寬度是720x576的,是4:3存儲16:9的,將其轉(zhuǎn)換為16:9 width=1024 if width==0: print 'error parsing width and height' exit() vc='' qstr='' astr='' vpre='' s='' if options.maxWidth!='': if width>string.atoi(options.maxWidth): height = height * string.atoi(options.maxWidth) / width width = string.atoi(options.maxWidth) padStr='' if options.pad==True: if height*16/9 - width>10:#寬度不夠 padStr=' -vf "pad='+str(height*16/9)+':'+str(height)+':'+str((height*16/9 - width)/2)+':0:black"' elif width - height*16/9 >10:#高度不夠 padStr=' -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 options.preset!='': vpre=' -vpre '+options.preset if options.an==True: astr=' -an' elif options.ogg==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 options.vcodec=='vp8': vc='libvpx' qstr=" -qmin "+options.q+" -qmax "+options.q elif options.vcodec=='x264': vc='libx264' qstr=" -crf "+options.q elif options.vcodec=='xvid': vc='libxvid' qstr=" -qmin "+options.q+" -qmax "+options.q cmd ='csh -c "' + "cd "+options.workdir+";touch ffm/output.log;(ffmpeg -y -i "+options.srcD+"/"+name+astr+" -vcodec "+vc+vpre+qstr+s+" -r 25 -threads 8 "+options.targetD+"/"+newname+"."+options.fileType + ' >>& ffm/output.log)"' print cmd #運(yùn)行 (si, so, se) = os.popen3(cmd) for line in se.readlines() :#打印輸出 print line for line in so.readlines() :#打印輸出 print line #print cmd,' finish'#再顯示一次命令
到此這篇關(guān)于Python腳本實(shí)現(xiàn)音頻和視頻格式轉(zhuǎn)換的文章就介紹到這了,更多相關(guān)Python格式轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 利用Python小工具實(shí)現(xiàn)3秒鐘將視頻轉(zhuǎn)換為音頻
- Python使用pydub模塊轉(zhuǎn)換音頻格式以及對音頻進(jìn)行剪輯
- Python?如何實(shí)現(xiàn)批量轉(zhuǎn)換視頻音頻的采樣率
- Python實(shí)現(xiàn)將mp3音頻格式轉(zhuǎn)換為wav格式
- 如何使用Python實(shí)現(xiàn)數(shù)據(jù)透視表、音頻文件格式轉(zhuǎn)換
- Python實(shí)現(xiàn)視頻轉(zhuǎn)換為音頻的方法詳解
- Python使用FFmpeg實(shí)現(xiàn)高效音頻格式轉(zhuǎn)換工具
- 使用python中Pydub進(jìn)行音頻格式轉(zhuǎn)換
相關(guān)文章
Python編程在flask中模擬進(jìn)行Restful的CRUD操作
今天小編就為大家分享一篇關(guān)于Python編程在flask中模擬進(jìn)行Restful的CRUD操作,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2018-12-12Python中map,reduce,filter和sorted函數(shù)的使用方法
這篇文章主要介紹了Python中map,reduce,filter和sorted函數(shù)的使用方法,是Python入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-08-08使用pycharm和pylint檢查python代碼規(guī)范操作
這篇文章主要介紹了使用pycharm和pylint檢查python代碼規(guī)范操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06opencv 圖像腐蝕和圖像膨脹的實(shí)現(xiàn)
這篇文章主要介紹了opencv 圖像腐蝕和圖像膨脹的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07python 的 scapy庫,實(shí)現(xiàn)網(wǎng)卡收發(fā)包的例子
今天小編就為大家分享一篇python 的 scapy庫,實(shí)現(xiàn)網(wǎng)卡收發(fā)包的例子,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07Python 使用 PyMysql、DBUtils 創(chuàng)建連接池提升性能
DBUtils 是一套 Python 數(shù)據(jù)庫連接池包,并允許對非線程安全的數(shù)據(jù)庫接口進(jìn)行線程安全包裝。這篇文章主要介紹了Python 使用 PyMysql、DBUtils 創(chuàng)建連接池,提升性能,需要的朋友可以參考下2019-08-08Pandas中兩個(gè)dataframe的交集和差集的示例代碼
這篇文章主要介紹了Pandas中兩個(gè)dataframe的交集和差集的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12Python設(shè)計(jì)模式之簡單工廠模式實(shí)例詳解
這篇文章主要介紹了Python設(shè)計(jì)模式之簡單工廠模式,結(jié)合實(shí)例形式分析了簡單工廠模式的概念、原理及相關(guān)使用技巧,需要的朋友可以參考下2019-01-01