Java&HTML5 audio 载入音频静态文件 或 动态字节流

一、方式1

存在静态文件,音频或视频文件可存储到项目路径下

(1)文件存储在服务路径 webapp 路径下,如下图所示

 

(2)浏览器可以直接访问

 

(3)HTML 内容

<audio id="audio" src="/static-file-server/audio/lie.mp3" controls></audio>

 

二、方式2

无静态文件,音/视频文件由代码动态生成,或存储于数据库(blob类型字段)

(1)HTML 内容


<audio id="audio" src="/server/audio/loading?id=1" controls></audio>

 

(2)Java 后台


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
@RequestMapping("/audio")
public class AudioController {

    @Autowired
    AudioServcie audioServcie;

    @RequestMapping(value = "/loading", method = RequestMethod.GET)
    @ResponseBody
    public void loading(HttpServletRequest request, HttpServletResponse response) throws IOException {
        long audioId = new Long(request.getParameter("id"));
        Audio audio = audioServcie.getByKey(audioId);
        if (null == audio || null == audio.getBlob()) {
            return;
        }

        FileInputStream fis = null;
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
            response.setContentType("application/octet-stream");//TODO 关键

            fis = (FileInputStream) audio.getBlob().getBinaryStream();
            bis = new BufferedInputStream(fis);

            byte[] b = new byte[bis.available()];
            bis.read(b);

            os = response.getOutputStream();
            if (b.length > 0) {
                os.write(b);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != os) {
                os.flush();
                os.close();
            }
            if (null != bis) {
                bis.close();
            }
            if (null != fis) {
                fis.close();
            }
        }
    }

}

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值