Python實現視頻轉換為音頻的方法詳解
1. Python需求的任務
Python如何將視頻轉換為音頻并將音頻文件保存到特定文件夾下
2. Python代碼的實現
from moviepy.editor import * import os def video_to_audio(video_file, output_folder): video = VideoFileClip(video_file) audio_file = os.path.join(output_folder, os.path.splitext(os.path.basename(video_file))[0] + ".mp3") audio = video.audio audio.write_audiofile(audio_file) return audio_file def main(): video_file = "D:/200-Life/220-Money/223-小紅書/舍長語錄視頻集合/第2集 陰陽五行:“東西方”一直明爭暗斗,導致的人體健康和世界格局.mp4" output_folder = "D:/200-Life/220-Money/223-小紅書/舍長語錄視頻集合" if not os.path.exists(output_folder): os.makedirs(output_folder) audio_file = video_to_audio(video_file, output_folder) print("音頻文件已保存到:", audio_file) if __name__ == "__main__": main()
3. 代碼修改的位置
video_file = "D:/200-Life/220-Money/223-小紅書/舍長語錄視頻集合/第2集 陰陽五行:“東西方”一直明爭暗斗,導致的人體健康和世界格局.mp4" output_folder = "D:/200-Life/220-Money/223-小紅書/舍長語錄視頻集合"
代碼只需要修改兩處,第一處是視頻位置,第二處是視頻導出的位置
4. 運行結果
代碼運行
運行結果
5. 注意事項
注意修改的文件路徑最好是 "xxx/xxx/xxx/xxxxxx/xxx/xx/"
這樣,注意斜杠的方向是/
,而不是\
。
6.方法補充
除了上文的方法,小編還為大家整理了一些其他Python視頻轉音頻的方法,希望對大家有所幫助
使用movipy庫 編寫python腳本將視頻轉換為mp3音頻
安裝movipy庫
打開powershell
pip install movipy
編寫腳本
新建文本video_to_audio.py
#!/usr/bin/env python3 import sys import time import os # import pipes from moviepy import * # 設置默認的比特率 DEFAULT_BITRATE = '32k' def convert_to_mp3(filename, bitrate): clip = VideoFileClip(filename) clip.audio.write_audiofile(filename[:-4] + " bitrate" + bitrate + ".mp3", bitrate=bitrate) clip.close() def main(): if len(sys.argv) <2 or len(sys.argv) > 3: print('command usage: python3 video_to_audio.py FileName') exit(1) else: filePath = sys.argv[1] bitrate = sys.argv[2] if len(sys.argv) == 3 else DEFAULT_BITRATE # check if the specified file exists or not if os.path.exists(filePath): print("file found! bitrate={bitrate}") # convert video to audio convert_to_mp3(filePath, bitrate=bitrate) else: print("no file: {filePath}") # time.sleep(1) # install ffmpeg and/or lame if you get an error saying that the program is currently not installed if __name__ == '__main__': main()
運行
在powershell中運行
python video_to_audio.py "video.mp4" 16k
第一個參數是文件路徑,第二個參數是音頻質量(比特率)默認32k,可選擇32k、64k、128k。
最低質量32k,再小也不會減小文件大小了,聲音質量還差
運行不起來就用絕對文件路徑
到此這篇關于Python實現視頻轉換為音頻的方法詳解的文章就介紹到這了,更多相關Python視頻轉音頻內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
在python中使用pymysql往mysql數據庫中插入(insert)數據實例
今天小編就為大家分享一篇在python中使用pymysql往mysql數據庫中插入(insert)數據實例。具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03Python?shapefile轉GeoJson的2種方式實例
geojson是地圖可視化系統(tǒng)中最常用的地理數據格式,幾乎所有主流地圖可視化庫或框架都支持geojson數據的加載,下面這篇文章主要給大家介紹了關于Python?shapefile轉GeoJson的2種方式的相關資料,需要的朋友可以參考下2023-03-03詳解利用OpenCV提取圖像中的矩形區(qū)域(PPT屏幕等)
這篇文章主要介紹了詳解利用OpenCV提取圖像中的矩形區(qū)域(PPT屏幕等),小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-07-07