视频文件的上传和编辑

来源:互联网 发布:百度云盘mac破解补丁 编辑:程序博客网 时间:2024/05/17 02:34

视频文件的上传和编辑

视频上传和剪辑页面<div id="picker">上传文件</div><div id="video"></div><div>开始时间</div><input type="text" id="start_time"/><div>结束时间</div><input type="text" id="end_time"/><button type="button" onclick="editMusic()" >剪辑</button><link href="$path/js/webuploader-0.1.5/webuploader.css" rel="stylesheet" type="text/css"/><script src="$path/js/webuploader-0.1.5/webuploader.min.js"></script><script type="text/javascript">$(document).ready(function(e) {    // 初始化Web Uploader    var uploader = WebUploader.create({        // 选完文件后,是否自动上传。        auto: true,        // swf文件路径        swf:  '$!path/js/webuploader-0.1.5/Uploader.swf',        // 文件接收服务端。        server: '$!path/text/uploadvideo',        // 内部根据当前运行是创建,可能是input元素,也可能是flash.        pick: '#picker',        fileVal:'Filedata',        //同一文件是否可以重复上传        duplicate :true,        // 只允许选择图片文件。        accept: {            title: 'video',            extensions: 'mp4,AVI,RM,WMV,ASF',            mimeTypes: 'video/*'        }    });    //上传过程中    uploader.on('uploadProgress',function( file, percentage ) {        $(".bs-example-modal-sm").modal("show");    });    //上传结束    uploader.on( 'uploadComplete', function( file ) {        $(".bs-example-modal-sm").modal("hide");;    });    // 完成上传完了,成功或者失败,先删除进度条。    uploader.on( 'uploadSuccess', function(file,resp) {        var url = '$!path/' + resp.url;        var video = '<video src="'+url+'" controls="controls"></video>';        var input = '<input id="video_path" name="video_path" value="'+resp.url+'" type="hidden">';        $("#video").html(video+input);    });});function editMusic(){    var start_time = $("#start_time").val();    var end_time = $("#end_time").val();    var video_path = $("#video_path").val();    $.ajax({        type:'post',        data:{startTime:start_time,endTime:end_time,videoPath:video_path},        url:'$path/text/editvideo',        success:function(date){            if(date==1){                alert("剪辑成功");                          }        }    });}</script>视频上传代码/*** 上传视频文件* @param inv* @param model* @param Filedata* @return*/@Post("uploadvideo")public Object uploadvideo(Invocation inv, Model model, MultipartFile Filedata){    String uploadDir = config.getString("upload.video");    int maxDirCount = config.getInt("upload.maxDirCount", 100);    HashMap<String,Object> map = uploadVideo(inv, Filedata, uploadDir, maxDirCount);    model.add("result", map);    return "result.json";}public static HashMap<String,Object> uploadVideo(Invocation inv, MultipartFile Filedata,        String uploadDir,Integer maxDirCount){    String urls = new String();    String url = null;    //Filedata-上传文件;uploadDir-上传路径;    String urlDir = uploadDir;    uploadDir = inv.getServletContext().getRealPath(uploadDir);    long tmp = System.currentTimeMillis();    long dirName = (tmp % new Long(maxDirCount));    urlDir = urlDir + "/" + dirName;    File dir = new File(uploadDir, String.valueOf(dirName));    if (!dir.exists()) {        dir.mkdirs();    }    String extName = FilenameUtils.getExtension(Filedata            .getOriginalFilename());    if (StringUtils.isEmpty(extName)) {        String type = Filedata.getContentType();        extName = MimeTypes.getExtension(type);        extName = StringUtils.substring(extName, 1);    }    String mainFileName = FilenameUtils.getBaseName(Filedata            .getOriginalFilename());    String fileName = mainFileName + "." + extName;    File file = new File(dir, fileName);    String path = urlDir + "/" + fileName;    try {        Filedata.transferTo(file);        Thumbnails.of(file);        urls = path;        url = ArrayUtils.toString(urls);        url = StringUtils.removeStart(url, "{");        url = StringUtils.removeEnd(url, "}");    } catch (Exception e) {        e.printStackTrace(System.err);    }    HashMap<String,Object> map = new HashMap<String,Object>();    map.put("url", url);    return map;}视频剪辑代码/*** 剪辑视频文件* @param inv* @param model* @param videoPath* @param startTime* @param endTime* @return*/@Post("editvideo")public Object editVideo(Invocation inv, Model model,String videoPath,String startTime,String endTime){    videoPath = inv.getServletContext().getRealPath(videoPath);    if(!checkFile(videoPath)){        model.add("result", "剪辑文件不存在");        return "result.json";    }    String outfile = config.getString("upload.video");    outfile = inv.getServletContext().getRealPath(outfile);    Timestamp timestamp = new Timestamp((new Date()).getTime());    DateFormat dft = new SimpleDateFormat("yyyyMM");    outfile = outfile + File.separator + dft.format(timestamp);    File file = new File(outfile);    if(!file.exists()){        file.mkdirs();    }    outfile = outfile + File.separator;    int start = Integer.valueOf(startTime);    int end = Integer.valueOf(endTime);    int duration = end - start;    String result = cutVideo("E:\\ffmpeg-20170425-b4330a0-win32-static\\ffmpeg-20170425-b4330a0-win32-static\\bin\\ffmpeg.exe",             videoPath, startTime, duration+"", outfile);    result = result.split("web")[result.split("web").length-1];    model.add("result", result);    return "result.json";}/** * 开始对文件进行编辑处理 * @param osNames * @param file      源文件地址 * @param startTime     开始时间 * @param duration      截取的时间长度 * @param outPutPath    输出文件地址 * @return */private static String cutVideo(String osNames, String file, String startTime, String duration, String outPutPath) {      //判断文件类型    int type = checkContentType(file);      String status = null;      if (type == 0) {          status = processVideo(osNames, ".mp4", file, startTime, duration, "640x480", outPutPath);//进行视频编辑    }else if(type == 8){        status = processAudio(osNames ,"_radio.mp3", file, startTime, duration, null, outPutPath);//进行音频编辑    }    return status;  }/** * 0 支持的视频文件 * 1 不支持 * 8 支持的音频文件 * 9 其他 * 暂列部分支持的文件类型 * @return */private static int checkContentType(String file) {      String type = file.substring(file.lastIndexOf(".") + 1, file.length())              .toLowerCase();      if (type.equals("avi")) {          return 0;      } else if (type.equals("wmv")) {          return 0;      } else if (type.equals("3gp")) {          return 0;      } else if (type.equals("mov")) {          return 0;      } else if (type.equals("mp4")) {          return 0;      } else if (type.equals("asf")) {          return 0;      } else if (type.equals("flv")) {          return 0;      } else if (type.equals("mp3")) {          return 8;      } else if (type.equals("wav")) {          return 8;      }     // 可调用其他工具进行转码    else if (type.equals("wmv9")) {          return 1;      } else if (type.equals("rm")) {          return 1;      } else if (type.equals("rmvb")) {          return 1;      }     return 9;  }/** * 处理视频文件 * @param oldfilepath * @return */private static String processVideo(String osNames, String newFileName, String oldFilePath,         String startTime, String duration, String resolution, String outPutPath ) {      if (!checkFile(oldFilePath)) {          System.out.println(oldFilePath + " 文件不存在");          return null;      }      List<String> commend = editingParameter(osNames, newFileName, oldFilePath, startTime, duration, resolution, outPutPath);    return runClip(commend);}/** *  * 剪辑文件  * @param commend  * @param newFileName  新文件名称 * @param oldFilePath  源文件地址 * @param saveName           保存文件名称前缀 * @param startTime           剪辑开始时间   形式 00:00:00.000/00:00:00/0 * @param duration            剪辑持续时长 * @param resolution   分辨率   EX:640x480 * @return */private static List<String> editingParameter(String osNames, String newFilePath, String oldFilePath        , String startTime, String duration, String resolution, String outPutPath){    List<String> commend = new ArrayList<String>();    commend.add(osNames);      commend.add("-y");           //是否覆盖    commend.add("-ss");          //截取开始时间    commend.add(startTime);         commend.add("-t");           //截取时长    commend.add(duration);    commend.add("-i");           //源文件地址    commend.add(oldFilePath);      //同时使用会导致-s无效    commend.add("-vcodec");   //强制使用codec编解码方式。如果用copy表示原始编解码数据必须被拷贝。    commend.add("copy"); //        commend.add("-f");        //        commend.add("mpeg");      if(null != resolution){         commend.add("-s");          //分辨率调整         commend.add(resolution);      }    commend.add(outPutPath + getRandomName() + newFilePath);      return commend;}/*** 运行程序 * @param commend * @return */private static String runClip(List<String> commend){    try {          ProcessBuilder builder = new ProcessBuilder(commend);          builder.command(commend);          Process pro = builder.start();          doWaitFor(pro);        String newFileName = commend.get(commend.size()-1);        return newFileName;      } catch (Exception e) {         e.printStackTrace();         return null;      }  }/** * 执行完成 * @param p * @return */private static int doWaitFor(Process p) {      InputStream in = null;    InputStream err = null;    int exitValue = -1;    try {        System.out.println("comeing");        in = p.getInputStream();        err = p.getErrorStream();        boolean finished = false;        while (!finished) {            try {                while (in.available() > 0) {                    Character c = new Character((char) in.read());                    System.out.print(c);                }                while (err.available() > 0) {                    Character c = new Character((char) err.read());                    System.out.print(c);                }                exitValue = p.exitValue();                finished = true;            } catch (IllegalThreadStateException e) {    //                  Thread.currentThread().sleep(500);            }        }    } catch (Exception e) {        System.err.println("doWaitFor();: unexpected exception - "                + e.getMessage());    } finally {        try {            if (in != null) {                in.close();            }        } catch (IOException e) {            System.out.println(e.getMessage());        }        if (err != null) {            try {                err.close();            } catch (IOException e) {                System.out.println(e.getMessage());            }        }    }    return exitValue;}视频剪辑完成
原创粉丝点击