最近要解决一个html5 播放音频的问题,在前台地址中不能直接写服务器中的音频文件地址。
在java中使用的springmvc来解决问题,先配置好springmvc的环境,拦截*.mp3的请求,写controller方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 package org.xxz.testaudio;import java.io.File;import java.io.FileInputStream;import java.io.OutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;@Controller @RequestMapping ("/player" )public class PlayerController { @RequestMapping (value = "/{id}" ) public ModelAndView getAudio (@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception { System.out.println("id: " + id); String range = request.getHeader("Range" ); String[] rs = range.split("\\=" ); range = rs[1 ].split("\\-" )[0 ]; String path = request.getServletContext().getRealPath("/" ); File file = new File(path + "/WEB-INF/mp3/" + id + ".mp3" ); if (!file.exists()) throw new RuntimeException("音频文件不存在 --> 404" ); OutputStream os = response.getOutputStream(); FileInputStream fis = new FileInputStream(file); long length = file.length(); System.out.println("file length : " + length); int count = 0 ; int percent = (int )(length * 0.4 ); int irange = Integer.parseInt(range); length = length - irange; response.addHeader("Accept-Ranges" , "bytes" ); response.addHeader("Content-Length" , length + "" ); response.addHeader("Content-Range" , "bytes " + range + "-" + length + "/" + length); response.addHeader("Content-Type" , "audio/mpeg;charset=UTF-8" ); int len = 0 ; byte [] b = new byte [1024 ]; while ((len = fis.read(b)) != -1 ) { os.write(b, 0 , len); count += len; if (count >= percent){ break ; } } System.out.println("count: " + count + ", percent: " + percent); fis.close(); os.close(); return null ; } }
页面编写:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <%@ 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 ="${pageContext.request.contextPath}/player/zj-ywaqldbry.mp3" controls ="controls" > Your browser does not support the audio tag. </audio > </body > </html >
这里只能播放视频文件的40%的内容。
在这里可以做到一个控制,比如你在用html5做项目中,有写播放的音频需要收费,但是你又只能让用户试听一部分的内容,那么你就可以这样实现。
不知道实际项目中是不是这么控制的。
如果您觉得文章有用或对您有帮助,欢迎通过以下方式赞助我。 ♪(^∀^●)ノ