最近要解决一个html5 播放音频的问题,在前台地址中不能直接写服务器中的音频文件地址。
在java中使用的springmvc来解决问题,先配置好springmvc的环境,拦截*.mp3的请求,写controller方法
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@Controller
@RequestMapping("/player")
public class PlayerController {
@RequestMapping(value = "/{id}")
public ModelAndView getAudio(@PathVariable String id, HttpServletRequest request,
HttpServletResponse response) throws Exception {
("id: " + id);
String range = ("Range");
String[] rs = ("\\=");
range = rs[1].split("\\-")[0];
String path = ().getRealPath("/");
File file = new File(path + "/WEB-INF/mp3/" + id + ".mp3");
if(!()) throw new RuntimeException("音频文件不存在 --> 404");
OutputStream os = ();
FileInputStream fis = new FileInputStream(file);
long length = ();
("file length : " + length);
// 播放进度
int count = 0;
// 播放百分比
int percent = (int)(length * 0.4);
int irange = (range);
length = length - irange;
("Accept-Ranges", "bytes");
("Content-Length", length + "");
("Content-Range", "bytes " + range + "-" + length + "/" + length);
("Content-Type", "audio/mpeg;charset=UTF-8");
int len = 0;
byte[] b = new byte[1024];
while ((len = (b)) != -1) {
(b, 0, len);
count += len;
if(count >= percent){
break;
}
}
("count: " + count + ", percent: " + percent);
();
();
return null;
}
}
页面编写:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>audio</title>
</head>
<body>
<audio src="${}/player/zj-ywaqldbry.mp3" controls="controls">
Your browser does not support the audio tag.
</audio>
</body>
</html>
这里只能播放视频文件的40%的内容。
在这里可以做到一个控制,比如你在用html5做项目中,有写播放的音频需要收费,但是你又只能让用户试听一部分的内容,那么你就可以这样实现。