音频上传和剪辑页面信息
<div id="edit_picker">上传文件</div>
<div id="edit_audio"></div>
<div>开始时间</div><input type="text" id="start_time"/><div>结束时间</div><input type="text" id="end_time"/>
<button type="button" onclick="editAudio()" >剪辑</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/uploadaudio',
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#edit_picker',
fileVal:'Filedata',
//同一文件是否可以重复上传
duplicate :true,
// 只允许选择图片文件。
accept: {
title: 'audio',
extensions: 'mp3,wav',
mimeTypes: 'audio/*'
}
});
//上传过程中
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 audio = '<embed id="lshfEmbed" src="'+url+'" windowlessVideo="true" autostart="0" loop="true" ></embed>';
var input = '<input id="audio_path" name="audio_path" value="'+resp.url+'" type="hidden">';
$("#edit_audio").html(audio+input);
});
});
function editAudio(){
var start_time = $("#start_time").val();
var end_time = $("#end_time").val();
var audio_path = $("#audio_path").val();
$.ajax({
type:'post',
data:{startTime:start_time,endTime:end_time,audioPath:audio_path},
url:'$path/text/editaudio',
success:function(date){
if(date==1){
alert("剪辑成功");
}
}
});
}
</script>
注:被系统使用的是web uploader上传,如有需要,可自行下载:这里写链接内容
音频文件上传代码:
@Post("uploadaudio")
public Object uploadaudio(Invocation inv, Model model, MultipartFile Filedata){
//写在config文件中的音频文件上传路径,根据需要,自己定义
String uploadDir = config.getString("upload.audio");
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){
//inv——request的封装,可使用request
//Filedata——上传的音频文件信息
//uploadDir——上传路径
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 startTime
* @param endTime
* @param audioPath
* @return
*/
@Post("editaudio")
public Object editAudio(Invocation inv,Model model,String startTime,String endTime,String audioPath){
String upOutDir = config.getString("upload.audio");
//剪辑后的路径
upOutDir = inv.getServletContext().getRealPath(upOutDir);
//获取年和月的时间
DateFormat dft = new SimpleDateFormat("yyyyMM");
Timestamp timestamp = new Timestamp((new Date()).getTime());
String outFile = upOutDir + File.separator +dft.format(timestamp);
File file = new File(outFile);
if(!file.exists()){
file.mkdirs();
}
upOutDir = outFile+File.separator + timestamp.getTime() + ".mp3";
audioPath = inv.getServletContext().getRealPath(audioPath);
if(cutAudio(audioPath, upOutDir, Integer.valueOf(startTime), Integer.valueOf(endTime))){
String path = config.getString("upload.audio")+File.separator +
dft.format(timestamp)+File.separator+timestamp.getTime()+ ".mp3";
model.add("result", path);
}else{
model.add("result", 0);
}
return "result.json";
}
/**
* 截取音频文件
* @param sourcepath 源文件地址
* @param targetpath 目标文件地址
* @param start 截取开始时间(秒)
* @param end 截取结束时间(秒)
* return 截取成功返回true,否则返回false
*/
public boolean cutAudio(String sourcefile, String targetfile, int start, int end) {
try{
File file = new File(sourcefile);
if(!file.exists()){
return false;
}
long totalTime = getVideoTime(sourcefile, "E:\\ffmpeg-20170425-b4330a0-win32-static\\ffmpeg-20170425-b4330a0-win32-static\\bin\\ffmpeg.exe"); //总时长(秒)
System.out.println(totalTime);
if(start<0 || end<=0 || start>=totalTime || end>totalTime || start>=end){
return false;
}
FileInputStream fis = new FileInputStream(file);
long fileSize = file.length(); //音频数据大小
long splitSize = (fileSize/totalTime)*(end-start); //截取的音频数据大小
long skipSize = (fileSize/totalTime)*start; //截取时跳过的音频数据大小
int splitSizeInt = Integer.parseInt(String.valueOf(splitSize));
int skipSizeInt = Integer.parseInt(String.valueOf(skipSize));
byte[] fbyte = new byte[splitSizeInt]; //存放截取的音频数据
byte[] skipBytes = new byte[skipSizeInt]; //存放截取时跳过的音频数据
fis.read(skipBytes, 0, skipBytes.length); //跳过不需要截取的数据
fis.read(fbyte, 0, fbyte.length); //读取要截取的数据到目标数组
fis.close();
File target = new File(targetfile);
if(target.exists()){ //如果目标文件已存在,则删除目标文件
target.delete();
}
FileOutputStream fos = new FileOutputStream(target);
fos.write(fbyte);
fos.flush();
fos.close();
}catch(IOException e){
e.printStackTrace();
return false;
}
return true;
}
/**
* 获取音频文件总时长
* @param video_path 文件路径
* @param ffmpeg_path 工具路径
* @return
*/
public int getVideoTime(String video_path, String ffmpeg_path) {
List<String> commands = new java.util.ArrayList<String>();
commands.add(ffmpeg_path);
commands.add("-i");
commands.add(video_path);
try {
ProcessBuilder builder = new ProcessBuilder();
builder.command(commands);
final Process p = builder.start();
//从输入流中读取视频信息
BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
//从视频信息中解析时长
String regexDuration = "Duration: (.*?), start: (.*?), bitrate: (\\d*) kb\\/s";
Pattern pattern = Pattern.compile(regexDuration);
Matcher m = pattern.matcher(sb.toString());
if (m.find()) {
int time = getTimelen(m.group(1));
return time;
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
//格式:"00:00:10.68"
private int getTimelen(String timelen){
int min=0;
String strs[] = timelen.split(":");
if (strs[0].compareTo("0") > 0) {
min+=Integer.valueOf(strs[0])*60*60;//秒
}
if(strs[1].compareTo("0")>0){
min+=Integer.valueOf(strs[1])*60;
}
if(strs[2].compareTo("0")>0){
min+=Math.round(Float.valueOf(strs[2]));
}
return min;
}
这样就完成了音频文件的上传和剪辑。