html5 audio读取文件流播放音频

controller:读取流

@RequestMapping(value = "audioListen")
    @ResponseBody
	public String getAudio(HttpServletRequest request, HttpServletResponse response,@RequestParam String path) throws Exception{
		 
		 if (path!=null) {
			 String range = request.getHeader("Range");  
             String[] rs = range.split("\\=");  
            range = rs[1].split("\\-")[0]; 
			 File file = new File(path);  
			 if(!file.exists()) throw new RuntimeException("音频文件不存在 --> 404");
			 OutputStream os = response.getOutputStream();  
			 FileInputStream fis = new FileInputStream(file);  
			 long length = file.length();  
			 // 播放进度  
			 int count = 0;  
			 // 播放百分比  
			 int percent = (int)(length * 1);  
			 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;  
			     }  
			 }  
			 fis.close();  
			 os.close();  
		 }
		return null;
	}

 

页面:

 

function audioListen(path){
	$("#robot-audio-listen-id").attr("src","${ctx}/admin/robot/audio/audioListen?path="+path.replace(/\\/g,"/"));
	document.getElementById("robot-audio-listen-id").load();
}

转自:https://blog.csdn.net/xxzblog/article/details/41312315

 

你可能感兴趣的:(前端插件,#,audio)