Python3, if you know that you can extract audio with 3 lines of code, is it not delicious for me to buy buns with these 10 yuan?

1 Introduction

Xiao Diaosi : Brother Yu, I want to extract the audio from the video. Is there any way?
Xiaoyu : You can do it directly with software.
Xiao Diaosi : Then you can't use money
Xiaoyu : ... Do you want to prostitute for free? ?
Xiao Diaosi : No, I have to rely on my own skills!
Xiaoyu : Then you can rely on it!
Xiao Diaosi : This cannot be done without your support.
Xiaoyu : With you, this is a flower, and I am a green leaf?
Xiao Diaosi : No, you are a root, without a root, there is no flower...
Xiaoyu : Oh, I still have to contribute to you when I co-author it?
Xiao Diaosi : Brother Yu, do you think there is such a library that can do this?
Xiaoyu : Yes, there must be...
Xiao Diaosi : I understand, old rules.
Xiaoyu : Well, open the whole thing.
insert image description here

2. Code combat

2.1 Introduction to Third-Party Libraries

Today, I will introduce a library that can extract only audio from video - ffmpy.
Many people may not have mentioned this library, but everyone should have heard of FFmpeg, which
can run recording, conversion, and streaming functions in multiple formats of audio and video.
Speaking of which, I have to mention two libraries:

  • libavcodec: Decoder library for audio and video in multiple projects
  • libavformat: an audio and video format conversion library

In Python, FFmpeg corresponds to ffmpy. so,

2.2 Installation

Old rules, direct pip installation

pip install ffmpy3

Other ways to install:

" Python3, choose Python to automatically install third-party libraries, and say goodbye to pip! ! "
" Python3: I only use one line of code to import all Python libraries! !

2.3 Code Examples

Since the code is very concise, let's go directly to the code

# -*- coding:utf-8 -*-
# @Time   : 2022-03-13
# @Author : carl_DJ

import uuid
import os
import  ffmpy3


'调用FFmpeg提取音频'
#传入三个参数:视频地址,音频结果存入地址,音频的格式后缀
def run_ffmpeg(video_path:str,audio_path:str,format:str):
	ff=  ffmpy3.FFmpeg(inputs =  {
    
    video_path:None},outputs = {
    
    audio_path:'-f{} -vn'.format(format)})
		ff.run()
	return audio_path
	
'接收参数'
def extract(video_path:str,tmp_dir:str,ext:str):
	file_name = '.'.join(os.path.basename(video_path).split('.')[0:-1])
	temp_name = os.path.join(tmp_dir,'{}.{}'.format(uuid.uuid4(),ext))
	return run_ffmpeg(video_path,temp_name,ext)

if __name__ == "__main__":
	print(extract('D:\project\kd.mp4','D:\project\video','wav'))	


After running, it will generate a wav format audio file whose folder is uuid.

3. Summary

Seeing this, today's sharing is almost here.
Mainly to extract audio content,
and ffmpy3 has many functions, you can refer to the official documentation.

Guess you like

Origin blog.csdn.net/wuyoudeyuer/article/details/123470161