package cn.myapps.support.weixin.service;

import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.InputFormatException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.myapps.common.Environment;
import cn.myapps.support.weixin.WeixinHandleException;

/**
 * 微信企业号，管理媒体素材文件API
 * @author Happy
 *
 */
public class MediaService {
	
	private static final String get_media_url = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
	
	
	
	public static void downloadMedia(String access_token,String media_id,String fileName) throws WeixinHandleException{
		
		String url = get_media_url.replace("ACCESS_TOKEN", access_token).replace("MEDIA_ID", media_id);
		InputStream is = null;
		FileOutputStream fs = null;
		try{
			fileName = Environment.getInstance().getRealPath(fileName);
			HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
			conn.connect();
			
			if(conn.getResponseCode()!=HttpURLConnection.HTTP_OK){
				throw new WeixinHandleException("获取临时素材文件连接失败，连接代码:"+conn.getResponseCode());
			}
			
			is = conn.getInputStream();
			fs = new FileOutputStream(fileName);  
			
			byte buffer[] = new byte[1024];
			int read =0;
			while((read=is.read(buffer))!=-1){
				fs.write(buffer, 0, read);
			}
			
			fs.close();
			is.close();
			
			if(fileName.toLowerCase().endsWith(".amr")){
				changeToMp3(fileName, fileName.replace(".amr", ".mp3"));
			}
			
		}catch(IOException e){
			e.printStackTrace();
			throw new WeixinHandleException("获取临时素材文件 下载失败："+e.getMessage());
		}finally{
			 if (fs != null) {
	                try {
	                	fs.close();
	                } catch (Exception e) {}
	            }
	            if (is != null) {
	                try {
	                    is.close();
	                } catch (Exception e) {}
	            }
		}
	}
	
	/**
	 * 把amr格式的语音转换成MP3
	 * @Title: changeToMp3 
	 * @Description: TODO(把amr格式的语音转换成MP3) 
	 * @author  pll
	 * @param @param sourcePath amr格式文件路径
	 * @param @param targetPath 存放mp3格式文件路径 
	 * @return void 返回类型 
	 * @throws
	 */
	public static void changeToMp3(String sourcePath, String targetPath) {  
		File source = new File(sourcePath);  
		File target = new File(targetPath);  
		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, target, attrs);  
		} catch (IllegalArgumentException e) {  
		} catch (InputFormatException e) {  
		} catch (EncoderException e) {  
		}  
	}
	
	
	public static void main(String[] args) {
		downloadMedia("Q48GlIkfKrNeC4epiju2tUrJYzGEqsvF5ZCnY7ifKaUcZghUwSrAf__k7sK1uhbigOfBol6N14xEoaenhaWFew", "AadHZLeba_8-cW_dICOSQrDoh9m1Hz1lZP0OgWhsN2mI0cSxT6NC0cAj7sgyd67w", "d:/a.jpg");
	}

}
