Last active
August 29, 2015 14:11
-
-
Save AmineChikhaoui/c3fe980bd6d8de45edb3 to your computer and use it in GitHub Desktop.
Script for converting mp4 videos to mp3 using ffmpeg.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python | |
from flask import Flask,request, render_template, make_response, send_file | |
from werkzeug import secure_filename | |
import subprocess | |
import os | |
UPLOAD_FOLDER = 'Bucket/' | |
ALLOWED_EXTENSIONS = set(['mp4','txt', 'jpg', 'jpeg']) | |
app = Flask(__name__) | |
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER | |
# Check if the file passed in the http request is allowed | |
def allowed_file(filename): | |
return '.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS | |
@app.route("/", methods = ['GET','POST']) | |
def toAudio(): | |
# Try catch block for checking whether the upload folder is created or not | |
try: | |
print os.getcwd() | |
os.stat(app.config['UPLOAD_FOLDER']) | |
except: | |
os.mkdir(app.config['UPLOAD_FOLDER']) | |
print "end try catch block" | |
if request.method == 'POST': | |
print "begin process" | |
file = request.files['file'] # gets the file from the http request | |
if file and allowed_file(file.filename): | |
print "begin if" | |
filename = secure_filename(file.filename) | |
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) # save the original mp4 file into the upload folder | |
print "saved" | |
name = os.path.join(app.config['UPLOAD_FOLDER'], filename) # build the path to the original mp4 file | |
new_filename = os.path.splitext(filename)[0] + '.mp3' # name of the destination file (.mp3) | |
print "new filename" | |
# call to the external command ffmpeg | |
sp = subprocess.Popen(['ffmpeg', '-i', os.path.join(app.config['UPLOAD_FOLDER'], filename), new_filename], stdout=subprocess.PIPE) | |
sp.wait(); # wait till the video converting ends | |
# once the mp3 file is created, it will be opened and wrapped in the http response | |
res = open(new_filename, 'rb') | |
raw_res = res.read() | |
response = make_response(raw_res) | |
response.headers['Content-Type'] = "application/octet-stream" | |
response.headers['Content-Disposition']= "inline; filename="+ new_filename | |
return response | |
# if the request method is GET, show an html form to upload the mp4 file | |
return ''' | |
<!DOCTYPE html> | |
<title>Upload</title> | |
<h1>Upload new file</h1> | |
<form action="" method=post enctype=multipart/form-data> | |
<p><input type=file name=file> | |
<input type=submit value=Upload> | |
</form> | |
''' | |
if __name__=="__main__": | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment