播放amr音频,后台进行mp3转码

public void sendFile(HttpServletRequest request, HttpServletResponse response) {
    String filePath = request.getParameter("filePath");
    OutputStream os = null;
    try {
            /* 前端插件无法播放amr音频,后台进行mp3转码 */
        String newPath = filePath.substring(0, filePath.lastIndexOf("."));

        File source = new File(filePath);
        File file = new File(newPath + ".mp3");
        AudioAttributes audio = new AudioAttributes();
        Encoder encoder = new Encoder();

        audio.setCodec("libmp3lame");
        EncodingAttributes attrs = new EncodingAttributes();
        attrs.setFormat("mp3");
        attrs.setAudioAttributes(audio);

        try {
            encoder.encode(source, file, attrs);
        } catch (IllegalArgumentException | EncoderException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "inline;filename=" + file.getName());

        response.setHeader("Content-Type", "audio/mpeg");

        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("Range", "bytes=0-" + file.length());
        os = response.getOutputStream();
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int bytes;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            os.write(bufferOut, 0, bytes);
        }
        in.close();
        os.flush();
        os.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (os != null) {
                os.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
阅读更多
换一批

没有更多推荐了,返回首页