package com.zd.common.core.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;


public class FfmpegConsole {
    private static final Logger log = LoggerFactory.getLogger(FfmpegConsole.class);
    private Runtime runtime;
    private Process pro;

    public void exec(String cmd) {
        try {
            System.out.println("系统开始执行命令：\n" + cmd);
            runtime = Runtime.getRuntime();
            log.error("cmdBegin:"+cmd);
            pro = runtime.exec(new String[]{"sh", "-c", cmd});
            log.error("cmdEnd:"+cmd);
            InputStream stream = pro.getErrorStream();
            output(stream);
            pro.waitFor();
            Thread.sleep(1000*10);
            this.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //            Thread.sleep(1000*10);
            System.out.println("已经停止");
            //            Thread.sleep(1000*5);
        }
    }

    public void stop() throws IOException {
        OutputStream ostream = pro.getOutputStream();
        ostream.write("q\r\n".getBytes());
        ostream.flush();
        ostream.close();
    }

    public void output(InputStream stream) {
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            isr = new InputStreamReader(stream, "utf-8");
            br = new BufferedReader(isr);
            String str;
            // 通过readLine()方法按行读取字符串
            while ((str = br.readLine()) != null) {
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(br, isr, stream);
        }
    }
    public void close(AutoCloseable ... acs) {
        for(AutoCloseable ac : acs) {
            try {
                ac.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) throws Exception {
        FfmpegConsole console = new FfmpegConsole();
//        String cmd = "ffmpeg.exe -f gdigrab -offset_x 42 -offset_y 325 -video_size 1196x900 -i desktop -f dshow -i audio=\"virtual-audio-capturer\" -vcodec libx264 -pix_fmt yuv420p  C:\\Users\\lv-wang\\Desktop\\测试录屏\\ii.mp4";
//        String cmd ="ffmpeg.exe -i D:/CHAI/4444.mp3 -i D:/CHAI/5555.mp3 -filter_complex amix=inputs=2:duration=longest:dropout_transition=2 D://CHAI//merge1.mp3";
        String cmd ="ffmpeg.exe -i D:/CHAI/7777.mp3 -i D:/CHAI/6666.mp3 -filter_complex \"[0:a]aformat=sample_fmts=fltp:channel_layouts=stereo,volume=0.9[a0]; [1:a]aformat=sample_fmts=fltp:channel_layouts=stereo,volume=0.5,adelay=5000|5000|5000,apad[a1]; [a0][a1]amerge=inputs=2[aout]\" -shortest -map \"[aout]\" -ac 2 D://CHAI//merge1.mp3";
        new Thread(()->console.exec(cmd)).start();
        Thread.sleep(1000*10);
        console.stop();
        System.out.println("已经停止");
        Thread.sleep(1000*5);

    }
}
