1. Python需求的任务
Python如何将视频转换为音频并将音频文件保存到特定文件夹下
2. Python代码的实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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. 代码修改的位置
1 2 | 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
1 | pip install movipy |
编写脚本
新建文本video_to_audio.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #!/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) 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中运行
1 | python video_to_audio.py "video.mp4" 16k |
第一个参数是文件路径,第二个参数是音频质量(比特率)默认32k,可选择32k、64k、128k。
最低质量32k,再小也不会减小文件大小了,声音质量还差
运行不起来就用绝对文件路径
到此这篇关于Python实现视频转换为音频的方法详解的文章就介绍到这了,更多相关Python视频转音频内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!