M3U8下载,直播源下载,FLASH下载(三)-直播源下载

2018年8月31日 更新,通过了一段时间的使用,我决定把这个下载类再升级一下。升级为一个工具类。我贴在了另外一篇帖子中。
M3U8下载,直播源下载,FLASH下载(四)-直播源下载-工具类java


前言

  在工做或者生活中,咱们每每会在网页中遇见一些不错的视频,想下载下来存到本地,可是无奈视频是flash播放的,不能在开发者工具中找到视频的绝对地址进行下载,反而是找到了个直播源,譬如:http://video.newsapp.cnr.cn/data/video/2018/7358/index.m3u8
这样的连接是直播源地址,不少电视台的流媒体或者网络直播就是采用这样的方式,优势我就不说了,请本身baidu。web

准备

JDK安装
ffmpeg安装:https://blog.csdn.net/u_ascend/article/details/80418402 apache

代码

package cn.edu.zua.common.util.audio;

import cn.edu.zua.common.util.UtilTools;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/** * AudioM3U8Downloader * * @author ascend * @date 2018/06/08 11:07. */
public class AudioM3U8Downloader {
    private static final Logger LOG = LoggerFactory.getLogger(AudioM3U8Downloader.class);

    private static final String basePath = "/tmp/";
    private static final int downloaderMaxSecond = 120;

    private AudioM3U8Downloader() {
    }

    /** * 测试方法 */
    public static void main(String[] args) throws Exception {
        byte[] bytes = downloadBytes("http://recordcdn.quklive.com/upload/vod/user1462960877450854/1527512379701708/3/video.m3u8");
        System.out.println(bytes.length);
        LOG.debug("等待2s");
        TimeUnit.SECONDS.sleep(2);
        // File file = downloadFile("http://recordcdn.quklive.com/upload/vod/user1462960877450854/1524531065801767/3/video.m3u8");
        // System.out.println("file.getAbsolutePath() = " + file.getAbsolutePath());
    }

    /** * 把m3u8短视频下载后提取File * @param m3u8Url 直播源地址 * @return 直播源文件,File * @throws InterruptedException 中断异常 * @throws IOException IO异常 */
    public static File downloadFile(String m3u8Url) throws InterruptedException, IOException {
        String fileName = UtilTools.getUUIDyyyyMMddHHmmss();
        File f = new File("/tmp/");
        if (!f.exists()) {
            f.mkdirs();
        }
        String fullFileName = "/tmp/" + fileName + ".mp4";
        String command = "ffmpeg -i " + m3u8Url + " -vcodec copy " + fullFileName + " -y";
        LOG.debug("执行命令:{}", command);
        Process process = Runtime.getRuntime().exec(command);
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        getStream(executorService, process.getErrorStream(), true);
        getStream(executorService, process.getInputStream(), false);
        TimeUnit.SECONDS.sleep(10);
        File file = new File(fullFileName);
        // 最长再等待24秒
        for (int i = 0; i < 8; i++) {
            if (!file.exists()) {
                LOG.debug("文件不存在,从新建立...");
                TimeUnit.SECONDS.sleep(3);
                file = new File(fullFileName);
            }
        }
        long size = 0;
        final boolean[] checkFlag = {true};
        executorService.execute(() -> {
            try {
                TimeUnit.SECONDS.sleep(150);
                checkFlag[0] = false;
            } catch (InterruptedException e) {
                LOG.error("最长等待线程被中断,正常错误", e);
            }
        });
        int maxCount = 10;
        while (checkFlag[0]) {
            TimeUnit.SECONDS.sleep(5);
            long fileLength = file.length();
            LOG.debug("上一次监测的大小:{}, 本次监测的大小:{}", size, fileLength);
            if (file.length() != size) {
                size = file.length();
                TimeUnit.SECONDS.sleep(5);
            } else {
                if (fileLength == 0 && maxCount-- > 0) {
                    continue;
                } else {
                    LOG.debug("退出循环...");
                    checkFlag[0] = false;
                }
            }
        }
        process.destroy();
        executorService.shutdownNow();
        LOG.info("文件下载成功:{}", file.getAbsolutePath());
        return file;
    }

    /** * 把m3u8短视频下载后提取byte数组,而且删除临时文件 * @param m3u8Url 直播源地址 * @return byte[],从文件中提取的字节数组 * @throws InterruptedException 中断异常 * @throws IOException IO异常 */
    public static byte[] downloadBytes(String m3u8Url) throws InterruptedException, IOException {
        File file = downloadFile(m3u8Url);
        LOG.debug("字节数组方法下载调用成功:{}, 文件大小:{}", file.getAbsolutePath(), file.length());
        LOG.debug("睡眠2秒钟,把文件转换为字节数组");
        TimeUnit.SECONDS.sleep(2);
        FileInputStream input = FileUtils.openInputStream(file);
        byte[] bytes = IOUtils.toByteArray(input);
        input.close();
        LOG.info("返回文件数组!!文件长度:{}", bytes.length);
        // 删除下载后的文件
        if (file.exists()) {
            LOG.debug("文件存在,删除文件!");
            if (Files.deleteIfExists(Paths.get(file.toURI()))) {
                LOG.debug("删除成功");
            }else {
                LOG.debug("删除失败");
            }
        }
        return bytes;
    }


    private static void getStream(ExecutorService executorService, final InputStream inputStream, final boolean printFlag) {
        executorService.execute(() -> {
            BufferedInputStream in = new BufferedInputStream(inputStream);
            byte[] bytes = new byte[1024];
            try {
                while (in.read(bytes) != -1) {
                    String s = new String(bytes, 0, bytes.length);
                    if (printFlag) {
// LOG.error("ffmpeg:error when downloading!\ninfo:"+s);
                    }
// LOG.debug("read from inputstream:{}", s);
                }
            } catch (IOException e) {
                LOG.error("读取下载流失败", e);
            } finally {
                try {
                    in.close();
                } catch (IOException e) {
                    LOG.error("关闭读取流失败:", e);
                }
            }
        });
    }
}

看这里,看这里
文章总目录:博客导航windows