1. 程式人生 > >Android-手機Mp3音樂檔案顯示到ListView中

Android-手機Mp3音樂檔案顯示到ListView中

在做音樂播放器的時候都需要搜尋手機裡面的音樂檔案並顯示到檔案中,並顯示到 ListView中,下面直接來說說搜尋音樂檔案並顯示到ListView中的實現方法。

直接上程式碼,從程式碼中看問題……

首先佈局檔案放置一個ListView,/com.android.Mp3List/res/layout/Activity_main.XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" 
    android:background="@drawable/beijing">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="音樂列表"
        android:layout_gravity="center"
        android:textSize="25sp" />

    <ListView
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>
mp3檔案有很多屬性,這裡以少量為例,只顯示音樂名,時間和演唱者:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/actor"
        android:layout_alignBottom="@+id/actor"
        android:layout_alignParentRight="true"
        android:layout_marginRight="28dp"
        android:text="time" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="24dp"
        android:text="name"
        android:textSize="25sp" />

    <TextView
        android:id="@+id/actor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/name"
        android:layout_below="@+id/name"
        android:text="actor" />

</RelativeLayout>

為了更好的管理我們的檔案,我們需要單獨建立一個類來管理MP3檔案的屬性值,新建類命名為MusicInfo.java:
package com.android.mp3list;

public class MusicInfo {
	private long id; // 歌曲ID 
	private String title; // 歌曲名稱 
	private String album; // 專輯 
	private long albumId;//專輯ID 
	private String displayName; //顯示名稱 
	private String artist; // 歌手名稱 
	private long duration; // 歌曲時長 
	private long size; // 歌曲大小 
	private String url; // 歌曲路徑 
	private String lrcTitle; // 歌詞名稱
	private String lrcSize; // 歌詞大小 

	public MusicInfo() {
		super();
	}
	public MusicInfo(long id, String title, String album, long albumId,
			String displayName, String artist, long duration, long size,
			String url, String lrcTitle, String lrcSize) {
		super();
		this.id = id;
		this.title = title;
		this.album = album;
		this.albumId = albumId;
		this.displayName = displayName;
		this.artist = artist;
		this.duration = duration;
		this.size = size;
		this.url = url;
		this.lrcTitle = lrcTitle;
		this.lrcSize = lrcSize;
	}
	
	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getAlbum() {
		return album;
	}

	public void setAlbum(String album) {
		this.album = album;
	}

	public long getAlbumId() {
		return albumId;
	}

	public void setAlbumId(long albumId) {
		this.albumId = albumId;
	}

	public String getArtist() {
		return artist;
	}

	public void setArtist(String artist) {
		this.artist = artist;
	}

	public long getDuration() {
		return duration;
	}

	public void setDuration(long duration) {
		this.duration = duration;
	}

	public long getSize() {
		return size;
	}

