Java Web uses ffmpeg for video transcoding, video screenshots, and javaffmpeg

Source: Internet
Author: User
Tags flv file savemedia

Java Web uses ffmpeg for Video Transcoding and video, javaffmpeg

Reposted from: [http://www.cnblogs.com/dennisit/archive/2013/02/16/2913287.html]

Player.

The multimedia video processing tool FFmpeg has powerful functions including video collection, video format conversion, video capturing, and watermarking.

The ffmpeg video acquisition function is very powerful. It can not only collect video capture card or USB camera images, but also screen recording. It also supports transmitting videos to RTSP-enabled streaming media servers in RTP mode, supports live applications.

1. supported formats

Formats that can be parsed by ffmpeg: (asx, asf, mpg, wmv, 3gp, mp4, mov, avi, and flv)

2. Unsupported format

For files that cannot be parsed by ffmpeg (wmv9, rm, rmvb, etc.), you can use other tools (mencoder) to convert to avi (which can be parsed by ffmpeg.

The instance transcodes the uploaded video to the flv format, which is supported by ffmpeg. Therefore, the ffmpeg video processing tool is required in our instance.

 

DatabaseMySQL5.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 (50) not null comment 'video name', src varchar (200) not null comment 'video storage address', picture varchar (200) not null comment 'video', descript varchar (400) comment 'video description', uptime varchar (40) comment 'upload Time'); desc tb_media;

Project Structure:

Upload video Interface Design

When uploading files, the enctype attribute value in Form must be "multipart/form-data". The module interface design is as follows:

Description of enctype attribute values

Application/x-www-form-urlencoded

Form data is encoded as name/value pairs, which are standard encoding formats

Multipart/form-data

Form data is encoded as a message. Each control on the page corresponds to a part of the message.

Text/plain

Form data is encoded in plain text, excluding characters in any control format

 

Business Interface Definition

Interface-oriented programming. The interface defines the system function module. this makes it easy to clarify the business. At the same time, the interface object must be created by the object that implements this interface. in this way, some business omissions in the encoding are avoided, and the scalability is also enhanced.

 

Package com. webapp. dao; import java. util. list; import com. webapp. entity. media;/***** MediaDao. java ** @ version: 1.1 ** @ author: su Ruian <a href = "mailto: DennisIT@163.com"> send mail </a> ** @ since: 1.0 Creation Time: 10:19:54 ** TODO: interface MediaDao. java is used... **/public interface MediaDao {/*** Video Transcoding * @ param ffmpegPath storage path of the transcoding tool * @ param upFilePath is used to specify the file to be converted into a format, the file storage path of the video source file * @ param codcFilePath after conversion * @ param mediaPicPath save path * @ return * @ throws Exception */public boolean executeCodecs (String ffmpegPath, String upFilePath, string codcFilePath, String mediaPicPath) throws Exception;/*** save the file * @ param media * @ return * @ throws Exception */public boolean saveMedia (Media media) throws Exception; /*** query the number of all records in the local database * @ return * @ throws Exception */public int getAllMediaCount () throws Exception; /*** paging query * @ param firstResult * @ param maxResult * @ return */public List <Media> queryALlMedia (int firstResult, int maxResult) throws Exception; /*** query video by Id * @ param id * @ return * @ throws Exception */public Media queryMediaById (int id) throws Exception ;}

 

The implementation of the interface, which lists the ffmpeg Video Transcoding and modules.

 

/*** Video Transcoding ** @ param ffmpegPath: storage path of the transcoding tool * @ param upFilePath: Specifies the file to be converted, the file storage path of the video source file * @ param codcFilePath after conversion * @ param mediaPicPath save path * @ return * @ throws Exception */public boolean executeCodecs (String ffmpegPath, String upFilePath, string codcFilePath, String mediaPicPath) throws Exception {// create a List set to save the command List to convert the video file to the flv format <String> convert = new ArrayList <String> (); convert. add (ffm PegPath); // Add the Conversion Tool Path convert. add ("-I"); // add the parameter "-I", which specifies the file to be converted to convert. add (upFilePath); // add the path of the video file to be converted to convert. add ("-qscale"); // specify the conversion quality convert. add ("6"); convert. add ("-AB"); // sets the audio bit rate convert. add ("64"); convert. add ("-ac"); // sets the number of audio channels convert. add ("2"); convert. add ("-ar"); // sets the audio sampling frequency convert. add ("22050"); convert. add ("-r"); // sets the frame rate convert. add ("24"); convert. add ("-y"); // add the parameter "-y", which specifies that the existing file will be overwritten. Convert. add (codcFilePath); // create a List set to save the command List <String> cutpic = new ArrayList <String> (); cutpic. add (ffmpegPath); cutpic. add ("-I"); cutpic. add (upFilePath); // same as above (the specified file can be a file converted to the flv format or 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 truncation. add ("17"); // the start time is 17th seconds. add ("-t"); // add the parameter "-t", which specifies the duration of cutpic. add ("0. 001 "); // Add a duration of 1 millisecond cutpic. add ("-s"); // add the parameter "-s", which specifies the captured image size cutpic. add ("800*280"); // the size of the captured image is 350*240 cutpic. add (mediaPicPath); // add the Save path of the captured image boolean mark = true; ProcessBuilder builder = new ProcessBuilder (); try {builder. command (convert); builder. redirectErrorStream (true); builder. start (); builder. command (cutpic); builder. redirectErrorStream (true); // if this attribute is true, any The error output generated by subsequent sub-processes will be merged with the standard output. // both of them can be read using the Process. getInputStream () method. This makes it easier to build associated error messages and corresponding outputs. 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 provided directly when necessary.

Because there are too many new objects, it is unnecessary to waste resources. Therefore, the factory adopts the singleton mode, which is a private structure and provides externally accessible methods.

 

Package com. webapp. dao; import com. webapp. dao. impl. mediaDaoImpl;/***** DaoFactory. java ** @ version: 1.1 ** @ author: su Ruian <a href = "mailto: DennisIT@163.com"> send mail </a> ** @ since: 1.0 Creation Time: 02:18:51 ** TODO: class DaoFactory. java is used... **/public class DaoFactory {// factory mode, producing Dao objects, interface-oriented programming, and returning the object private static DaoFactory daoFactory = new DaoFactory () that implements the definition of the business interface (); // Singleton design mode, private structure, unique interface for obtaining created objects externally, private DaoFactory () {} public static DaoFactory getInstance () {return daoFactory ;} public static MediaDao getMediaDao () {return new MediaDaoImpl ();}}

 

The view submits the request to the controller. The controller analyzes the Request Parameters and processes the corresponding service call. The servlet controller code is as follows:

 

Package com. webapp. service; import java. io. file; import java. io. IOException; import java. io. printWriter; 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. fil Eupload. disk. diskFileItemFactory; import org. apache. commons. fileupload. servlet. servletFileUpload; import com. webapp. dao. daoFactory; import com. webapp. dao. mediaDao; import com. webapp. entity. media; import com. webapp. util. dateTimeUtil;/***** MediaService. java ** @ version: 1.1 ** @ author: su Ruian <a href = "mailto: DennisIT@163.com"> send mail </a> ** @ since: 1.0 Creation Time: 02:24:47 ** TODO: class MediaS Ervice. java is used... **/public class MediaService extends HttpServlet {public void doGet (HttpServletRequest request, response) throws ServletException, IOException {doPost (request, response);} public void doPost (HttpServletRequest request, httpServletResponse response) throws ServletException, IOException {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) {// some default configuration DiskFileItemFactory factory = new DiskFileItemFactory () when parsing is provided; // create a parser to analyze InputStream, the parser encapsulates the analysis results into a collection of FileItem objects // A FileItem object corresponds to a form field ServletFileUpload sfu = new ServletFileUpload (factory); try {Media media = new Media (); List <FileItem> items = sfu. parseRequest (request); boolean flag = false; // the mark for (int I = 0; I <items. size (); I ++) {FileItem item = items. get (I); // determine whether to upload a file or a common form field if (item. isFormField () {// isFormField () is true, indicating that this is not a file upload form field // String paramName = item in a common form field. getFieldName ();/* String paramValue = item. getString (); System. out. println ("parameter name:" + paramName + ", corresponding parameter value:" + p AramValue); */if (paramName. equals ("title") {media. setTitle (new String (item. getString (). getBytes ("ISO8859-1"), "UTF-8");} if (paramName. equals ("descript") {media. setDescript (new String (item. getString (). getBytes ("ISO8859-1"), "UTF-8");} else {// Upload File // System. out. println ("Upload File" + item. getName (); ServletContext sctx = this. getServletContext (); // get the path of the saved file String basePath = sctx. getRealPath ("vide OS "); // get the file name String fileUrl = item. getName (); // in some operating systems, item. the getName () method returns the complete name of the file, including the path String fileType = fileUrl. substring (fileUrl. lastIndexOf (". "); // format of the truncated file // custom method to generate the file name String serialName = String. valueOf (System. currentTimeMillis (); // File to be transcoded 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 maximum file size allowed by the system is 500 MB </li> ";} String codcFilePath = basePath +"/"+ serialName + ". flv "; // set the storage path of the File converted to the flv format. String mediaPicPath = basePath +"/images "+ File. separator + serialName + ". jpg "; // set the storage path of the uploaded video // the path of the configured Conversion Tool (ffmpeg.exe) String ffmpegPath = getServletContext (). getRealPath ("/tools/ffmpeg.exe"); media. setSrc ("videos/" + serialName + ". flv "); media. setPicture ("videos/images/" + serialNa Me + ". jpg "); media. setUptime (DateTimeUtil. getYMDHMSFormat (); // transcoding flag = mediaDao.exe cuteCodecs (ffmpegPath, uploadFile. getAbsolutePath (), codcFilePath, mediaPicPath) ;}} if (flag) {// transcoding successful, add this video information to the data table mediaDao. saveMedia (media); message = "<li> uploaded successfully! </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 );}}}

 

You can search by page to display the latest top5 and the homepage. The corresponding special effects can be implemented using JS.

 

 

 

 

The related 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://www.w3.org/TR/html4/loose.dtd">  

All the images displayed on the home page are request links with IDs. The images are the images pulled during video transcoding. You can click an image to send a video playback request,

Shows the video playback page effect.

 

The video playback page must be embedded with a flash player.

The Code is as follows:

<! -- Embedded flash player --> <td align = "center" width = "455"> <object width = "452" height = "339" classid = "clsid: d27CDB6E-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>

Instructions:

<Object> element: loads ActiveX controls. The classid attribute specifies the ActiveX space used by the browser. the classid value must be "clsid: D27CDB6E-AE6D-11cf-96B8-444553540000" because the player created in Flash is used to play the video file"

 

<Param> element, value‑defined specifies the video file used by flash. A file parameter is passed to the player.swf player in the value‑value. This parameter specifies the path of the video to be played.

The <embed> element and src attribute are also used to load a video. They are exactly the same as the value attribute value marked by <param>.


Use ffmpegexe video in java

Encoding: The format parameters are different,
 
Java calls ffmpeg to upload video to Convert flv and

Xuexi
 

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: info-contact@alibabacloud.com 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.