Python Gadgets: 3 seconds to convert video to audio

Foreword

Text and images in this article from the network, only to learn, exchange, not for any commercial purposes, belongs to original author, if any questions, please contact us for treatment.

Author: pk brother

PS: If necessary Python learning materials can be added to a small partner click the link below to obtain their own

http://note.youdao.com/noteshare?id=3054cce4add8a909e784ad934f956cef

Importing installation

Quick installation pip command.

pip install ffmpy3 

Import just installed ffmpy3 libraries inferior need to read the directory to store video and audio stored in the directory, so we need to import the os module.

import os
from ffmpy3 import FFmpeg

Create a directory to save the audio

We need to put the converted audio files stored in the specified folder in order to be more intelligent, we make a judgment, if this directory does not exist, we create, present, remains unchanged.

. 1  DEF mkdir_output (output_dir):
 2      Existence = os.path.exists (output_dir)
 . 3      IF  Not Existence:
 . 4          Print ( ' create audio storage directory ' )
 . 5          os.makdirs (output_dir)     # Create a directory 
. 6          the os.chdir (output_dir)        # switch to the folder you created 
7          return True
 8      the else :
 9          Print ( ' ! directory already exists, is about to save ' )
 10          return False

We store the path as an argument, given storage path when you can wait for the next call.

File format handling

We need to convert video to audio files in a folder, with the file name of the video module os read out on the list.

. 1 filepath R & lt = " / the Users / brucepk / Test "    # path to be converted stored video 
2 the os.chdir (filepath)                   # switch to the modified path 
. 3 filename = the os.listdir (filepath)   # all file names in the folder to give

Then we replace all video files into audio format suffixes, many video file formats, I basically common listed.

Here Insert Picture Description

Convert all video files into the appropriate directory wav audio files stored in the specified directory.

Audio File Properties

Just change the file extension, of course not, no change file attributes, such files can not be read, we need FFmpeg method of audio give it the attributes of the audio file after conversion.

1 ff = FFmpeg(
2             inputs={changefile: None},
3             outputs={outputfile: '-vn -ar 44100 -ac 2 -ab 192 -f wav'}
4             )
5         print(ff.cmd)
6         ff.run()

effect

I put in the test directory two video files, one that I take with your phone mp4 format video, in order to test the effect, and recorded a voice, another video format is mkv movie.

Here Insert Picture Description

After running the code, it will automatically create a folder output, which is the converted audio files.

Here Insert Picture Description

Audio software supports open, you can clearly hear the audio.

Run error process

1, when you run the code, Windows system may not find an error like ffmpeg appears, as shown below. Here Insert Picture Description

At this point, we need to download FFmpeg, visit the address below to download the appropriate installation package according to their own computer version.

Here Insert Picture Description

Ffmpeg unzip the file, open ffmpy3.py file (hold down the Ctrl key, click ffmpy3, quickly jump to the module), the value of the executable code below ffmpeg.exe parameter to the absolute path of the executable file.

__init__(self, executable='ffmpeg', global_options=None, inputs=None, outputs=None)

解压后的 ffmpeg.exe 文件在 bin 目录下,把路径替换掉。

Here Insert Picture Description

修改后,再次运行,就可以顺利转换了。

2、路径拼接的问题

我的代码是在 Mac 系统中完成的,Mac 中路径是用 / 隔开,而 Windows 中是用 \,为了防止收到转义字符的影响,路径前面最好加上 r。

filepath = r"/Users/brucepk/test"

所以在路径拼接时,Windows 电脑记得 "/" 换成 ""

changefile = filepath+"/"+filename[i]

以上时 Mac 系统的写法,Windows 中改成:

changefile = filepath+"\\"+filename[i]
完整代码
 1 import os
 2 from ffmpy3 import FFmpeg
 3  4 def mkdir_output(output_dir):
 5     existence = os.path.exists(output_dir)
 6     if not existence:
 7         print('创建音频存放目录')
 8         os.makedirs(output_dir)    # 创建目录
 9         os.chdir(output_dir)       # 切换到创建的文件夹
10         return True
11     else:
12         print('目录已存在,即将保存!')
13         return False
14 15 16 if __name__ == '__main__':
17     filepath = r"/Users/brucepk/test"   # 待转换视频存放的路径
18     os.chdir(filepath)                  # 切换到改路径下
19     filename = os.listdir(filepath)     # 得到文件夹下的所有文件名称
20 21     output_dir = r'/Users/brucepk/output'    # 转换后音频文件存放的路径
22     mkdir_output(output_dir)
23     for i in range(len(filename)):
24         # windows电脑记得把下面两处的 "/" 换成 "\\"
25         changefile = filepath+"/"+filename[i]
26         outputfile = output_dir+"/"+filename[i].replace('mp4', 'wav').replace('mkv', 'wav')\
27             .replace('rmvb', 'wav').replace('3gp', 'wav').replace('avi', 'wav')\
28             .replace('mpeg', 'wav').replace('mpg', 'wav').replace('dat', 'asf')\
29             .replace('wmv', 'wav').replace('flv', 'wav').replace('mov', 'wav')\
30             .replace('mp4', 'wav').replace('ogg', 'wav').replace('ogm', 'wav')\
31             .replace('rm', 'wav')
32 33         ff = FFmpeg(
34             inputs={changefile: None},
35             outputs={outputfile: '-vn -ar 44100 -ac 2 -ab 192 -f wav'}
36             )
37         print(ff.cmd)
38         ff.run()

 

Guess you like

Origin www.cnblogs.com/Qqun821460695/p/11971703.html