Home > Software design >  How would I pass a video file to FFMPEG in Flask in order to convert it to MP4?
How would I pass a video file to FFMPEG in Flask in order to convert it to MP4?

Time:08-30

I'm building a video sharing site and everything has been going smoothly so far until this. I want to pass the video file I'm uploading to FFMPEG to convert it to MP4 and to a specific resolution (480p). I've been spending over an hour trying to figure out how to do this to no success. Could anybody help? Here is my code:

Code for uploading:

@app.route("/upload", methods=["GET", "POST"])
@login_required
def upload():
    if request.method == "POST":
        if "video" not in request.files:
            print("error whole uploading")
            return redirect(request.url)
        video = request.files["video"]
        if video.filename == "":
            print("no file uplaoded")
            return redirect(request.url)
        if video and filename_check(video.filename, type="video"):
            filename = secure_filename(video.filename)
            file_path = os.path.join(app.config["UPLOAD_FOLDER"], filename)
            print(file_path)
            video.save(file_path)

            print("upload success")

            return redirect(request.url)
            
    return render_template("upload.html")

init.py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import os

app = Flask(__name__)

UPLOAD_FOLDER = os.path.join(app.root_path, 'uploads')
ALLOWED_VIDEO_EXTENTIONS = {"mp4", "webm"}
ALLOWED_IMAGE_EXTENTIONS = {"mp4", "webm"}

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def filename_check(filename, type):
    if type == "video":
        return "." in filename and \
            filename.rsplit(".", 1)[1].lower() in ALLOWED_VIDEO_EXTENTIONS
    else:
        return "." in filename and \
            filename.rsplit(".", 1)[1].lower() in ALLOWED_IMAGE_EXTENTIONS

app.config["SECRET_KEY"] = "newtube"  # do not reveal to ANYONE dumbass

app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.db"
db = SQLAlchemy(app)

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "signin"

import newtube.views

CodePudding user response:

After saved video, using pydub to convert it to MP4 format:

from pydub import AudioSegment
def convert_to_mp4(file_path):
  tmp_audio = AudioSegment.from_file(file_path)
  tmp_audio.export(file_path, format='wav', parameters=["-vf", "scale=-1:480"])
  return file_path

CodePudding user response:

I've found a solution using MoviePy:

from moviepy.editor import *
...
converted = VideoFileClip(file_path)
converted.resize(width=480)
converted.write_videofile(file_path)
  • Related