1. 程式人生 > >JAVA 讀取MP3歌名,歌手,專輯,封面

JAVA 讀取MP3歌名,歌手,專輯,封面

 上傳MP3檔案後,後臺讀取MP3資訊。需要使用的引入一個jar :   Jaudiotagger-2.2.6-SNAPSHOT.jar  下載地址

package com.hnzh.bnk.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.audio.mp3.MP3File;
import org.jaudiotagger.tag.TagException;
import org.jaudiotagger.tag.id3.AbstractID3v2Frame;
import org.jaudiotagger.tag.id3.AbstractID3v2Tag;
import org.jaudiotagger.tag.id3.framebody.FrameBodyAPIC;

import com.hnzh.bnk.admin.service.entity.model.Music;
import com.jfinal.kit.PathKit;
import com.jfinal.log.Log;

import io.jboot.utils.StrUtils;

/**
 * MP3工具類
 * @author zhaoqx
 *
 */
public class MP3Utils {

	protected static final Log logger = Log.getLog(MP3Utils.class);
	
	/**
	 * 解析MP3獲取歌名,歌手,專輯
	 * @param music 音樂Bean
	 * @return
	 */
	public static Music getSongInfo(Music music) {
        try {
        	MP3File mp3File = (MP3File) AudioFileIO.read(new File(PathKit.getWebRootPath() + music.getMusicUrl()));
        	AbstractID3v2Tag tag = mp3File.getID3v2Tag();
        	String songName = "";
        	String singer = "";
        	String author = "";
            //MP3AudioHeader audioHeader = (MP3AudioHeader) mp3File.getAudioHeader();
        	if(mp3File.getID3v2Tag() != null && mp3File.getID3v2Tag().frameMap != null){
        		if(tag.frameMap.get("TIT2") != null){
        			songName = tag.frameMap.get("TIT2").toString();//歌名
            		if(!StrUtils.isNotBlank(songName)){
                    	songName = "未知歌曲";
                    }
            		music.setTitle(reg(songName));
        		}
        		if(tag.frameMap.get("TPE1") != null){
        			singer = mp3File.getID3v2Tag().frameMap.get("TPE1").toString();//歌手
                    if(!StrUtils.isNotBlank(singer)){
                    	singer = "未知歌手";
                    }
                    music.setSinger(reg(singer));
        		}
        		if(tag.frameMap.get("TALB") != null){
        			author = mp3File.getID3v2Tag().frameMap.get("TALB").toString();//專輯
        			music.setAlbum(reg(author));
        		}
        	}
            //int duration = audioHeader.getTrackLength();//時長
        } catch (Exception e) {
        	logger.error("MP3Utils:讀取MP3資訊失敗!");
        }
        return music;
	}

	
	//去除不必要的字串
	public static String reg(String input) {
	    return input.substring(input.indexOf('"') + 1, input.lastIndexOf('"'));
	}
	
	 /**
     * 獲取MP3封面圖片
     * @param mp3File
     * @return
	 * @throws InvalidAudioFrameException 
	 * @throws ReadOnlyFileException 
	 * @throws TagException 
	 * @throws IOException 
	 * @throws CannotReadException 
     */
    public static byte[] getMP3Image(Music music) {
        byte[] imageData = null;
    	MP3File mp3File;
		try {
			mp3File = (MP3File) AudioFileIO.read(new File(PathKit.getWebRootPath() + music.getMusicUrl()));
	        AbstractID3v2Tag tag = mp3File.getID3v2Tag();
	        AbstractID3v2Frame frame = (AbstractID3v2Frame) tag.getFrame("APIC");
	        FrameBodyAPIC body = (FrameBodyAPIC) frame.getBody();
	        imageData = body.getImageData();
		} catch (Exception e) {
			logger.error("MP3Utils:讀取MP3封面失敗!");
			return null;
		}
        return imageData;
    }
    
    /**
     * 獲取mp3圖片並將其儲存至指定路徑下
     * 如果沒有讀取到圖片 ,則返回"/static/music/images/defulate.jpg"
     * @param music mp3檔案物件
     * @param mp3ImageSavePath mp3圖片儲存位置(預設mp3ImageSavePath +"\" mp3File檔名 +".jpg" )
     * @param cover 是否覆蓋已有圖片
     * @return 生成圖片路徑
     */
    public static String saveMP3Image(Music music, String mp3ImageSavePath, boolean cover) {
        //生成mp3圖片路徑
    	//PathKit.getWebRootPath() + music.getMusicUrl() 路徑字首,修改成自己的url字首
    	File file = new File(PathKit.getWebRootPath() + music.getMusicUrl());
        String mp3FileLabel = file.getName();
        String mp3ImageFullPath = mp3ImageSavePath + ("\\" + mp3FileLabel + ".jpg");

        //若為非覆蓋模式,圖片存在則直接返回(不再建立)
        if( !cover ) {
            File tempFile = new File(mp3ImageFullPath) ;
            if(tempFile.exists()) {
                return mp3ImageFullPath;
            }
        }

        //生成mp3存放目錄
        File saveDirectory = new File(mp3ImageSavePath);
        saveDirectory.mkdirs();

        //獲取mp3圖片
        byte imageData[];
		imageData = getMP3Image(music);
		if(imageData == null){
			logger.error("MP3Utils:讀取MP3封面失敗!");
            //獲取失敗,返回預設圖片路徑
			return "/static/music/images/defulate.jpg";
		}
		
        //若圖片不存在,則直接返回null
        if (null == imageData || imageData.length == 0) {
            return null;
        }
        //儲存mp3圖片檔案
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(mp3ImageFullPath);
            fos.write(imageData);
            fos.close();
        } catch(Exception e) {
        	logger.error("MP3Utils:儲存讀取mp3圖片檔案失敗!");
        }
        return mp3ImageFullPath.substring(PathKit.getWebRootPath().length(), mp3ImageFullPath.length());
    }
}