	public void setSize(long size) {
		this.size = size;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getLrcTitle() {
		return lrcTitle;
	}

	public void setLrcTitle(String lrcTitle) {
		this.lrcTitle = lrcTitle;
	}

	public String getLrcSize() {
		return lrcSize;
	}

	public void setLrcSize(String lrcSize) {
		this.lrcSize = lrcSize;
	}

	public String getDisplayName() {
		return displayName;
	}

	public void setDisplayName(String displayName) {
		this.displayName = displayName;
	}

再新建一個類查詢資料庫取得MP3檔案,並分離取得各屬性值,MusicUtil.java:

package com.android.mp3list;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;

public class MusicUtil {

	public static List<MusicInfo> getMp3Infos(Context context) {
		Cursor cursor = context.getContentResolver().query(
				MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
				MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
		
		List<MusicInfo> musicInfos = new ArrayList<MusicInfo>();
		for (int i = 0; i < cursor.getCount(); i++) {
			cursor.moveToNext();
			MusicInfo musicInfo = new MusicInfo();
			long id = cursor.getLong(cursor
					.getColumnIndex(MediaStore.Audio.Media._ID));	//音樂id
			String title = cursor.getString((cursor	
					.getColumnIndex(MediaStore.Audio.Media.TITLE))); // 音樂標題
			String artist = cursor.getString(cursor
					.getColumnIndex(MediaStore.Audio.Media.ARTIST)); // 藝術家
			String album = cursor.getString(cursor
					.getColumnIndex(MediaStore.Audio.Media.ALBUM));	//專輯
			String displayName = cursor.getString(cursor
					.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
			long albumId = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
			long duration = cursor.getLong(cursor
					.getColumnIndex(MediaStore.Audio.Media.DURATION)); // 時長
			long size = cursor.getLong(cursor
					.getColumnIndex(MediaStore.Audio.Media.SIZE)); // 檔案大小
			String url = cursor.getString(cursor
					.getColumnIndex(MediaStore.Audio.Media.DATA)); // 檔案路徑
			int isMusic = cursor.getInt(cursor
					.getColumnIndex(MediaStore.Audio.Media.IS_MUSIC)); // 是否為音樂
			if (isMusic != 0) { // 只把音樂新增到集合當中
				musicInfo.setId(id);
				musicInfo.setTitle(title);
				musicInfo.setArtist(artist);
				musicInfo.setAlbum(album);
				musicInfo.setDisplayName(displayName);
				musicInfo.setAlbumId(albumId);
				musicInfo.setDuration(duration);
				musicInfo.setSize(size);
				musicInfo.setUrl(url);
				musicInfos.add(musicInfo);
			}
		}
		return musicInfos;
	}
	
	public static List<HashMap<String, String>> getMusicMaps(
			List<MusicInfo> mp3Infos) {
		List<HashMap<String, String>> mp3list = new ArrayList<HashMap<String, String>>();
		for (Iterator iterator = mp3Infos.iterator(); iterator.hasNext();) {
			MusicInfo musicInfo = (MusicInfo) iterator.next();
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("title", musicInfo.getTitle());
			map.put("Artist", musicInfo.getArtist());
			map.put("album", musicInfo.getAlbum());
			map.put("displayName", musicInfo.getDisplayName());
			map.put("albumId", String.valueOf(musicInfo.getAlbumId()));
			map.put("duration", formatTime(musicInfo.getDuration()));
			map.put("size", String.valueOf(musicInfo.getSize()));
			map.put("url", musicInfo.getUrl());
			mp3list.add(map);
		}
		return mp3list;
	}
	
	/**
	 * 格式化時間,將毫秒轉換為分:秒格式
	 * @param time
	 * @return
	 */
	public static String formatTime(long time) {
		// TODO Auto-generated method stub
		String min = time / (1000 * 60) + "";
		String sec = time % (1000 * 60) + "";
		if (min.length() < 2) {
			min = "0" + time / (1000 * 60) + "";
		} else {
			min = time / (1000 * 60) + "";
		}
		if (sec.length() == 4) {
			sec = "0" + (time % (1000 * 60)) + "";
		} else if (sec.length() == 3) {
			sec = "00" + (time % (1000 * 60)) + "";
		} else if (sec.length() == 2) {
			sec = "000" + (time % (1000 * 60)) + "";
		} else if (sec.length() == 1) {
			sec = "0000" + (time % (1000 * 60)) + "";
		}
		return min + ":" + sec.trim().substring(0, 2);
	}
	
}
當然,要在Listview中顯示當然少不了介面卡了,這裡繼承的是BaseAdapter:
package com.android.mp3list;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MusicListAdapter extends BaseAdapter{

	private Context context;
	private List<MusicInfo> musicInfos;
	private MusicInfo musicInfo;
	
	/**
	 * 建構函式
	 * @param context	上下文
	 * @param mp3Infos  集合物件
	 */
	public MusicListAdapter(Context context, List<MusicInfo> mp3Infos) {
		this.context = context;
		this.musicInfos = mp3Infos;
	}


	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return musicInfos.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder viewHolder = null;
		if(convertView == null)
		{
			viewHolder = new ViewHolder();
			convertView = LayoutInflater.from(context).inflate(R.layout.list, null);
			viewHolder.musicTitle = (TextView) convertView.findViewById(R.id.name);
			viewHolder.musicDuration = (TextView) convertView.findViewById(R.id.time);
			viewHolder.musicArtist = (TextView) convertView.findViewById(R.id.actor);
			convertView.setTag(viewHolder);			//表示給View新增一個格外的資料,
		} else {
			viewHolder = (ViewHolder)convertView.getTag();//通過getTag的方法將資料取出來
		}
		musicInfo = musicInfos.get(position);
		viewHolder.musicTitle.setText(musicInfo.getTitle());		//顯示標題
		viewHolder.musicArtist.setText(musicInfo.getArtist());		//顯示藝術家
		viewHolder.musicDuration.setText(MusicUtil.formatTime(musicInfo.getDuration()));//顯示時長
		
		return convertView;
	}
	
	/**
	 * 定義一個內部類
	 * 宣告相應的控制元件引用
	 *
	 */
	public class ViewHolder {
		//所有控制元件物件引用
		public ImageView albumImage;	//專輯圖片
		public TextView musicTitle;		//音樂標題
		public TextView musicDuration;	//音樂時長
		public TextView musicArtist;	//音樂藝術家
	}

}
到這裡,就差最後一步了,是什麼呢?當然是new一個Adapter取得MP3檔案屬性值並放到Listview中顯示了,這裡我們轉到MainActivity.java裡面實現了。
package com.android.mp3list;

import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.widget.ListView;

public class MainActivity extends Activity {
	private ListView listview;
	private List<MusicInfo> musicInfos = null;
	private MusicListAdapter Listadapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		listview = (ListView) findViewById(R.id.list);
		
		musicInfos = MusicUtil.getMp3Infos(MainActivity.this);
		Listadapter = new MusicListAdapter(this, musicInfos);
		listview.setAdapter(Listadapter);
	}

}

就這樣,所有工作都結束了,看一下效果:

                                             

顯示效果還是很不錯的,如果需要顯示更多東西,只需把MusicInfo.java取得的對應的值取出即可。