html5 audio读取文件流播放音频

最近要解决一个html5 播放音频的问题,在前台地址中不能直接写服务器中的音频文件地址。

在java中使用的springmvc来解决问题,先配置好springmvc的环境,拦截*.mp3的请求,写controller方法

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;
	}

}

页面编写:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




audio


	



这里只能播放视频文件的40%的内容。

在这里可以做到一个控制,比如你在用html5做项目中,有写播放的音频需要收费,但是你又只能让用户试听一部分的内容,那么你就可以这样实现。

你可能感兴趣的:(java,xxzkid,小小钟,audio,html5,springmvc)