将mp3文件转换为Base64用于网页播放

2019-09-30  本文已影响0人  夹板儿孩

网上花里胡哨的代码很多,作为小白,看起来是真的挺吃力的。于是我找到了一个适用于自己的代码,希望能帮到大家
工作需求,需要在网页上播放音视频文件,但是文件又在其他地方。所以就想到用后端直接转成字节直接传给给网页播放,这里我一共找到了两种方式。

package com.frontier.screen.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;


@Controller
public class AudioController {
    @RequestMapping("getBase")
    @ResponseBody
    public String getBase() throws Exception {
        File file = new File("D:/这,就是爱.mp3");
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) (file.length() * 0.5)];
        inputFile.read(buffer);
        inputFile.close();
        String str = new BASE64Encoder().encode(buffer);
        System.out.println("长度: " + str.length());
        return str;
    }

    @RequestMapping("getBase2")
    public ModelAndView getAudio(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String range = request.getHeader("Range");
        String[] rs = range.split("\\=");
        range = rs[1].split("\\-")[0];

        File file = new File("D:/这,就是爱.mp3");
        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 * 0.4); //播放百分比.这里我们控制仅播放40%

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

HTML部分代码请点击这里
getBase2 这个方式是我在百度的时候偶然发现,感兴趣的可以阅读原文

上一篇 下一篇

猜你喜欢

热点阅读