Use FFmpeg to implement video transcoding and video capture in the Java Web

Source: Internet
Author: User
Tags save file java web flv file savemedia

Reprinted from: [Http://]

The video website provides the online video playback function, plays the FLV format file, it is the Flash animation file, can play the file through the Flash production player. The player.swf player that is produced in the project.

The Multimedia video processing tool FFmpeg has the very powerful function including the video collection function, the video format conversion, the video capture picture, gives the video watermark and so on.

FFmpeg video capture is very powerful, not only can capture video capture card or USB camera image, but also for screen recording, but also support the RTP way to stream the video to the support of RTSP streaming server, support the live application.

1. Formats that can be supported

FFmpeg can parse the format: (asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv, etc.)

2. Formats that cannot be supported

For FFmpeg cannot parse the file format (WMV9,RM,RMVB, etc.), you can first use another tool (MEncoder) to convert to AVI (FFmpeg can parse) format.

The instance is to upload the video transcoding to FLV format, the format ffmpeg support, so we need ffmpeg video processing tool in our instance.

Database MySQL5.5

Database scripts required by the instance

Drop database if exists db_mediaplayer;create database db_mediaplayer;use db_mediaplayer;create table Tb_media (    ID int NOT NULL PRIMARY key auto_increment comment ' primary key ',     title varchar (+) NOT null comment ' video name ',    src varchar (200 ) NOT NULL comment ' video storage address ',    picture varchar (+) NOT null comment ' video ',    descript varchar comment ' video description ', C7/>uptime varchar (+) Comment ' upload time ');d ESC Tb_media;

Project Structure diagram:

Upload Video Interface design

When uploading a file, the Enctype attribute value in the form form must be "Multipart/form-data". Module interface design such as:

Enctype Property Value Description


The form data is encoded as a name/value pair, which is the standard encoding format


The form data is encoded as a message, and each control on the page corresponds to a part of the message


The form data is encoded in plain text, with no characters in any control format

Business Interface Definition

Interface-oriented programming, the interface defines the system function module. This facilitates the clearing of the business, while the object of the interface must be created by the object that implements the interface. This avoids some of the business omissions in the code, and the extensibility is enhanced.

Package Com.webapp.dao;import java.util.list;import;/** * * * * @version: 1.1 * * @author: Sujonin <a href= "mailto:[email protected" "> Send mail </a> * * @since: 1.0 Create Time: 2013-2-07 a.m. 10:19:54 * * Todo:interface is used for ... * */public interface Me Diadao {/** * video transcoding * @param ffmpegpath transcoding Tool Storage Path * @param upfilepath used to specify the file to be converted to, the video source file * @param codcfilepath format converted file Save path * @param mediapicpath Save path * @return * @throws Exception */Pub Lic boolean executecodecs (String ffmpegpath,string upfilepath, String Codcfilepath, String mediapicpath) throws        Exception; /** * Save File * @param media * @return * @throws Exception * * Public boolean Savemedia (Media media) thr    oWS Exception;   /** * Query the number of records in the local library * @return * @throws Exception */public int getallmediacount () throws Exception;     /** * Paged Query * @param firstresult * @param maxresult * @return * * Public list<media> que        Ryallmedia (int firstresult, int maxresult) throws Exception; /** * Search video by ID * @param ID * @return * @throws Exception */public Media Querymediabyid (int id) thro WS Exception;}

Interface implementation, listed here FFmpeg video transcoding and module

    /** * Video transcoding * @param ffmpegpath transcoding Tool Storage Path * @param upfilepath used to specify the file to be converted, the video source file to be @param CODCF Ilepath format converted file Save path * @param mediapicpath Save path * @return * @throws Exception */Public Boolean Executecodecs (String Ffmpegpath, String Upfilepath, String Codcfilepath, String mediapicpath) throws Exception        {//Create a List collection to save the Convert video file to FLV format command list<string> convert = new arraylist<string> (); Convert.add (Ffmpegpath); Add Conversion Tool Path Convert.add ("-i"); Add the parameter "-i", which specifies the file to convert Convert.add (Upfilepath);     Add the path to the video file you want to convert Convert.add ("-qscale");        Specifies the quality of the conversion convert.add ("6");        Convert.add ("-ab");        Set the audio bitrate Convert.add ("64");        Convert.add ("-ac");        Set the number of channels Convert.add ("2");        Convert.add ("-ar");        Sets the sampling frequency of the sound Convert.add ("22050");        Convert.add ("-R");        Set the frame frequency convert.add ("24"); Convert.add ("-y"); Add Parameter "-Y ", this parameter specifies that the existing file Convert.add (Codcfilepath) will be overwritten;        Create a List collection to hold commands for capturing pictures from video list<string> cutpic = new arraylist<string> ();        Cutpic.add (Ffmpegpath);        Cutpic.add ("-i"); Cutpic.add (Upfilepath);        Ibid. (The specified file can be a file converted to FLV format, or it can be a converted flv file) cutpic.add ("-y");        Cutpic.add ("-f");        Cutpic.add ("Image2"); Cutpic.add ("-ss"); Add the parameter "-SS", which specifies the starting time of the Intercept Cutpic.add ("17"); Add a start time of 17th seconds Cutpic.add ("-t"); Add the parameter "-T", which specifies the duration cutpic.add ("0.001"); Add duration is 1 ms Cutpic.add ("-S"); Add the parameter "-S", which specifies the captured picture size Cutpic.add ("800*280"); Add the captured image size to 350*240 cutpic.add (Mediapicpath);        Adds a saved path to the captured picture, Boolean Mark = true;        Processbuilder builder = new Processbuilder ();            try {builder.command (convert);            Builder.redirecterrorstream (TRUE);                        Builder.start ();            Builder.command (Cutpic);       Builder.redirecterrorstream (TRUE);     If this property is true, any error output generated by subsequent child processes started by the start () method of this object will be merged with the standard output,//So both can be read using the Process.getinputstream () method.        This makes associating error messages and corresponding outputs easier builder.start ();            } catch (Exception e) {mark = false;            System.out.println (e);        E.printstacktrace ();    } return mark; }

There may be multiple modules in the system, the business DAO of these modules can be managed by the factory and can be provided directly when needed.

Because if the object is new too much, it will unnecessarily waste resources. So the factory, using a singleton mode, private structure, to provide external access to the method can be.

Package Com.webapp.dao;import com.webapp.dao.impl.mediadaoimpl;/** * *     * *  @version: 1.1 *   *  @author  : Sujonin    <a href= "mailto:[email protected" "> Send mail </a> *     *  @since     : 1.0        Creation Time:    2013-2-07        pm 02:18:51 *      *  TODO     :    class is used for ... * /public class Daofactory {//Factory mode, production of DAO object, interface-oriented programming, return object implementing business interface definition        private static daofactory daofactory = new Daofactory ();        Singleton design mode, private construction, external provides a unique interface to get the created object,    private Daofactory () {            } public        static Daofactory getinstance () {        return daofactory;    }        public static Mediadao Getmediadao () {        return new Mediadaoimpl ();}    }

The view submits the request, gives the controller, the controller analyzes the request parameter, and makes the corresponding business call processing. servlet controller related code is as follows

Package Com.webapp.service;import;import;import;import Java.util.list;import Javax.servlet.servletcontext;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.commons.fileupload.fileitem;import Org.apache.commons.fileupload.disk.diskfileitemfactory;import Org.apache.commons.fileupload.servlet.servletfileupload;import Com.webapp.dao.daofactory;import  Com.webapp.dao.mediadao;import;import com.webapp.util.datetimeutil;/** * * * * @version: 1.1 * * @author: Sujonin <a href= "mailto:[email protected" "> Send mail </ a> * * @since: 1.0 created: 2013-2-08 pm 02:24:47 * * Todo:class MEDIASERVICE.JAV A is used for ... * */public class Mediaservice extends HttpServlet {public void doget (HttpServletRequest requeSt, httpservletresponse response) throws Servletexception, IOException {doPost (request, response); } public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioex        ception {PrintWriter out = Response.getwriter ();        Mediadao Mediadao = Daofactory.getmediadao ();                String message = "";        String uri = Request.getrequesturi ();                String path = uri.substring (Uri.lastindexof ("/"), Uri.lastindexof (".")); if ("/uploadfile". Equals (path)) {//provides some default configuration when parsing diskfileitemfactory factory = new Diskfileitemfactory                        (); Create a parser that parses InputStream, which encapsulates the results of the analysis into a collection of Fileitem objects//A Fileitem object corresponding to a form field servletfileupload SFU =                    New Servletfileupload (Factory);                try {Media media = new Media ();                list<fileitem> items = sfu.parserequest (request); Boolean flag =False                    Transcoding success or not marks for (int i=0; i<items.size (); i++) {Fileitem item = items.get (i);                        To distinguish between uploading a file or a normal form field if (Item.isformfield ()) {//isformfield () is true, indicating that this is not a File Upload form field                        Normal form field String paramname = Item.getfieldname ();                            /* String paramvalue = item.getstring ();                        SYSTEM.OUT.PRINTLN ("Parameter name is:" + paramname + ", the corresponding parameter value is:" + paramvalue); */if (paramname.equals ("title")) {Media.settitle (new String (Item.getstri                        Ng (). GetBytes ("Iso8859-1"), "UTF-8")); } if (Paramname.equals ("descript")) {Media.setdescript (new String (                        Tstring (). GetBytes ("Iso8859-1"), "UTF-8"));    }}else{//upload file                    System.out.println ("Upload file" + item.getname ());                        ServletContext sctx = This.getservletcontext ();                        Get the path to save the file String BasePath = Sctx.getrealpath ("Videos");                        Get filename String fileurl= item.getname (); On some operating systems, the Item.getname () method returns the full name of the file, which includes the path String FileType = fileurl.substring (fileurl.lastindexof (".")); Intercept file format//custom method to generate file name String Serialname = string.valueof (system.currenttimem                        Illis ());                        Files to be transcoded file UploadFile = new file (basepath+ "/temp/" +serialname + fileType);                                                Item.write (UploadFile); if (Item.getsize () >500*1024*1024) {message = "<li> upload failed!                        The file you uploaded is too large, the system allows maximum file 500m</li> ";                    }    String Codcfilepath = BasePath + "/" + Serialname + ". flv"; Sets the save path of the file after conversion to FLV format String Mediapicpath = BasePath + "/images" +file.separator+ serialname + ". jpg    "; Set the save path for uploaded videos//Get the storage path for the configured conversion tool (Ffmpeg.exe) String F                                                Fmpegpath = Getservletcontext (). Getrealpath ("/tools/ffmpeg.exe");                        MEDIA.SETSRC ("videos/" + Serialname + ". flv");                        Media.setpicture ("videos/images/" +serialname + ". jpg");                                                Media.setuptime (Datetimeutil.getymdhmsformat ()); Transcode flag = Mediadao.executecodecs (Ffmpegpath, Uploadfile.getabsolutepath ()                    , Codcfilepath, Mediapicpath); }} if (flag) {//transcoding succeeds, add the video information to the datasheet Mediadao.savemedia (m            Edia);        message = "<li> upload successful!</li>";                } request.setattribute ("message", message);                                        Request.getrequestdispatcher ("media_upload.jsp"). Forward (Request,response);                } catch (Exception e) {e.printstacktrace ();            throw new Servletexception (e);            }} if ("/queryall". Equals (Path)) {list<media> medialist;                try {medialist = Mediadao.queryallmedia (0,5);                Request.setattribute ("Medialist", medialist);            Request.getrequestdispatcher ("media_list.jsp"). Forward (request, response);            } catch (Exception e) {e.printstacktrace ();            }} if ("/play". Equals (Path)) {String idstr = Request.getparameter ("id");            int mediaid =-1;            Media media = null; if (NULL!=IDSTR) {MediAId = Integer.parseint (IDSTR);            } try {media = Mediadao.querymediabyid (MediaID);            } catch (Exception e) {e.printstacktrace ();            } request.setattribute ("Media", media);        Request.getrequestdispatcher ("media_player.jsp"). Forward (request, response); }    }    }

Can be found by paging, display the latest TOP5, display to the first page. The corresponding effects can be implemented using JS.

The relevant code is as follows:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><%@ page import=" com.webapp.entity.* "%><%@ page import=" Java.util.    * "%><% String Path = Request.getcontextpath (); String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://" >

The images displayed on the homepage are link requests with IDs. The picture is the picture that was pulled to the video transcoding process. Click the image to send a video request to play,

The video playback page works as shown.

Video playback page needs to embed Flash player in the page

The code is as follows:

<!--embedded Flash Player--><TD align= "center" width= "455" >    <object width= "452" height= "339" classid= "clsid :D 27cdb6e-ae6d-11cf-96b8-444553540000 ">    <param name=" movie "        value=" <%=basepath%>tools/ PLAYER.SWF?FILENAME=<%=BASEPATH%><%=MEDIA.GETSRC ()%> "/>    <embed        src=" <%=basePath% >TOOLS/PLAYER.SWF?FILENAME=<%=BASEPATH%><%=MEDIA.GETSRC ()%> "        width=" 98% "height=" 90% "> </embed>     </object></td>

Related instructions:

<object> element, loading the ActiveX control, the ClassID property specifies the ActiveX space used by the browser. Because the video file is played using a flash-produced player, the value of ClassID must be "clsid:d 27cdb6e-ae6d-11cf-96b8-444553540000 "

The <param> element, the Value property, specifies the video file to be loaded. The video player that was created by Flash is used in the instance. A file parameter was passed to the player.swf player in the Value property values. This parameter specifies the path of the video to play.

The <embed> element, the SRC attribute is also used to load the movie, with the same functionality as the value of the <param> tag property.

The Java Web uses FFmpeg to implement video transcoding, video

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.