current position:Home>Python video add audio (with code) | Python tool

Python video add audio (with code) | Python tool

2022-02-02 09:46:50 Swordsman a Liang_ ALiang

Catalog

Preface

Environment depends on

Code

summary


Preface

This article provides a way to add audio to video without audio python Tools , Attach code .

Environment depends on

ffmpeg Environmental installation , You can refer to another article of mine :windows ffmpeg Installation and deployment _ A Liang's blog -CSDN Blog

ffmpy install :

pip install ffmpy -i https://pypi.douban.com/simple

Code

Don't bullshit , Code up .

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/12/5 1:49
# @Author  :  Swordsman a Liang _ALiang
# @Site    : 
# @File    : video_add_audio_tool.py

import os
import uuid
from ffmpy import FFmpeg


#  Video add audio 
def video_add_audio(video_path: str, audio_path: str, output_dir: str):
    _ext_video = os.path.basename(video_path).strip().split('.')[-1]
    _ext_audio = os.path.basename(audio_path).strip().split('.')[-1]
    if _ext_audio not in ['mp3', 'wav']:
        raise Exception('audio format not support')
    _codec = 'copy'
    if _ext_audio == 'wav':
        _codec = 'aac'
    result = os.path.join(
        output_dir, '{}.{}'.format(
            uuid.uuid4(), _ext_video))
    ff = FFmpeg(
        inputs={video_path: None, audio_path: None},
        outputs={result: '-map 0:v -map 1:a -c:v copy -c:a {} -shortest'.format(_codec)})
    print(ff.cmd)
    ff.run()
    return result

Code instructions

1、video_add_audio Method parameters have video address 、 Audio address 、 The output directory .

2、 Audio support mp3 as well as wav Format , among wav Format ffmpeg The command will be different .

Check it out

if __name__ == '__main__':
    print(video_add_audio('data/999.mp4', 'data/2dc9fa4f-802d-4076-b2c3-b1da886a7cc0.wav', 'data/'))
E:\ProgramData\Anaconda3\envs\pytorch\python.exe C:/Users/yi/PycharmProjects/test/video_add_audio_tool.py
ffmpeg -i data/999.mp4 -i data/2dc9fa4f-802d-4076-b2c3-b1da886a7cc0.wav -map 0:v -map 1:a -c:v copy -c:a aac -shortest data/6854281e-19ac-4edc-9638-4124a2a22e52.mp4
ffmpeg version n4.3.1-20-g8a2acdc6da Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 9.3-win32 (GCC) 20200320
  configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-iconv --enable-zlib --enable-libxml2 --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvmaf --disable-vulkan --enable-libvorbis --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-ffnvcodec --enable-cuda-llvm --disable-libglslang --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libtwolame --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-libs=-lgomp
  libavutil      56. 51.100 / 56. 51.100
  libavcodec     58. 91.100 / 58. 91.100
  libavformat    58. 45.100 / 58. 45.100
  libavdevice    58. 10.100 / 58. 10.100
  libavfilter     7. 85.100 /  7. 85.100
  libswscale      5.  7.100 /  5.  7.100
  libswresample   3.  7.100 /  3.  7.100
  libpostproc    55.  7.100 / 55.  7.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'data/999.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2mp41
    encoder         : Lavf58.76.100
  Duration: 00:00:04.88, start: 0.000000, bitrate: 8420 kb/s
    Stream #0:0(und): Video: mpeg4 (Simple Profile) (mp4v / 0x7634706D), yuv420p, 1280x688 [SAR 1:1 DAR 80:43], 8417 kb/s, 25 fps, 25 tbr, 12800 tbn, 25 tbc (default)
    Metadata:
      handler_name    : VideoHandler
Guessed Channel Layout for Input Stream #1.0 : stereo
Input #1, wav, from 'data/2dc9fa4f-802d-4076-b2c3-b1da886a7cc0.wav':
  Metadata:
    copyright       : bbs.cnxp.com(C)2009
    title           : ���ɱ�ֲ�̫��(���ݼ�����).Leon.1994.Directors.Cut.720p.Bluray
    encoder         : Lavf58.45.100
  Duration: 00:00:05.02, bitrate: 1411 kb/s
    Stream #1:0: Audio: pcm_s16le ([1][0][0][0] / 0x0001), 44100 Hz, stereo, s16, 1411 kb/s
Stream mapping:
  Stream #0:0 -> #0:0 (copy)
  Stream #1:0 -> #0:1 (pcm_s16le (native) -> aac (native))
Press [q] to stop, [?] for help
Output #0, mp4, to 'data/6854281e-19ac-4edc-9638-4124a2a22e52.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2mp41
    encoder         : Lavf58.45.100
    Stream #0:0(und): Video: mpeg4 (Simple Profile) (mp4v / 0x7634706D), yuv420p, 1280x688 [SAR 1:1 DAR 80:43], q=2-31, 8417 kb/s, 25 fps, 25 tbr, 12800 tbn, 12800 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1: Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 128 kb/s
    Metadata:
      encoder         : Lavc58.91.100 aac
frame=  122 fps=0.0 q=-1.0 Lsize=    5096kB time=00:00:04.87 bitrate=8561.0kbits/s speed=72.6x    
video:5015kB audio:77kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.087828%
[aac @ 00000192e5913d40] Qavg: 181.360
data/6854281e-19ac-4edc-9638-4124a2a22e52.mp4

Process finished with exit code 0

OK, Finally, the synthesized video address is output .

summary

There's nothing to summarize , When I have time, I'd better put some ffmpeg Order to sort it out .

Share :

        Memory is a way to get together , Letting go is a form of freedom . Don't be sad , Don't worry , The memories of encounter are all good stories .——《 The account of Xia Mu's friend 》

If this article is useful to you , Give me some advice. , thank you !

copyright notice
author[Swordsman a Liang_ ALiang],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202020946495014.html

Random recommended