1. 程式人生 > >audio讀取檔案流播放音訊

audio讀取檔案流播放音訊

jsp階段:

<audio controls="controls" controlsList="nodownload"><source  src="${ctx }/phone/getAudio.ce?type=3&PATHID='+mp+'" type="audio/mpeg"></audio>

效果圖:


java部分:

@RequestMapping("getAudio")  
    @ResponseBody
	public String getAudio(HttpServletRequest request, HttpServletResponse response) throws Exception{
		 Map<String, Object> map = getPageMapParams();	
		 List<Map<String, Object>> list_new =xcxQqandWxServices.getimgOraudiopath(map);
		 
		 String path = (String)list_new.get(0).get("TRANCFILEPATH");
		 if (path!=null) {
			 String range = request.getHeader("Range");  
                         String[] rs = range.split("\\=");  
                         range = rs[1].split("\\-")[0]; 
			 File file = new File(path);  
			 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;
	}
借鑑地址:https://blog.csdn.net/xxzblog/article/details/41312315