流文件边下边播,解决ios播放不了音频问题

    最近遇见ios播放不了mp3问题,经过网上查找资料找到解决办法,记录下来以便下次使用。

    解决此问题的核心思想断点上传,每次请求返回4096kb大小的文件流。

    附上代码,可直接使用。

//断点续传,解决ios播放不了音频问题
	private void sendVideo(HttpServletRequest request, HttpServletResponse response, File file, String fileName,String exName) throws FileNotFoundException, IOException {
		RandomAccessFile randomFile = new RandomAccessFile(file, "r");//只读模式
		long contentLength = randomFile.length();
		String range = request.getHeader("Range");
		int start = 0, end = 0;
		if(range != null && range.startsWith("bytes=")){
			String[] values = range.split("=")[1].split("-");
			start = Integer.parseInt(values[0]);
			if(values.length > 1){
				end = Integer.parseInt(values[1]);
			}
		}
		int requestSize = 0;
		if(end != 0 && end > start){
			requestSize = end - start + 1;
		} else {
			requestSize = Integer.MAX_VALUE;
		}

		byte[] buffer = new byte[4096];
		if(exName.equals("MP4")){
			response.setContentType("video/mp4");
		}else if(exName.equals("MP3")){
			response.setContentType("audio/mp3");
		}else if (exName.equals("FlV")){
			response.setContentType("video/flv");
		}
		response.setHeader("Accept-Ranges", "bytes");
		response.setHeader("ETag", fileName);
		response.setHeader("Last-Modified", new Date().toString());
		//第一次请求只返回content length来让客户端请求多次实际数据
		if(range == null){
			response.setHeader("Content-length", contentLength + "");
		}else{
			//以后的多次以断点续传的方式来返回视频数据
			response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);//206
			long requestStart = 0, requestEnd = 0;
			String[] ranges = range.split("=");
			if(ranges.length > 1){
				String[] rangeDatas = ranges[1].split("-");
				requestStart = Integer.parseInt(rangeDatas[0]);
				if(rangeDatas.length > 1){
					requestEnd = Integer.parseInt(rangeDatas[1]);
				}
			}
			long length = 0;
			if(requestEnd > 0){
				length = requestEnd - requestStart + 1;
				response.setHeader("Content-length", "" + length);
				response.setHeader("Content-Range", "bytes " + requestStart + "-" + requestEnd + "/" + contentLength);
			}else{
				length = contentLength - requestStart;
				response.setHeader("Content-length", "" + length);
				response.setHeader("Content-Range", "bytes "+ requestStart + "-" + (contentLength - 1) + "/" + contentLength);
			}
		}
		ServletOutputStream out = response.getOutputStream();
		int needSize = requestSize;
		randomFile.seek(start);
		while(needSize > 0){
			int len = randomFile.read(buffer);
			if(needSize < buffer.length){
				out.write(buffer, 0, needSize);
			} else {
				out.write(buffer, 0, len);
				if(len < buffer.length){
					break;
				}
			}
			needSize -= buffer.length;
		}
		randomFile.close();
		out.close();

	}

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页