[PYTHON] Convert mp4 to mp3 with ffmpeg (thumbnail embedded version)

Added the following functions to Convert mp4 to mp3 with ffmpeg.

I used ffmpeg to cut out thumbnails (artwork).

Eyed3 was used to embed thumbnails (artwork). eyed3 is a tool that can edit mp3 tag information. This time I used it from within the python script. There is also a CLI. python2.7 is required because it does not support python3.

Operating environment

Installation

# ffmpeg
brew install ffmpeg --with-tools

# eyed3
pip install eyed3==0.7.8

Conversion script

ffmpeg_conv_mp3.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# system requirement
    * python 2.7

# install
    $ brew install ffmpeg --with-tools
    $ pip install eyed3==0.7.8
"""

import argparse
import eyed3
from eyed3.id3.frames import ImageFrame
from os import getcwd, path, system, remove
import sys

FFMPEG_MP42MP3_CMD = (
    u'ffmpeg'
    u' -y'
    u' -loglevel warning'
    u' -i "{src_file}"'
    u' -acodec libmp3lame'
    u' -ab 256k'
    u' "{dest_file}"'
)
FFMPEG_THUMBNAIL_CMD = (
    u'ffmpeg'
    u' -y'
    u' -loglevel warning'
    u' -i "{src_file}"'
    u' -ss 5'
    u' -vframes 1'
    u' -f image2'
    u' "{dest_file}"'
)


def rename_filename_ext(src_file, rename_ext, dest_directory):
    name, ext = path.splitext(path.basename(src_file))
    return (name, path.join(dest_directory, name + rename_ext))


def main(src_files, dest_directory):
    for src_file in src_files:
        src_file = path.abspath(src_file).decode('utf-8')
        dest = path.abspath(dest_directory).decode('utf-8')

        title, dest_mp3_file = rename_filename_ext(src_file, u'.mp3', dest)
        title, dest_png_file = rename_filename_ext(src_file, u'.png', dest)

        # mp4 -> mp3 encode
        ffmpeg_cmd = FFMPEG_MP42MP3_CMD.format(
            src_file=src_file,
            dest_file=dest_mp3_file
        )
        print(u'{0} -> {1}'.format(src_file, dest_mp3_file))
        system(ffmpeg_cmd.encode(sys.stdin.encoding))

        #Cut out thumbnail image from mp4
        ffmpeg_cmd = FFMPEG_THUMBNAIL_CMD.format(
            src_file=src_file,
            dest_file=dest_png_file
        )
        system(ffmpeg_cmd.encode(sys.stdin.encoding))

        #Embed thumbnail images in mp3 files
        f = eyed3.load(dest_mp3_file)
        if f.tag is None:
            f.initTag()
        f.tag.title = title
        with open(dest_png_file, 'rb') as dest_png:
            f.tag.images.set(
                ImageFrame.FRONT_COVER,
                dest_png.read(),
                'image/png'
            )
        f.tag.save(encoding='utf-8')

        if path.exists(dest_png_file):
            remove(dest_png_file)


def parse_args():
    parser = argparse.ArgumentParser(
        description=u'Convert mp4 to mp3 with ffmpeg(Thumbnail embedded version)'
    )
    parser.add_argument(
        'source_files',
        metavar='source_file',
        nargs='+',
        help='source files'
    )
    parser.add_argument(
        '--dest',
        metavar='destination_directory',
        nargs='?',
        default=getcwd(),
        help='destination directory (default: current directory)'
    )
    return parser.parse_args()


if __name__ == '__main__':
    args = parse_args()
    main(args.source_files, args.dest)
chmod +x ffmpeg_conv_mp3.py

How to use

Encode "* .mp4" under the "./mp4/in/" directory to mp3 and output to the "./mp4/out/" directory.

ffmpeg_conv_mp3.py ./mp4/in/*.mp4 --dest ./mp4/out/

Recommended Posts

Convert mp4 to mp3 with ffmpeg (thumbnail embedded version)
Convert 202003 to 2020-03 with pandas
Convert video to black and white with ffmpeg + python + opencv
Convert .ipynb to .html (with BatchFile)
Convert wma to mp3 on Mac
Convert list to DataFrame with python
MP3 to WAV conversion with Python
Convert sentences to vectors with gensim
Convert PDF to image with ImageMagick
For the time being, I want to convert files with ffmpeg !!
Convert memo at once with Python 2to3
Convert from PDF to CSV with pdfplumber
Let's develop something close to embedded with TDD ~ Key input detection version ~
Convert character strings to features with RoBERTa
Convert Excel data to JSON with python
Convert Hiragana to Romaji with Python (Beta)
Convert FX 1-minute data to 5-minute data with Python
Convert PDF files to PNG files with GIMP
Convert array (struct) to json with golang
Convert HEIC files to PNG files with Python
Convert Chinese numerals to Arabic numerals with Python
Sample to convert image to Wavelet with Python
Convert DICOM to PNG with Ascending and Descending
Convert data with shape (number of data, 1) to (number of data,) with numpy.
Convert PDF to image (JPEG / PNG) with Python
Convert PDFs to images in bulk with Python
Convert svg file to png / ico with Python
Convert Windows epoch values to date with python
Easily convert Jupyter Notebooks to blogs with fastpages
[Improved version] Script to monitor CPU with Python
How to convert (32,32,3) to 4D tensor (1,32,32,1) with ndarray type
Convert strings to character-by-character list format with python
Convert to HSV
I want to convert an image to WebP with lollipop
How to convert / restore a string with [] in python
Display embedded images of mp3 and flac with mutagen
0 Convert unfilled date to datetime type with regular expression
Convert a text file with hexadecimal values to a binary file
How to convert horizontally held data to vertically held data with pandas
How to convert a class object to a dictionary with SQLAlchemy
How to measure mp3 file playback time with python
Convert the image in .zip to PDF with Python
How to convert JSON file to CSV file with Python Pandas
PyInstaller memorandum Convert Python [.py] to [.exe] with 2 lines
Convert numeric variables to categorical with thresholds in pandas