当前位置: 代码迷 >> Android >> Android上MP3播放器的实现源代码01
  详细解决方案

Android上MP3播放器的实现源代码01

热度:21   发布时间:2016-05-01 16:49:08.0
Android下MP3播放器的实现源代码01
第一个类AlbumActivity

package com.alex.media;import com.alex.media.ArtistActivity.ListItemClickListener;import android.app.Activity;import android.content.Intent;import android.database.Cursor;import android.os.Bundle;import android.provider.MediaStore;import android.view.View;import android.widget.AdapterView;import android.widget.LinearLayout;import android.widget.ListView;import android.widget.AdapterView.OnItemClickListener;import android.widget.LinearLayout.LayoutParams;public class AlbumActivity extends Activity {	private int[] _ids;	private String[]_titles;	private ListView listview;	@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		Intent intent = this.getIntent();		String albumName;		albumName = intent.getExtras().getString("albums");		listview = new ListView(this);		Cursor c = this.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,				new String[]{MediaStore.Audio.Media.TITLE,				MediaStore.Audio.Media.DURATION,				MediaStore.Audio.Media.ARTIST,				MediaStore.Audio.Media._ID,				MediaStore.Audio.Media.DISPLAY_NAME}, 				MediaStore.Audio.Media.ALBUM + "='" + albumName+"'", 				null,				null);	   c.moveToFirst();	   _ids = new int[c.getCount()];	   _titles = new String[c.getCount()];	   for(int i=0;i<c.getCount();i++){	       _ids[i] = c.getInt(3);	       _titles[i] = c.getString(0);	       c.moveToNext();	  }	   listview.setAdapter(new MusicListAdapter(this, c));	   listview.setOnItemClickListener(new ListItemClickListener());	   LinearLayout list = new LinearLayout(this);	   list.setBackgroundResource(R.drawable.listbg);	   LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(	   LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);	   list.addView(listview,params);	   setContentView(list);	   	    	}	 class ListItemClickListener implements OnItemClickListener{	    	@Override	    	public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {	    		// TODO Auto-generated method stub	    		Intent intent = new Intent(AlbumActivity.this,MusicActivity.class);	    		intent.putExtra("_ids", _ids);	    		intent.putExtra("_titles", _titles);	    		intent.putExtra("position", position);	    		startActivity(intent);	    		finish();	    	}	    		    }}



第二个类AlbumListAdapter
package com.alex.media;import java.util.HashMap;import android.app.Activity;import android.content.Context;import android.database.Cursor;import android.provider.MediaStore;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 AlbumListAdapter extends BaseAdapter{	private Context myCon;	private String[] albums;	private HashMap<String, String> myMap;	public AlbumListAdapter(Context con,String[] str1, HashMap<String, String> map){		myCon = con;		albums = str1;		myMap = map;	}		@Override	public int getCount() {		return albums.length;	}	@Override	public Object getItem(int position) {		return position;	}	@Override	public long getItemId(int position) {		return position;	}	@Override	public View getView(int position, View convertView, ViewGroup parent) {		convertView = LayoutInflater.from(myCon).inflate(R.layout.albumslist,				null);		/**		 * 设置专辑名		 */		TextView album = (TextView)convertView.findViewById(R.id.album);		if (albums[position].length()>24){			try {				String albumName = bSubstring(albums[position],24);				album.setText(albumName);			} catch (Exception e) {				e.printStackTrace();			}					} else {			album.setText(albums[position]);		}		/**		 * 设置艺术家姓名		 */		TextView artist = (TextView)convertView.findViewById(R.id.mysinger);		if (myMap.get(albums[position]).equals("<unknown>")){			artist.setText("未知艺术家");		} else{			artist.setText(myMap.get(albums[position]));		}				ImageView Albumsitem = (ImageView)convertView.findViewById(R.id.Albumsitem);		Albumsitem.setImageResource(R.drawable.album);		return convertView;	}		/**	 * 字符串裁剪	 * @param s	 * @param length	 * @return	 * @throws Exception	 */	public static String bSubstring(String s, int length) throws Exception  	{  	 	    byte[] bytes = s.getBytes("Unicode");  	    int n = 0; // 表示当前的字节数  	    int i = 2; // 要截取的字节数,从第3个字节开始  	    for (; i < bytes.length && n < length; i++)  	    {  	        // 奇数位置,如3、5、7等,为UCS2编码中两个字节的第二个字节  	        if (i % 2 == 1)  	        {  	            n++; // 在UCS2第二个字节时n加1  	        }  	        else 	        {  	            // 当UCS2编码的第一个字节不等于0时,该UCS2字符为汉字,一个汉字算两个字节  	            if (bytes[i] != 0)  	            {  	                n++;  	            }  	        }  	    }  	    // 如果i为奇数时,处理成偶数  	    if (i % 2 == 1)  	 	    {  	        // 该UCS2字符是汉字时,去掉这个截一半的汉字  	        if (bytes[i - 1] != 0)  	            i = i - 1;  	        // 该UCS2字符是字母或数字,则保留该字符  	        else 	            i = i + 1;  	    }  	 	    return new String(bytes, 0, i, "Unicode");  	}  }


第三个类ArtistActivity
package com.alex.media;import com.alex.media.RecentlyActivity.ListItemClickListener;import android.app.Activity;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.database.Cursor;import android.media.AudioManager;import android.os.Bundle;import android.provider.MediaStore;import android.view.View;import android.widget.AdapterView;import android.widget.LinearLayout;import android.widget.ListView;import android.widget.AdapterView.OnItemClickListener;import android.widget.LinearLayout.LayoutParams;public class ArtistActivity extends Activity {	private int[] _ids;	private String[]_titles;	private ListView listview;	@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		Intent intent = this.getIntent();		String artistName;		if (intent.getExtras().getString("artist").equals("未知艺术家")){			artistName = "<unknown>";		} else{			artistName = intent.getExtras().getString("artist");		}		listview = new ListView(this);		Cursor c = this.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,				new String[]{MediaStore.Audio.Media.TITLE,				MediaStore.Audio.Media.DURATION,				MediaStore.Audio.Media.ARTIST,				MediaStore.Audio.Media._ID,				MediaStore.Audio.Media.DISPLAY_NAME}, 				MediaStore.Audio.Media.ARTIST + "='" + artistName+"'", 				null,				null);	   c.moveToFirst();	   _ids = new int[c.getCount()];	   _titles = new String[c.getCount()];	   for(int i=0;i<c.getCount();i++){	       _ids[i] = c.getInt(3);	       _titles[i] = c.getString(0);	       c.moveToNext();	  }	   listview.setAdapter(new MusicListAdapter(this, c));	   listview.setOnItemClickListener(new ListItemClickListener());	   LinearLayout list = new LinearLayout(this);	   list.setBackgroundResource(R.drawable.listbg);	   LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(	   LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);	   list.addView(listview,params);	   setContentView(list);	   	    	}	 class ListItemClickListener implements OnItemClickListener{	    	@Override	    	public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {	    		// TODO Auto-generated method stub	    		Intent intent = new Intent(ArtistActivity.this,MusicActivity.class);	    		intent.putExtra("_ids", _ids);	    		intent.putExtra("_titles", _titles);	    		intent.putExtra("position", position);	    		startActivity(intent);	    		finish();	    	}	    		    }}


第四个类 ArtistListAdapter
package com.alex.media;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 ArtistListAdapter extends BaseAdapter{	private Context myCon;	private String[] artists;		public ArtistListAdapter(Context con,String[] str1){		myCon = con;		artists = str1;	}	@Override	public int getCount() {		return artists.length;	}	@Override	public Object getItem(int position) {		return position;	}	@Override	public long getItemId(int position) {		return position;	}	@Override	public View getView(int position, View convertView, ViewGroup parent) {		convertView = LayoutInflater.from(myCon).inflate(R.layout.artistslist,				null);				//设置艺术家姓名		TextView artist = (TextView)convertView.findViewById(R.id.artist);		artist.setText(artists[position]);				//设置列表项图标		ImageView Artistsitem = (ImageView)convertView.findViewById(R.id.Artistsitem);		Artistsitem.setImageResource(R.drawable.artist);		return convertView;	}}



第五个类ClicksActivity

package com.alex.media;import com.alex.media.ListActivity.ListItemClickListener;import android.app.Activity;import android.content.Context;import android.content.Intent;import android.database.Cursor;import android.media.AudioManager;import android.os.Bundle;import android.provider.MediaStore;import android.view.KeyEvent;import android.view.View;import android.widget.AdapterView;import android.widget.LinearLayout;import android.widget.ListView;import android.widget.AdapterView.OnItemClickListener;import android.widget.LinearLayout.LayoutParams;public class ClicksActivity extends Activity {	private DBHelper dbHelper = null;	private ListView listview;	private int[] _ids;	private String[]_titles;	Cursor cursor = null;	int[] music_id;	//关于音量的变量	private AudioManager mAudioManager = null;	private int maxVolume;//最大音量	private int currentVolume;//当前音量	@Override	protected void onCreate(Bundle savedInstanceState) {		// TODO Auto-generated method stub		super.onCreate(savedInstanceState);		dbHelper = new DBHelper(this, "music.db", null, 2);		cursor = dbHelper.queryByClicks();		cursor.moveToFirst();		int num;		if (cursor!=null){			num = cursor.getCount();		} else{			return;		}		String idString ="";		if (num>=10){			for(int i=0;i<10;i++){				music_id = new int[10];				music_id[i]=cursor.getInt(cursor.getColumnIndex("music_id"));				if (i<9){					idString = idString+music_id[i]+",";				} else{					idString = idString+music_id[i];				}				cursor.moveToNext();			} 		}else if(num>0){			for(int i=0;i<num;i++){				music_id = new int[num];				music_id[i]=cursor.getInt(cursor.getColumnIndex("music_id"));				if (i<num-1){					idString = idString+music_id[i]+",";				} else{					idString = idString+music_id[i];				}				cursor.moveToNext();			}		}		System.out.println(idString);		if (cursor!=null){			cursor.close();			cursor=null;		}		listview = new ListView(this);		Cursor c = this.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,        			new String[]{MediaStore.Audio.Media.TITLE,					MediaStore.Audio.Media.DURATION,					MediaStore.Audio.Media.ARTIST,					MediaStore.Audio.Media._ID,					MediaStore.Audio.Media.DISPLAY_NAME} , MediaStore.Audio.Media._ID + " in ("+ idString + ")", null, null);				  c.moveToFirst();	        _ids = new int[c.getCount()];	        _titles = new String[c.getCount()];	        for(int i=0;i<c.getCount();i++){	        	_ids[i] = c.getInt(3);	        	_titles[i] = c.getString(0);	        	c.moveToNext();	        }	        listview.setAdapter(new MusicListAdapter(this, c));	        listview.setOnItemClickListener(new ListItemClickListener());	        	        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); 			maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);//获得最大音量  			currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);//获得当前音量 			LinearLayout list = new LinearLayout(this);			list.setBackgroundResource(R.drawable.listbg);	        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(	        LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);	        list.addView(listview,params);	        setContentView(list);	    }	   	    class ListItemClickListener implements OnItemClickListener{	    	@Override	    	public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {	    		// TODO Auto-generated method stub	    		Intent intent = new Intent(ClicksActivity.this,MusicActivity.class);	    		intent.putExtra("_ids", _ids);	    		intent.putExtra("_titles", _titles);	    		intent.putExtra("position", position);	    			    		startActivity(intent);	    		finish();	    	}	    		    }	    public boolean onKeyDown(int keyCode, KeyEvent event) {			if (keyCode == event.KEYCODE_BACK) {				Intent intent = new Intent();				intent.setClass(this, MainActivity.class);				startActivity(intent);				finish();			}			return true;	    }	    public boolean dispatchKeyEvent(KeyEvent event) { 			int action = event.getAction(); 			int keyCode = event.getKeyCode(); 			switch (keyCode) { 				case KeyEvent.KEYCODE_VOLUME_UP: 				if (action == KeyEvent.ACTION_UP) {					if (currentVolume<maxVolume){						currentVolume = currentVolume + 1;						mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);					} else {						mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);					}				} 				return false; 				case KeyEvent.KEYCODE_VOLUME_DOWN: 				if (action == KeyEvent.ACTION_UP) { 					if (currentVolume>0){						currentVolume = currentVolume - 1;						mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume , 0);					} else {						mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);					}				} 				return false; 				default: 				return super.dispatchKeyEvent(event); 			} 		}}



第六个类DBHelper


package com.alex.media;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.database.sqlite.SQLiteDatabase.CursorFactory;public class DBHelper extends SQLiteOpenHelper {	private Cursor c = null;	private static final String CREATE_TAB = "create table "		+ "music(_id integer primary key autoincrement,music_id integer,clicks integer," +				"latest text)";	private static final String TAB_NAME = "music";	private SQLiteDatabase db = null;	public DBHelper(Context context, String name, CursorFactory factory,			int version) {		super(context, name, factory, version);	}	@Override	public void onCreate(SQLiteDatabase db) {		this.db = db;		db.execSQL(CREATE_TAB);	}		public void insert(ContentValues values){		SQLiteDatabase db = getWritableDatabase();		db.insert(TAB_NAME, null, values);	}	public void update(ContentValues values,int id){		SQLiteDatabase db = getWritableDatabase();		db.update(TAB_NAME, values, "music_id="+id, null);	}		public void delete(int id){		if (db == null){			db = getWritableDatabase();		}		db.delete(TAB_NAME, "music_id=?", new String[]{String.valueOf(id)});	}		public Cursor query(int id){		SQLiteDatabase db = getReadableDatabase();		c = db.query(TAB_NAME, null, "music_id=?", new String[]{String.valueOf(id)}, null, null, null);		return c;	}		public Cursor queryByClicks(){//按点击量查询		SQLiteDatabase db = getReadableDatabase();		c = db.query(TAB_NAME, null, null, null, null, null, "clicks desc");		return c;	}		public Cursor queryRecently(){//按时间降序查询		SQLiteDatabase db = getReadableDatabase();		c = db.query(TAB_NAME, null, null, null, null, null, "latest desc");		return c;	}		public void close(){		if (db != null){			db.close();			db=null;		}		if (c!=null){			c.close();			c=null;		}	}		@Override	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {	}}
  相关解决方案