package com.ssj.framework.weixin.util;

import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.idworker.IdWorker;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.mp3.MP3AudioHeader;
import org.jaudiotagger.audio.mp3.MP3File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class AmrToMp3Util {

	 private static Logger logger = LoggerFactory.getLogger(AmrToMp3Util.class);
	public static String changeToMp3(String inputPath) { 
		String file_path = (String) SystemResourceLocator.getValue("file_save_path");
		String outPath=inputPath.substring(0, inputPath.lastIndexOf(".") + 1) + "mp3";
		List<String> command = new ArrayList<String>();  
		command.add("/usr/local/ffmpeg/ffmpeg");  
        command.add("-i");  
        command.add(file_path+inputPath);  
        command.add("-ab");  
        command.add("56");  
        command.add("-ar");  
        command.add("22050");  
        command.add("-qscale");  
        command.add("5");  
        command.add("-r");  
        command.add("15");  
        command.add("-s");  
        command.add("600x500");  
        command.add(file_path+outPath);  
        try {  
        	logger.info(""+command);
            Process videoProcess = new ProcessBuilder(command).redirectErrorStream(true).start();  
              
            new DoOutput(videoProcess.getErrorStream()).start();  
              
            new DoOutput(videoProcess.getInputStream()).start();  
              
            videoProcess.waitFor();  
              
        } catch (Exception e) {  
            logger.error("异常", e);
        }  
        return outPath;
	}
	/**
	 * 数据库的相对路径
	* @param inputPath
	* @return
	* 创建人：ZhangCaibao 
	* 2018年5月2日 下午4:08:47 
	* @String
	 */
	public static String mergeToMp3(List<String> inputPath) { 
		String file_path = (String) SystemResourceLocator.getValue("file_save_path");
		String fPath = DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd");
		File  f = new File(file_path+fPath);
		if (!f.exists()) {
			f.mkdirs();
		}
		String outPath=fPath+"/"+ IdWorker.generateId() + ".mp3";
		List<String> command = new ArrayList<String>();  
		StringBuffer sb =new StringBuffer();
		command.add("/usr/local/ffmpeg/ffmpeg");
		for (String string : inputPath) {
			command.add("-i");  
			command.add(file_path+string); 
		}
		command.add("-filter_complex"); 
		sb.append("\'"); 
		for (int i=0;i<inputPath.size();i++) {
			String numindex="["+i+":0]";
			sb.append(numindex); 
		}
		sb.append(" concat=n="+inputPath.size()+":v=0:a=1 [a]");
		sb.append("\'"); 
		logger.info(sb.toString());
		command.add(sb.toString());
		command.add("-map");
		command.add("[a]");
		command.add(file_path+outPath);
		try {  
			logger.info(""+command);
			
			
			Process videoProcess = new ProcessBuilder(command).redirectErrorStream(true).start();  
			
			new DoOutput(videoProcess.getErrorStream()).start();  
			
			new DoOutput(videoProcess.getInputStream()).start();  
			
			videoProcess.waitFor();  
			
		} catch (Exception e) {  
			logger.error("异常", e);
		}  
		return outPath;
	}
	
	
	
	
	 /**
     * 
     * 多线程内部类 读取转换时cmd进程的标准输出流和错误输出流，这样做是因为如果不读取流，进程将死锁
     */
    private static class DoOutput extends Thread {
        public InputStream is;

        //构造方法
        public DoOutput(InputStream is) {
            this.is = is;
        }

        public void run() {
            BufferedReader br = new BufferedReader(new InputStreamReader(this.is));
            String str = null;
            try {
                //这里并没有对流的内容进行处理，只是读了一遍
                while ((str = br.readLine()) != null) {
                    logger.debug(str);
                }
            } catch (IOException e) {
                logger.error("执行转换mp3命令异常", e);
                e.printStackTrace();
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
    public static long getMp3duration(String url){
    	String file_path = (String) SystemResourceLocator.getValue("file_save_path");
    	File file  =new File(file_path+url);
    	MP3File f =null;
    	long i=0;
		try {
			f = (MP3File) AudioFileIO.read(file);
			MP3AudioHeader audioHeader = (MP3AudioHeader)f.getAudioHeader();
			i= audioHeader.getTrackLength();
		} catch (Exception e) {
			e.printStackTrace();
		}
        return i;
    }

	public static double getMp3durationNew(String url){
		String file_path = (String) SystemResourceLocator.getValue("file_save_path");
		File file  =new File(file_path+url);
		MP3File f =null;
		double i=0;
		try {
			f = (MP3File) AudioFileIO.read(file);
			MP3AudioHeader audioHeader = (MP3AudioHeader)f.getAudioHeader();
			i= audioHeader.getPreciseTrackLength();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return i;
	}

    public static String  conversionDate(long i){
    	Long  minute  = i/60;  
		Long  second  = i%60;  
		
    	 String min = minute >= 10 ? minute+"" : "0" + minute;
    	 String sec = second >= 10 ? second+"" : "0" + second;
         return  min + ":" + sec;
    }
}
