安卓音乐播放器开发含源代码
安卓音乐播放器开发,含源代码
基于android平台的音乐播放器开发实验报告For personal use only in study and research; not for commercial use学生姓名:温从林学号:0215班级:计自1201第一章引言1.1 项目背景当今社会的生活节奏越来越快,人们对手机的要求也越来越高,由于手机市场发展迅速,使得手机操作系统也出现了不同各类,现在的市场上主要有三个手机操作系统,Windows mobile,symbian,以及谷歌的Android操作系统,其中占有开放源代码优势的Android系统有最大的发展前景。
那么能否在手机上拥有自己编写的个性音乐播放器呢?能的,谷歌Android系统就能做到。
本文的音乐播放器就是基于谷歌Android手机平台的播放器。
Android:是谷歌于2007年公布的开放式源代码手机系统,它的开放性就优于其它封闭式的手机系统,因此,任何人都可能根据自己的喜好将手机系统中的所有功能重新编写。
这使得越来越多的人关注这个操作系统。
本次作品音乐播放器就是基于Android平台的。
1.2 编写目的现今社会生活紧张,而欣赏音乐是其中最好的舒缓压力的方式之一,本项目的目的是开发一个可以播放主流音乐文件格式的播放器,本设计实现的主要功能是播放Mp3,Wav多种格式的音乐文件,并且能够控制播放,暂停,停止,播放列等基本播放控制功能,界面简明,操作简单。
本项目是一款基于Android手机平台的音乐播放器,使Android手机拥有个性的多媒体播放器,使手机显得更生动灵活化,与人们更为接近,让手机主人随时随地处于音乐视频的旋律之中。
使人们的生活更加多样化。
也使设计者更加熟练Android的技术和其它在市场上的特点。
1.3 开发环境Eclipse、Android SDK 3.2.0第二章系统需求分析2.1 功能需求(用例图分析)根据项目的目标,我们可获得项目系统的基本需求,以下从不同角度来描述系统的需求,并且使用用例图来描述,系统的功能需求,我们分成四部分来概括,即播放器的基本控制需要,播放列表管理需求,播放器友好性需求和播放器扩展卡需求。
android 开发之音乐播放器代码
package com.Aina.Android;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FilenameFilter;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.TreeMap;import android.app.Activity;import android.app.AlertDialog;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.app.AlertDialog.Builder;import android.content.ActivityNotFoundException; import android.content.DialogInterface;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.media.MediaPlayer;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.util.Log;import android.view.KeyEvent;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.ImageButton;import android.widget.ImageView;import android.widget.ListView;import android.widget.ScrollView;import android.widget.SeekBar;import android.widget.TextView;import android.widget.Toast;public class ActivityMain extends Activity{ /** Called when the activity is first created. */private ViewlrcKLOK viewlrcKLOK;private MediaPlayer mMediaPlayer = null;private SeekBar mSeekBar = null;private ListView mListView = null;private ImageButton mLastbtn = null;private ImageButton mStartbtn = null;private ImageButton mPausebtn = null;private ImageButton mStopbtn = null;private ImageButton mNextbtn = null;private TextView mTextView = null;private ScrollView scrollview =null;private ImageView header =null;private TextView lrc = null;private List<String> mMusiclist = null;private int mCurrent = 0;private int count = 0;private boolean isrun = false;private boolean isauto = false;private static final String PA TH = "/sdcard/mp3/";private static TreeMap<Integer, lrcObject> lrc_map;private static int lrc_timeend =0;private long KeyDownOldTime =0;private int KeyDownCount =0;private String songName ="";private String songAuthor ="";private NotificationManager mNotificationManager;private static int NOTIFICA TIONS_ID = yout.main;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.main);mListView = (ListView) this.findViewById(R.id.lv_music);mSeekBar = (SeekBar) this.findView ById(R.id.SeekBar01);mTextView = (TextView) this.findV iewById(R.id.mTextV iew);viewlrcKLOK = (ViewlrcKLOK) this.findView ById(R.id.lrc_view);lrc = (TextView) this.findViewById(R.id.lrc);scrollview = (ScrollView) this.findView ById(R.id.scrollview);mLastbtn = (ImageButton) this.findView ById(R.id.imgbtn_last);mStartbtn = (ImageButton) this.findViewById(R.id.imgbtn_start);mPausebtn = (ImageButton) this.findViewById(R.id.imgbtn_pause);mStopbtn = (ImageButton) this.findViewById(R.id.imgbtn_stop);mNextbtn = (ImageButton) this.findViewById(R.id.imgbtn_next);header = (ImageView) this.findViewById(R.id.header);mMusiclist = new ArrayList<String>();mMediaPlayer = new MediaPlayer();lrc_map = new TreeMap<Integer, lrcObject>();viewlrcKLOK.SetlrcContent("歌词",0,0,"......",0);lrc_timeend = 0;lrc.setV isibility(View.GONE);mNotificationManager = (NotificationManager) getSystemService(NOTIFICA TION_SERVICE);mMediaPlayer.setOnPreparedListener(prepareListener);mMediaPlayer.setOnCompletionListener(CompletionListener);mMediaPlayer.setOnErrorListener(ErrorListener);// 开始按钮mStartbtn.setOnClickListener(new ImageButton.OnClickListener() {@Overridepublic void onClick(View v) {//lrc.setV isibility(View.GONE); //控件隐藏PlayMusic(PA TH + mMusiclist.get(mCurrent));}});// 下一首mNextbtn.setOnClickListener(new ImageButton.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubNextMusic();}});// 上一首mLastbtn.setOnClickListener(new ImageButton.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubLastMusic();}});// 暂停mPausebtn.setOnClickListener(new ImageButton.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubisrun = true;isauto = false;mPausebtn.setVisibility(V iew.GONE);// 隐藏暂停按钮mStartbtn.setV isibility(View.VISIBLE);// 显示启动按钮// 是否正在播放if (mMediaPlayer.isPlaying()) {viewlrcKLOK.Stop();mMediaPlayer.pause();}}});// 停止mStopbtn.setOnClickListener(new ImageButton.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubStopMusic();}});mListView.setOnItemClickListener(new ListView.OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> arg0, V iew arg1, int arg2, long arg3) {mCurrent = arg2;StopMusic();PlayMusic(PA TH + mMusiclist.get(mCurrent));}});mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {@Overridepublic void onProgressChanged(SeekBar seekBar,int progress, boolean fromUser) {if (!isauto) {mMediaPlayer.seekTo(progress);}}@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {isauto = false;}@Overridepublic void onStopTrackingTouch(SeekBar seekBar) {isauto = true;}});this.MusicList();}private void setPlayint(String tickerText, String title, String content,int drawable) {Notification notification = new Notification(drawable, tickerText,System.currentTimeMillis());PendingIntent contentIntent = PendingIntent.getActivity(this, 0,new Intent(this, ActivityMain.class), 0);notification.setLatestEventInfo(this, title, content, contentIntent);mNotificationManager.notify(NOTIFICA TIONS_ID, notification);}private MediaPlayer.OnPreparedListener prepareListener = new MediaPlayer.OnPreparedListener(){public void onPrepared(MediaPlayer mp){isrun = true;setPlayint(songAuthor,songName, songAuthor, R.drawable.icon);lrc_timeend = 0;viewlrcKLOK.SetlrcContent("准备好",0,0,"go,go,go..",0);viewlrcKLOK.Star();count = mMediaPlayer.getDuration();Log.i("TAG-count", count + "");mSeekBar.setMax(count);// 设置最大值.mTextView.setText("当前播放歌曲:" + mMusiclist.get(mCurrent));mp.start(); //开始播放//Toast.makeText(ActivityMain.this, "开始播放",Toast.LENGTH_SHORT).show();myHandler.sendEmptyMessage(PROGRESS_CHANGED);}};//视频播放完成private MediaPlayer.OnCompletionListener CompletionListener=new MediaPlayer.OnCompletionListener(){@Overridepublic void onCompletion(MediaPlayer arg0) {mMediaPlayer.stop();isauto = true;mSeekBar.setProgress(0);viewlrcKLOK.SetlrcContent("准备好",0,0,"... ...",0);viewlrcKLOK.Stop();//Toast.makeText(ActivityMain.this, "播放完成:",Toast.LENGTH_SHORT).show();NextMusic();}};//播放时发现错误private MediaPlayer.OnErrorListener ErrorListener=new MediaPlayer.OnErrorListener(){ @Overridepublic boolean onError(MediaPlayer mp, int what, int extra) {// TODO Auto-generated method stubmMediaPlayer.stop();Toast.makeText(ActivityMain.this, "发现错误:-错误编号:"+what,Toast.LENGTH_SHORT).show();return true;}};public void PlayMusic(String path) {try {String lrcpath = path;//装载歌词lrcpath = lrcpath.substring(0,lrcpath.length()-4)+".lrc";this.lrc.setText(read(lrcpath));//Toast.makeText(this,"打开",Toast.LENGTH_SHORT).show();//装载头像String headerFile = path.substring(PA TH.length());int pos1 = headerFile.indexOf("-");int pos2 = headerFile.indexOf(".");if (pos1>=0){songName = headerFile.substring(pos1+1,pos2);headerFile = headerFile.substring(0,pos1);songAuthor = headerFile.trim();}headerFile = PA TH+"pic/"+headerFile.trim()+".jpg";//Toast.makeText(this, headerFile, Toast.LENGTH_SHORT).show();File myFile = new File(headerFile);if (myFile.exists()){Bitmap bm = BitmapFactory.decodeFile(headerFile);header.setImageBitmap(bm);}else{Bitmap bm = BitmapFactory.decodeResource(this.getResources(),R.drawable.back4);header.setImageBitmap(bm);}mStartbtn.setV isibility(View.GONE);// 隐藏启动按钮mPausebtn.setVisibility(V iew.VISIBLE);// 显示暂停按钮if (!isrun) {mMediaPlayer.reset();// 重置mMediaPlayer.setDataSource(path);// 设置数据源mMediaPlayer.prepare();// 准备} else {mMediaPlayer.start();// 暂停之后接着播放viewlrcKLOK.Star();}isauto = true;} catch (Exception ex) {this.ShowDialog("播放音乐异常:" + ex.getMessage());}}//创建一个消息处理private final static int PROGRESS_CHANGED = 0;private final static int HIDE_CONTROLER = 1;private final static int VIDEO_READY =3;Handler myHandler = new Handler(){@Overridepublic void handleMessage(Message msg) {switch(msg.what){case VIDEO_READY:break;case PROGRESS_CHANGED:{int nowTime = mMediaPlayer.getCurrentPosition();if (nowTime<count){mSeekBar.setProgress(nowTime);mSeekBar.invalidate();if (nowTime>lrc_timeend && isrun){//查找歌词Iterator<Integer> iterator = lrc_map.keySet().iterator();while(iterator.hasNext()) {Object ob =iterator.next();lrcObject val = (lrcObject)lrc_map.get(ob);if (nowTime>val.begintime){lrcObject val_1 = new lrcObject();val_1.begintime = 0;val_1.lrc ="...";val_1.timeline = 0;if (iterator.hasNext()){Object ob_1 =iterator.next();val_1 = (lrcObject)lrc_map.get(ob_1);}lrc_timeend = val_1.begintime+val_1.timeline;viewlrcKLOK.SetlrcContent(val.lrc,val.timeline,val_1.begintime-val.begintime-val.timeline, val_1.lrc,val_1.timeline);viewlrcKLOK.invalidate();}}}nowTime/=1000;int minute = nowTime/60;int hour = minute/60;int second = nowTime%60;minute %= 60;//mTextView.setText(String.format("%02d",nowTime));mTextView.setText(String.format("%02d:%02d:%02d", hour,minute,second));}sendEmptyMessage(PROGRESS_CHANGED);}break;case HIDE_CONTROLER:break;}super.handleMessage(msg);}};public void NextMusic() {int num = mMusiclist.size();if (++mCurrent >= num) {mCurrent = 0;}StopMusic();PlayMusic(PA TH + mMusiclist.get(mCurrent));}public void LastMusic() {int num = mMusiclist.size();if (--mCurrent < 0) {mCurrent = num - 1;}StopMusic();PlayMusic(PA TH + mMusiclist.get(mCurrent));}@Overrideprotected void onPause() {super.onPause();/*Dialog dialog = new AlertDialog.Builder(this).setTitle("对话框标题") .setIcon(R.drawable.icon).setMessage("登陆对话框")// 设置对话框显示一个单选的list.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubfinish();}}).setNeutralButton("退出", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stub}}).create();dialog.show();*/setPlayint(songAuthor,songName, songAuthor, R.drawable.icon);}/*** 销毁*/@Overrideprotected void onDestroy() {isauto = false;if (mMediaPlayer.isPlaying()) {mMediaPlayer.stop();// 停止}mMediaPlayer.reset();mMediaPlayer.release();super.onDestroy();}protected void dialog() {AlertDialog.Builder builder = new Builder(ActivityMain.this);builder.setMessage("确定要退出吗?");builder.setTitle("提示");builder.setPositiveButton("确认",new android.content.DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();mNotificationManager.cancel(NOTIFICA TIONS_ID);android.os.Process.killProcess(android.os.Process.myPid());}});builder.setNegativeButton("取消",new android.content.DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {onPause();dialog.dismiss();}});builder.create().show();}@Overridepublic boolean onKeyDown(int keyCode,KeyEvent event){if (keyCode==79)//耳机键{long time = System.currentTimeMillis();if ((time-KeyDownOldTime)/1000>5)KeyDownCount = 0;KeyDownCount++;Toast.makeText(this, "按键次数:"+event.getRepeatCount()+"所用时间:"+(time-KeyDownOldTime)/1000, Toast.LENGTH_SHORT).show();KeyDownOldTime = time;}else if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {dialog();return true;}return super.onKeyDown(keyCode, event);/*if (keyCode == KeyEvent.KEYCODE_BACK) {PackageManager pm = getPackageManager();ResolveInfo homeInfo = pm.resolveActivity(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CA TEGORY_HOME), 0);ActivityInfo ai = homeInfo.activityInfo;Intent startIntent = new Intent(Intent.ACTION_MAIN);startIntent.addCategory(Intent.CA TEGORY_LAUNCHER);startIntent.setComponent(new ComponentName(ai.packageName,));startActivitySafely(startIntent);return true;} elsereturn super.onKeyDown(keyCode, event);*/}void startActivitySafely(Intent intent) {intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);try {startActivity(intent);} catch (ActivityNotFoundException e) {} catch (SecurityException e) {}}public void StopMusic() {isrun = false;viewlrcKLOK.Stop();lrc_timeend = 99999;mPausebtn.setVisibility(V iew.GONE);// 隐藏暂停按钮mStartbtn.setV isibility(View.VISIBLE);// 显示启动按钮if (mMediaPlayer.isPlaying()) {mMediaPlayer.stop();// 停止}}/*** 文件过滤器** @author Aina**/class MusicFilter implements FilenameFilter {@Overridepublic boolean accept(File dir, String filename) {return (filename.endsWith(".mp3"));}}/*** 读取文件*/public static String read(String file) {TreeMap<Integer, lrcObject> lrc_read =new TreeMap<Integer, lrcObject>();String data = "";try {File saveFile=new File(file);FileInputStream stream = new FileInputStream(saveFile);// context.openFileInput(file);BufferedReader br = new BufferedReader(newInputStreamReader(stream,"GB2312"));int i = 0;while ((data = br.readLine()) != null) {data = data.replace("[","");data = data.replace("]","@");String splitdata[] =data.split("@");String lrcContenet = splitdata[splitdata.length-1];for (int j=0;j<splitdata.length-1;j++){String tmpstr = splitdata[j];tmpstr = tmpstr.replace(":",".");tmpstr = tmpstr.replace(".","@");String timedata[] =tmpstr.split("@");int m = Integer.parseInt(timedata[0]); //分int s = Integer.parseInt(timedata[1]); //秒int ms = Integer.parseInt(timedata[2]); //毫秒int currTime = (m*60+s)*1000+ms*10;lrcObject item1= new lrcObject();item1.begintime = currTime;item1.lrc = lrcContenet;lrc_read.put(currTime,item1);// 图像资源的IDi++;}}stream.close();}catch (FileNotFoundException e) {}catch (IOException e) {}/** 遍历hashmap 计算每句歌词所需要的时间*/lrc_map.clear();data ="";Iterator<Integer> iterator = lrc_read.keySet().iterator();lrcObject oldval = null;int i =0;StringBuffer sb = new StringBuffer();while(iterator.hasNext()) {Object ob =iterator.next();lrcObject val = (lrcObject)lrc_read.get(ob);if (oldval==null)oldval = val;else{lrcObject item1= new lrcObject();item1 = oldval;item1.timeline = val.begintime-oldval.begintime;lrc_map.put(new Integer(i), item1);sb.append(String.format("[%04d]-[%04d]-%s\n",item1.begintime,item1.timeline,item1.lrc));i++;oldval = val;}}data = sb.toString();return data;}/*** 播放列表*/public void MusicList() {try {File home = new File(PA TH);File[] f = home.listFiles(new MusicFilter());if (f.length > 0) {for (int i = 0; i < f.length; i++) {File file = f[i];mMusiclist.add(file.getName().toString());}ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,yout.simple_list_item_1, mMusiclist);mListView.setAdapter(adapter);}} catch (Exception ex) {this.ShowDialog("显示音乐列表异常:" + ex.getMessage());}}public void ShowDialog(String str) {new AlertDialog.Builder(this).setTitle("提示").setMessage(str).setPositiveButton("OK", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {}}).show();}/*@Overridepublic void run() {// TODO Auto-generated method stubwhile (true) {try {if (isauto) {int n = mMediaPlayer.getCurrentPosition();Message msg = new Message();msg.what = n;handler.sendMessage(msg);}Thread.sleep(100);} catch (Exception ex) {ex.printStackTrace();}}}*/}第二部分package com.Aina.Android;public class lrcObject {public int begintime;public int endtime;public int timeline;public String lrc;}第三部分package com.Aina.Android;import android.content.Context;import android.graphics.Bitmap;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Rect;import android.graphics.Bitmap.Config;import android.util.AttributeSet;import android.view.View;public final class V iewlrcKLOK extends View implements Runnable { private final Paint paint;private Bitmap mBitlrcBack = null;private Bitmap mBitlrc = null;private Canvas lrc_backCanvas =null;private Canvas lrc_Canvas = null;private Canvas lrc_backNextCanvas =null;private Bitmap mBitlrcNextBack = null;private Canvas lrc_Canvas1 = null;private Bitmap mBitlrc1 = null;private int lrcWidth = 0;private int lrcWidth1 = 0;private int lrcHeight = 0;private int lrcSpeed = 100;private int lrcSpeed1 = 100;private int movex = 0;private int movex1 = 0;private int dispIndex = 0;private int mTimeduff = 0;private int DisplayWidth;//屏幕宽带private int DisplayHeight;//屏幕高度private String lrc_content="这是一个测试"; //歌词内容private String lrc_Nextcontent=""; //歌词内容private int lrc_timelen = 0;private int lrc_timelen1 = 0;private Thread ThreadKLOK =null;private int nState = 0;public V iewlrcKLOK(Context context,AttributeSet attrs) {super(context,attrs);paint = new Paint();//DisplayMetrics displayMetrics = new DisplayMetrics();//this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);//DisplayHeight = displayMetrics.heightPixels;//DisplayWidth = displayMetrics.widthPixels;ThreadKLOK = new Thread(this);ThreadKLOK.start();}@Overridepublic void onDraw(Canvas canvas) {Rect frame = new Rect();// canvas.drawText("speed"+lrcSpeed, 2, 30, paint);if (mBitlrc==null)return;this.DrawImage(canvas, mBitlrcBack,2, 8,lrcWidth,lrcHeight,0,0);this.DrawImage(canvas, mBitlrc,2, 8,movex,lrcHeight,0,0);this.DrawImage(canvas, mBitlrcNextBack,20, lrcHeight+15,lrcWidth1,lrcHeight,0,0);this.DrawImage(canvas, mBitlrc1,20, lrcHeight+15,movex1,lrcHeight,0,0);}@Overridepublic void run() {while (!Thread.interrupted()) {try {if (nState==1){if (dispIndex==0){if (movex<lrcWidth)movex++;else{movex1 = 0;dispIndex = 1;Thread.sleep(mTimeduff);}Thread.sleep(lrcSpeed);}else{if (movex1<lrcWidth1)movex1++;Thread.sleep(lrcSpeed1);}}} catch (Exception ex) {ex.printStackTrace();Thread.currentThread().interrupt();}this.postInvalidate();}}/*** x:屏幕上的x坐标* y:屏幕上的y坐标* w:要绘制的图片的宽度* h:要绘制的图片的高度* bx:图片上的x坐标* by:图片上的y坐标** @param canvas* @param mBitmap* @param x* @param y* @param w* @param h* @param bx* @param by*/public void DrawImage(Canvas canvas, Bitmap mBitmap, int x, int y, int w, int h, int bx, int by) {Rect src = new Rect();// 图片裁剪区域Rect dst = new Rect();// 屏幕裁剪区域src.left = bx;src.top = by;src.right = bx + w;src.bottom = by + h;dst.left = x;dst.top = y;dst.right = x + w;dst.bottom = y + h;canvas.drawBitmap(mBitmap, src, dst, paint);src = null;dst = null;}public void SetlrcContent(String lrc,int tiemlen,int timeduff,String lrc_1,int timelen1) {ThreadKLOK.suspend();lrc_content = lrc;lrc_timelen = tiemlen;lrc_timelen1 = timelen1;movex = 0;movex1 = 0;dispIndex = 0;paint.setTextSize(24);Rect rect = new Rect();mTimeduff = timeduff;//返回包围整个字符串的最小的一个Rect区域paint.getTextBounds(lrc, 0, 1, rect);float strwid = paint.measureText(lrc);float strwid1 = paint.measureText(lrc_1);lrcWidth = (int)strwid;lrcWidth1 = (int)strwid1;lrcHeight = 23;if (lrc_timelen>0)lrcSpeed = (lrc_timelen/lrcWidth);elselrcSpeed = 1000;if (lrc_timelen1>0)lrcSpeed1 = (lrc_timelen1/lrcWidth1);elselrcSpeed1 = 1000;mBitlrcBack = Bitmap.createBitmap( lrcWidth,lrcHeight, Config.ARGB_8888 ); mBitlrc = Bitmap.createBitmap( lrcWidth,lrcHeight, Config.ARGB_8888 );mBitlrcNextBack = Bitmap.createBitmap(lrcWidth1,lrcHeight, Config.ARGB_8888); mBitlrc1 = Bitmap.createBitmap(lrcWidth1,lrcHeight, Config.ARGB_8888 );lrc_backCanvas = new Canvas(mBitlrcBack);lrc_Canvas = new Canvas(mBitlrc);lrc_Canvas1 = new Canvas(mBitlrc1);lrc_backNextCanvas = new Canvas(mBitlrcNextBack);/*paint.setColor(Color.GREEN);rect.top = 0;rect.left = 0;rect.right =lrcWidth;rect.bottom = lrcHeight;lrc_backCanvas.drawRect(rect, paint);*/paint.setColor(Color.WHITE);lrc_backCanvas.drawText(lrc_content, 0, 20, paint);lrc_backNextCanvas.drawText(lrc_1, 0, 20, paint);paint.setColor(Color.RED);lrc_Canvas.drawText(lrc_content, 0, 20, paint);lrc_Canvas1.drawText(lrc_1, 0, 20, paint);}public void Star(){ThreadKLOK.resume();nState = 1;}public void Stop(){ThreadKLOK.suspend();nState =0;}}。
Android下MP3播放器的实现源代码
MusicInfoController.javapackage com.yarin.android.MusicPlayer;import android.content.ContentResolver;import android.database.Cursor;import .Uri;import android.provider.MediaStore;public class MusicInfoController{private static MusicInfoController mInstance = null;private MusicPlayerApp pApp = null;public static MusicInfoController getInstance(MusicPlayerApp app){if (mInstance == null){mInstance = new MusicInfoController(app);}return mInstance;}private MusicInfoController(MusicPlayerApp app){pApp = app;}public MusicPlayerApp getMusicPlayer(){return pApp;}private Cursor query(Uri uri, String[] prjs, String selections, String[] selectArgs, String order){ ContentResolver resolver = pApp.getContentResolver();if (resolver == null){return null;}return resolver.query(uri, prjs, selections, selectArgs, order);}public Cursor getAllSongs(){return query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);MusicList.javapackage com.yarin.android.MusicPlayer;import android.app.ListActivity;import android.content.BroadcastReceiver;import ponentName;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.content.ServiceConnection;import android.database.Cursor;import android.os.Bundle;import android.os.IBinder;import android.provider.MediaStore;import android.view.View;import android.widget.Button;import android.widget.ListAdapter;import android.widget.ListView;import android.widget.SimpleCursorAdapter;import android.widget.T extView;public class MusicList extends ListActivity{private MusicPlayerService mMusicPlayerService = null;private MusicInfoController mMusicInfoController = null;private Cursor mCursor = null;private TextView mTextView = null;private Button mPlayPauseButton = null;private Button mStopButton = null;private ServiceConnection mPlaybackConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { mMusicPlayerService = ((MusicPlayerService.LocalBinder)service).getService();}public void onServiceDisconnected(ComponentName className){ mMusicPlayerService = null;}};protected BroadcastReceiver mPlayerEvtReceiver = new BroadcastReceiver() { @Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();if (action.equals(MusicPlayerService.PLAYER_PREPARE_END)) {// will begin to playmTextView.setVisibility(View.INVISIBLE); mPlayPauseButton.setVisibility(View.VISIBLE);mStopButton.setVisibility(View.VISIBLE);mPlayPauseButton.setText(R.string.pause);} else if(action.equals(MusicPlayerService.PLAY_COMPLETED)){ mPlayPauseButton.setText(R.string.play);}}};public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.list_layout);MusicPlayerApp musicPlayerApp=(MusicPlayerApp)getApplication(); mMusicInfoController =(musicPlayerApp).getMusicInfoController();// bind playback servicestartService(new Intent(this,MusicPlayerService.class));bindService(new Intent(this,MusicPlayerService.class), mPlaybackConnection,Context.BIND_AUTO_CREATE);mTextView = (TextView)findViewById(R.id.show_text); mPlayPauseButton = (Button)findViewById(R.id.play_pause_btn); mStopButton = (Button) findViewById(R.id.stop_btn);mPlayPauseButton.setOnClickListener(new Button.OnClickListener() {public void onClick(View v) {// Perform action on clickif (mMusicPlayerService != null && mMusicPlayerService.isPlaying()) { mMusicPlayerService.pause();mPlayPauseButton.setText(R.string.play);} else if (mMusicPlayerService != null){mMusicPlayerService.start();mPlayPauseButton.setText(R.string.pause);}}});mStopButton.setOnClickListener(new Button.OnClickListener() {public void onClick(View v) {// Perform action on clickif (mMusicPlayerService != null ) {mTextView.setVisibility(View.VISIBLE);mPlayPauseButton.setVisibility(View.INVISIBLE);mStopButton.setVisibility(View.INVISIBLE); mMusicPlayerService.stop();}}});IntentFilter filter = new IntentFilter();filter.addAction(MusicPlayerService.PLAYER_PREPARE_END);filter.addAction(MusicPlayerService.PLAY_COMPLETED);registerReceiver(mPlayerEvtReceiver, filter);}protected void onResume() {super.onResume();mCursor = mMusicInfoController.getAllSongs();ListAdapter adapter = new MusicListAdapter(this,yout.simple_expandable_list_item_2, mCursor, new String[]{}, new int[]{});setListAdapter(adapter);}protected void onListItemClick(ListView l, View v, int position, long id) {super.onListItemClick(l, v, position, id);if (mCursor == null ||mCursor.getCount() == 0) {return;}mCursor.moveToPosition(position);String url = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));mMusicPlayerService.setDataSource(url);mMusicPlayerService.start();}/********************************************************************/class MusicListAdapter extends SimpleCursorAdapter {public MusicListAdapter(Context context, int layout, Cursor c,String[] from, int[] to) { super(context, layout, c, from, to);}public void bindView(View view, Context context, Cursor cursor) {super.bindView(view, context, cursor);TextView titleView = (TextView) view.findViewById(android.R.id.text1);TextView artistView = (TextView) view.findViewById(android.R.id.text2);titleView.setText(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)));artistView.setText(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)));//int duration cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));}public static String makeTimeString(long milliSecs) {StringBuffer sb = new StringBuffer();long m = milliSecs / (60 * 1000);sb.append(m < 10 ? "0" + m : m);sb.append(":");long s = (milliSecs % (60 * 1000)) / 1000;sb.append(s < 10 ? "0" + s : s);return sb.toString();}MusicPlayerApp.java package com.yarin.android.MusicPlayer;import android.app.Application;public class MusicPlayerApp extends Application{private MusicInfoController mMusicInfoController = null;public void onCreate(){ super.onCreate();mMusicInfoController = MusicInfoController.getInstance(this); }public MusicInfoController getMusicInfoController(){return mMusicInfoController;}}MusicPlayerService.javapackage com.yarin.android.MusicPlayer;import java.io.IOException;import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.os.Binder;import android.os.IBinder;public class MusicPlayerService extends Service{private final IBinder mBinder = new LocalBinder();private MediaPlayer mMediaPlayer = null;public static final String PLAYER_PREPARE_END = "com.yarin.musicplayerservice.prepared";public static final String PLAY_COMPLETED = "com.yarin.musicplayerservice.playcompleted";MediaPlayer.OnCompletionListener mCompleteListener = new MediaPlayer.OnCompletionListener(){public void onCompletion(MediaPlayer mp){ broadcastEvent(PLAY_COMPLETED);}};MediaPlayer.OnPreparedListener mPrepareListener = new MediaPlayer.OnPreparedListener(){public void onPrepared(MediaPlayer mp){ broadcastEvent(PLAYER_PREPARE_END);}};private void broadcastEvent(String what){Intent i = new Intent(what); sendBroadcast(i);}public void onCreate(){super.onCreate();mMediaPlayer = new MediaPlayer(); mMediaPlayer.setOnPreparedListener(mPrepareListener);mMediaPlayer.setOnCompletionListener(mCompleteListener);}public class LocalBinder extends Binder{public MusicPlayerService getService(){return MusicPlayerService.this;public IBinder onBind(Intent intent){return mBinder;}public void setDataSource(String path){try{mMediaPlayer.reset();mMediaPlayer.setDataSource(path); mMediaPlayer.prepare();}catch (IOException e){return;}catch (IllegalArgumentException e){return;}}public void start(){mMediaPlayer.start();}public void stop(){mMediaPlayer.stop();}public void pause(){mMediaPlayer.pause();public boolean isPlaying(){return mMediaPlayer.isPlaying();}public int getDuration(){return mMediaPlayer.getDuration();}public int getPosition(){return mMediaPlayer.getCurrentPosition();}public long seek(long whereto){mMediaPlayer.seekTo((int) whereto);return whereto;}}。
Androidstudio简单的音乐播放器实现
Androidstudio简单的音乐播放器实现JAVA文件:MainActivity.java,menuActivity.java,Music.java,PreActivity.javaXML文件:activity_main.xml,activity_pre.xml,activity_menu.xml在PreActivity.java文件中,程序主要执行开启线程,实现开启软件进入欢迎界面,并在1秒后自动跳转到音乐播放器主界面,界面在activity_pre.xml文件中实现。
PreActivity.javapublic class PreActivity extends Activity {Handler handler=new Handler(){public void handleMessage(Message msg){if(msg.what==250){Intent intent=new Intent(PreActivity.this,MainActivity.class);startActivity(intent);finish();}};};@Overrideprotected void onCreate(Bundle savedInstanceState){//TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(yout.activity_pre); //加载布局WaitThread thread=new WaitThread(); //开启线程thread.start();}public class WaitThread extends Thread{ //创建线程@Overridepublic void run(){//TODO Auto-generated method stubtry{Thread.sleep(1000);}catch (InterruptedException e){//TODO Auto-generated catch blocke.printStackTrace();}Message message=new Message();message.what=250;message.arg1=1;handler.sendMessage(message);}}}activity_pre.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android=""android:layout_width="400dp"android:layout_height="800dp"android:background="#ffffff"android:orientation="vertical"android:weightSum="1"><ImageViewandroid:src="@drawable/welcome"android:layout_width="408dp"android:layout_height="451dp"android:layout_weight="0.77" /></LinearLayout>主要功能实现MainActivity.java,音乐播放器主界面activity_main.xml。
Android Studio Service编程 音乐播放器
广州xx 学院Android 程序设计 实验报告专业班级 计算机181 实验日期__ 2021.5.18_ _ 姓 名 xx 学 号201xx 实验名称 Service 编程 指导老师__ xx _(报告内容包括:实验目的、实验设备及器材、实验步骤、实验数据、图表及曲线处理、实验小结等)。
1. 实验目的(1) 了解如何创建服务;(2) 掌握服务的两种启动方式;(3) 掌握如何使用本地服务通信。
2. 实验要求(1) 使用服务通信,实现音乐播放器功能,实现音乐的播放、暂停、继续播放、退出。
3. 实验步骤(1)导入音乐文件和界面图片之后,开始创建布局,代码如下,效果图如图1-1所示。
<ImageViewandroid :id ="@+id/iv_music"android :layout_width ="240dp"android :layout_height ="240dp"android :layout_gravity ="center_horizontal" android :layout_margin ="15dp"android :src ="@drawable/music"/><SeekBarandroid :id ="@+id/sb"android :layout_width ="match_parent"android :layout_height ="wrap_content" /><RelativeLayoutandroid :layout_width ="match_parent"android :layout_height ="wrap_content"android:paddingLeft="8dp"android:paddingRight="8dp"><TextViewandroid:id="@+id/tv_progress"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="00:00" /><TextViewandroid:id="@+id/tv_total"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:text="00:00" /></RelativeLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><Buttonandroid:id="@+id/btn_play"android:layout_width="0dp"android:layout_height="40dp"android:layout_margin="8dp"android:layout_weight="1"android:background="@drawable/btn_bg_selector"android:text="播放音乐" /><Buttonandroid:id="@+id/btn_pause"android:layout_width="0dp"android:layout_height="40dp"android:layout_margin="8dp"android:layout_weight="1"android:background="@drawable/btn_bg_selector"android:text="暂停播放" /><Buttonandroid:id="@+id/btn_continue_play"android:layout_width="0dp"android:layout_height="40dp"android:layout_margin="8dp"android:layout_weight="1"android:background="@drawable/btn_bg_selector"android:text="继续播放" /><Buttonandroid:id="@+id/btn_exit"android:layout_width="0dp"android:layout_height="40dp"android:layout_margin="8dp"android:layout_weight="1"android:background="@drawable/btn_bg_selector"android:text="退出" /></LinearLayout>图1-1 界面布局效果图(2)创建背景选择器btn_bg_selector.xml关键代码如下:<selector xmlns:android="/apk/res/android"><item android:state_pressed="true" ><shape android:shape="rectangle"><corners android:radius="3dp"/><solid android:color="#d4d4d4"/></shape></item><item android:state_pressed="false" ><shape android:shape="rectangle"><corners android:radius="3dp"/><solid android:color="#ffffff" /></shape></item></selector>(3)创建MusicService服务关键代码如下所示:public class MusicService extends Service {private MediaPlayer player;private Timer timer;public MusicService() {}@Overridepublic IBinder onBind(Intent intent) {return new MusicControl();}@Overridepublic void onCreate() {super.onCreate();player = new MediaPlayer();//创建音乐播放器对象}public void addTimer() { //添加计时器用于设置音乐播放器中的播放进度条if (timer == null) {timer = new Timer(); //创建计时器对象TimerTask task = new TimerTask() {@Overridepublic void run() {if (player == null) return;int duration = player.getDuration(); //获取歌曲总时长int currentPosition = player.getCurrentPosition();//获取播放进度Message msg = MainActivity.handler.obtainMessage();//创建消息对象//将音乐的总时长和播放进度封装至消息对象中Bundle bundle = new Bundle();bundle.putInt("duration", duration);bundle.putInt("currentPosition", currentPosition);msg.setData(bundle);//将消息发送到主线程的消息队列MainActivity.handler.sendMessage(msg);}};//开始计时任务后的5毫秒,第一次执行task任务,以后每500毫秒执行一次timer.schedule(task, 5, 500);}}class MusicControl extends Binder {public void play() {try {player.reset();//重置音乐播放器//加载多媒体文件player = MediaPlayer.create(getApplicationContext(),R.raw.music);player.start();//播放音乐addTimer(); //添加计时器} catch (Exception e) {e.printStackTrace();}}public void pausePlay() {player.pause(); //暂停播放音乐}public void continuePlay() {player.start(); //继续播放音乐}public void seekTo(int progress) {player.seekTo(progress);//设置音乐的播放位置}}@Overridepublic void onDestroy() {super.onDestroy();if (player == null) return;if (player.isPlaying()) player.stop();//停止播放音乐player.release(); //释放占用的资源player = null; //将player置为空}}(4)编写界面交互代码关键代码如下:public class MainActivity extends AppCompatActivity implementsView.OnClickListener{private static SeekBar sb;private static TextView tv_progress, tv_total;private ObjectAnimator animator;private MusicService.MusicControl musicControl;MyServiceConn conn;Intent intent;private boolean isUnbind = false;//记录服务是否被解绑@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);init();}private void init() {tv_progress = (TextView) findViewById(_progress);tv_total = (TextView) findViewById(_total);sb = (SeekBar) findViewById(R.id.sb);findViewById(R.id.btn_play).setOnClickListener(this);findViewById(R.id.btn_pause).setOnClickListener(this);findViewById(R.id.btn_continue_play).setOnClickListener(this);findViewById(R.id.btn_exit).setOnClickListener(this);intent = new Intent(this, MusicService.class);//创建意图对象conn = new MyServiceConn();//创建服务连接对象bindService(intent, conn, BIND_AUTO_CREATE); //绑定服务//为滑动条添加事件监听sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {@Overridepublic void onProgressChanged(SeekBar seekBar, int progress, booleanfromUser) { //滑动条进度改变时,会调用此方法if (progress == seekBar.getMax()) { //当滑动条滑到末端时,结束动画animator.pause(); //停止播放动画}}@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {//滑动条开始滑动时调用}@Overridepublic void onStopTrackingTouch(SeekBar seekBar) { //滑动条停止滑动时调用//根据拖动的进度改变音乐播放进度int progress = seekBar.getProgress();//获取seekBar的进度musicControl.seekTo(progress); //改变播放进度}});ImageView iv_music = (ImageView) findViewById(R.id.iv_music);animator = ObjectAnimator.ofFloat(iv_music, "rotation", 0f, 360.0f);animator.setDuration(10000); //动画旋转一周的时间为10秒animator.setInterpolator(new LinearInterpolator());animator.setRepeatCount(-1); //-1表示设置动画无限循环}4.运行结果开始播放如图4-1所示图4-15.实验小结通过此次实验,让我了解到了Android中的服务创建,比如下载文件、播放音乐等功能,其中让我学到了一个背景选择器,可以通过这个选择器动态呈现按钮的背景颜色。
Android实现音乐视频播放
Android实现⾳乐视频播放本⽂实例为⼤家分享了Android实现⾳乐视频播放的具体代码,供⼤家参考,具体内容如下步骤1、新建⼀个安卓项⽬,再加⼀个assets包2、在 assets中加⼊⼀段⾳频3、在界⾯中加⼊⾳乐的“开始”按钮和“暂停”按钮。
4、在 MainActivity⽂件中写相应逻辑package com.hnucm.c201901020110;import androidx.annotation.RequiresApi;import androidx.appcompat.app.AppCompatActivity;import android.media.MediaPlayer;import android.os.Build;import android.os.Bundle;import android.view.View;import java.io.IOException;public class MainActivity extends AppCompatActivity {MediaPlayer mediaPlayer = new MediaPlayer(); //⾳频对象 //⼤于Build.VERSION_CODES.N版本才能⽤@RequiresApi(api = Build.VERSION_CODES.N)@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);//加载⾳乐⽂件try {// mediaPlayer.setDataSource("联⽹后,⽹址");mediaPlayer.setDataSource(getAssets().openFd("a1.mp3"));mediaPlayer.prepare();}catch (IOException e){e.printStackTrace();}findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Overridepublic void onClick(View v) {// 播放⾳乐mediaPlayer.start();}});findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() { @Overridepublic void onClick(View v) {// 暂停⾳乐mediaPlayer.pause();}});}}视频播放1、新建⼀个⽂件夹,将视频⽂件放⼊raw⽂件夹中2、在界⾯中加⼊视频的“开始”按钮和“暂停”按钮。
Android简易音乐播放器实现代码
Android简易⾳乐播放器实现代码本⽂实例为⼤家分享了Android⾳乐播放器的具体代码,供⼤家参考,具体内容如下1.播放项⽬内的⾳乐package com.thm.g150820_android26_playmusic;import Android.media.MediaPlayer;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.ImageButton;import android.widget.SeekBar;public class MainActivity extends AppCompatActivity {private MediaPlayer mediaPlayer;private SeekBar seekBar;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);seekBar = (SeekBar) findViewById(R.id.seekBar);seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {@Overridepublic void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {}@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {}@Overridepublic void onStopTrackingTouch(SeekBar seekBar) {//获取拖动结束之后的位置int progress = seekBar.getProgress();//跳转到某个位置播放mediaPlayer.seekTo(progress);}});}public void isPlayOrPause(View view){//把View强转为ImageButtonImageButton imageButton = (ImageButton) view;if(mediaPlayer==null) {//实例化MediaPlayermediaPlayer = MediaPlayer.create(this, R.raw.yao);//开始播放mediaPlayer.start();//图标修改为暂停的图标imageButton.setImageResource(android.R.drawable.ic_media_pause);//获取⾳乐的总时长int duration = mediaPlayer.getDuration();//设置进度条的最⼤值为⾳乐的总时长seekBar.setMax(duration);new MyThre().start();}//判断如果⾳乐在播放else if(mediaPlayer.isPlaying()){//就暂停⾳乐mediaPlayer.pause();//图标修改为播放的图标imageButton.setImageResource(android.R.drawable.ic_media_play);}else{mediaPlayer.start();//图标修改为暂停的图标imageButton.setImageResource(android.R.drawable.ic_media_pause);}}//写内部类class MyThre extends Thread{@Overridepublic void run() {super.run();while(seekBar.getProgress()<=seekBar.getMax()){//获取当前⾳乐播放的位置int currentPosition = mediaPlayer.getCurrentPosition();//让进度条动起来seekBar.setProgress(currentPosition);}}}}2.播放内存卡中的⾳乐package com.thm.g150820_android26_playmusic;import android.media.AudioManager;import android.media.MediaPlayer;import .Uri;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.ImageButton;import android.widget.SeekBar;import java.io.IOException;public class MainActivity extends AppCompatActivity {private MediaPlayer mediaPlayer;private SeekBar seekBar;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);seekBar = (SeekBar) findViewById(R.id.seekBar);seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Overridepublic void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { }@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {}@Overridepublic void onStopTrackingTouch(SeekBar seekBar) {//获取拖动结束之后的位置int progress = seekBar.getProgress();//跳转到某个位置播放mediaPlayer.seekTo(progress);}});}public void isPlayOrPause(View view){//把View强转为ImageButtonImageButton imageButton = (ImageButton) view;if(mediaPlayer==null) {//实例化MediaPlayer//播放应⽤内的⾳乐//mediaPlayer = MediaPlayer.create(this, R.raw.yao);//播放内存卡中的⾳乐mediaPlayer = new MediaPlayer();//设置类型mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);//设置⾳乐路径try {mediaPlayer.setDataSource(this, Uri.parse("storage/sdcard0/Music/a.mp3"));//播放之前准备⼀下mediaPlayer.prepare();} catch (IOException e) {e.printStackTrace();}//开始播放mediaPlayer.start();//图标修改为暂停的图标imageButton.setImageResource(android.R.drawable.ic_media_pause);//获取⾳乐的总时长int duration = mediaPlayer.getDuration();//设置进度条的最⼤值为⾳乐的总时长seekBar.setMax(duration);new MyThre().start();}//判断如果⾳乐在播放else if(mediaPlayer.isPlaying()){//就暂停⾳乐mediaPlayer.pause();//图标修改为播放的图标imageButton.setImageResource(android.R.drawable.ic_media_play);}else{mediaPlayer.start();//图标修改为暂停的图标imageButton.setImageResource(android.R.drawable.ic_media_pause);}}//写线程内部类class MyThre extends Thread{@Overridepublic void run() {super.run();while(seekBar.getProgress()<=seekBar.getMax()){//获取当前⾳乐播放的位置int currentPosition = mediaPlayer.getCurrentPosition();//让进度条动起来seekBar.setProgress(currentPosition);}}}}3.添加读取内存的权限更多关于播放器的内容请点击进⾏学习。
最全的Android开源音乐播放器源码汇总
最全的Android开源音乐播放器源码汇总收集了很多音乐播放器类的Android项目源码,非常不错的开源项目,会让你事半功倍,希望大家补充。
谢谢!Android基于经纬度切歌的冲绳音乐播放器源码Android应用源码适合新手学习的本地音乐播放器Android应用源码网络本地音乐播放器工程源码Android应用源码仿手机QQ音乐播放器项目Android应用源码超级精致的本地音乐播放器Android应用源码教学自学用音乐播放器Android应用源码25国语言音乐播放器Android应用源码仿唱片机音乐播放器Android应用源码仿多米音乐播放器项目Android应用源码安卓win8风格音乐播放器Android应用源码仿酷狗音乐播放器本地版Android应用源码安卓奇葩音乐播放器项目Android应用源码魔音盒音乐播放器项目Android应用源码音乐实时跳动频谱显示Android应用源码强大的3D音乐播放器项目Android应用源码仿安卓QQ音乐播放器项目android应用源码先锋音乐快剪铃声剪辑项目Android和讯音乐播放器培训项目Android应用源码安卓乐迹音乐播放器项目Android应用源码带歌词与频谱SMplaye音乐播放器Android应用源码含歌词列表gif简单音乐播放器Android应用源码国外在线电台音乐播放器.rarAndroid例子源码音乐播放器aidl实现进程间的通讯Android 音乐播放器android开发源码分享之在线音乐播放器完整项目jamendo_android一个开源的Android在线音乐播放器实例。
Android 音乐播放器(晴天播放)Android优雅音乐源码Android MusicPlayer音乐播放器源码Android 简易音乐播放器源码GitHub开源项目之Jamendo音乐播放器Android音乐播放器歌词显示实例。
Android应用开发--MP3音乐播放器代码实现(一)
Android应⽤开发--MP3⾳乐播放器代码实现(⼀)需求1:将内存卡中的MP3⾳乐读取出来并显⽰到列表当中1. 从数据库中查询所有⾳乐数据,保存到List集合当中,List当中存放的是Mp3Info对象2. 迭代List集合,把每⼀个Mp3Info对象的所有属性,保存到Map对象当中3. 定义⼀个List集合,把Map对象添加到List集合当中4. 通过定义⼀个SimpleAdpter,调⽤setAdpter⽅法,将数据显⽰到列表当中[java]1. /**2. * ⽤于从数据库中查询歌曲的信息,保存在List当中3. *4. * @return5. */6. public List<Mp3Info> getMp3Infos() {7. Cursor cursor = getContentResolver().query(8. MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,9. MediaStore.Audio.Media.DEFAULT_SORT_ORDER);10. List<Mp3Info> mp3Infos = new ArrayList<Mp3Info>();11. for (int i = 0; i < cursor.getCount(); i++) {12. Mp3Info mp3Info = new Mp3Info();13. cursor.moveToNext();14. long id = cursor.getLong(cursor15. .getColumnIndex(MediaStore.Audio.Media._ID)); //⾳乐id16. String title = cursor.getString((cursor17. .getColumnIndex(MediaStore.Audio.Media.TITLE)));//⾳乐标题18. String artist = cursor.getString(cursor19. .getColumnIndex(MediaStore.Audio.Media.ARTIST));//艺术家20. long duration = cursor.getLong(cursor21. .getColumnIndex(MediaStore.Audio.Media.DURATION));//时长22. long size = cursor.getLong(cursor23. .getColumnIndex(MediaStore.Audio.Media.SIZE)); //⽂件⼤⼩24. String url = cursor.getString(cursor25. .getColumnIndex(MediaStore.Audio.Media.DATA)); //⽂件路径26. int isMusic = cursor.getInt(cursor27. .getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));//是否为⾳乐28. if (isMusic != 0) { //只把⾳乐添加到集合当中29. mp3Info.setId(id);30. mp3Info.setTitle(title);31. mp3Info.setArtist(artist);32. mp3Info.setDuration(duration);33. mp3Info.setSize(size);34. mp3Info.setUrl(url);35. mp3Infos.add(mp3Info);36. }37. }38. return mp3Infos;39. }[java]1. /**2. * 填充列表3. * @param mp3Infos4. */5. public void setListAdpter(List<Mp3Info> mp3Infos) {6. List<HashMap<String, String>> mp3list = new ArrayList<HashMap<String, String>>();7. for (Iterator iterator = mp3Infos.iterator(); iterator.hasNext();) {8. Mp3Info mp3Info = (Mp3Info) iterator.next();9. HashMap<String, String> map = new HashMap<String, String>();10. map.put("title", mp3Info.getTitle());11. map.put("Artist", mp3Info.getArtist());12. map.put("duration", String.valueOf(mp3Info.getDuration()));13. map.put("size", String.valueOf(mp3Info.getSize()));14. map.put("url", mp3Info.getUrl());15. mp3list.add(map);16. }17. mAdapter = new SimpleAdapter(this, mp3list,18. yout.music_list_item_layout, new String[] { "title", "Artist", "duration" },19. new int[] { R.id.music_title, R.id.music_Artist, R.id.music_duration });20. mMusiclist.setAdapter(mAdapter);21. }实现效果如图:需求2:点击列表的每⼀项,启动⼀个服务来播放⾳乐1. 注册条⽬点击监听器OnItemClickListener2. 定义⼀个实现OnItemClickListener接⼝的内部类3. 定义⼀个继承Service的服务类PlayerServie1. 注册条⽬点击监听器OnItemClickListener[java]1. mMusiclist = (ListView) findViewById(R.id.music_list);2. mMusiclist.setOnItemClickListener(new MusicListItemClickListener());3. mp3Infos = getMp3Infos();4. setListAdpter(getMp3Infos());2. 定义⼀个实现OnItemClickListener接⼝的内部类[java]1. private class MusicListItemClickListener implements OnItemClickListener {2. @Override3. public void onItemClick(AdapterView<?> parent, View view, int position,4. long id) {5. if(mp3Infos != null) {6. Mp3Info mp3Info = mp3Infos.get(position);7. Log.d("mp3Info-->", mp3Info.toString());8. Intent intent = new Intent();9. intent.putExtra("url", mp3Info.getUrl());10. intent.putExtra("MSG", AppConstant.PlayerMsg.PLAY_MSG);11. intent.setClass(MainActivity.this, PlayerService.class);12. startService(intent); //启动服务13. }14. }15. }3. 定义⼀个继承Service的服务类PlayerServie(未完善的Service类)[java]1. package com.wwj.sb.service;2.3.4. import android.annotation.SuppressLint;5. import android.app.Service;6. import android.content.Intent;7. import android.media.MediaPlayer;8. import android.media.MediaPlayer.OnPreparedListener;9. import android.os.IBinder;10.11. import com.wwj.sb.domain.AppConstant;12.13. @SuppressLint("NewApi")14. public class PlayerService extends Service {15. private MediaPlayer mediaPlayer = new MediaPlayer(); //媒体播放器对象16. private String path; //⾳乐⽂件路径17. private boolean isPause; //暂停状态18.19. @Override20. public IBinder onBind(Intent arg0) {21. return null;22. }23.24. @Override25. public int onStartCommand(Intent intent, int flags, int startId) {26. if(mediaPlayer.isPlaying()) {27. stop();28. }29. path = intent.getStringExtra("url");30. int msg = intent.getIntExtra("MSG", 0);31. if(msg == AppConstant.PlayerMsg.PLAY_MSG) {32. play(0);33. } else if(msg == AppConstant.PlayerMsg.PAUSE_MSG) {34. pause();35. } else if(msg == AppConstant.PlayerMsg.STOP_MSG) {36. stop();37. }38. return super.onStartCommand(intent, flags, startId);39. }40.41.42. /**43. * 播放⾳乐44. * @param position45. */46. private void play(int position) {47. try {48. mediaPlayer.reset();//把各项参数恢复到初始状态49. mediaPlayer.setDataSource(path);50. mediaPlayer.prepare(); //进⾏缓冲51. mediaPlayer.setOnPreparedListener(new PreparedListener(position));//注册⼀个监听器52. }53. catch (Exception e) {54. e.printStackTrace();55. }56. }57.58. /**59. * 暂停⾳乐60. */61. private void pause() {62. if (mediaPlayer != null && mediaPlayer.isPlaying()) {63. mediaPlayer.pause();64. isPause = true;65. }66. }67.68. /**69. * 停⽌⾳乐70. */71. private void stop(){72. if(mediaPlayer != null) {73. mediaPlayer.stop();74. try {75. mediaPlayer.prepare(); // 在调⽤stop后如果需要再次通过start进⾏播放,需要之前调⽤prepare函数76. } catch (Exception e) {77. e.printStackTrace();78. }79. }80. }81.82.83. @Override84. public void onDestroy() {85. if(mediaPlayer != null){86. mediaPlayer.stop();87. mediaPlayer.release();88. }89. }90. /**91. *92. * 实现⼀个OnPrepareLister接⼝,当⾳乐准备好的时候开始播放93. *94. */95. private final class PreparedListener implements OnPreparedListener {96. private int positon;97.98. public PreparedListener(int positon) {99. this.positon = positon;100. }101.102. @Override103. public void onPrepared(MediaPlayer mp) {104. mediaPlayer.start(); //开始播放105. if(positon > 0) { //如果⾳乐不是从头播放106. mediaPlayer.seekTo(positon);107. }108. }109. }110.111. }public class MusicActivity extends Activity {private boolean isStop = false;private MediaPlayer mPlayer;public final String TITLE = Environment.getExternalStorageDirectory()+ "/iwantyourlove.mp3";private File file;private SeekBar seekBar;private ImageView play;private TextView title;protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.music_main);initWidgets();}// 重新初始化播放器public void initWidgets() {play = (ImageView) findViewById(R.id.img_stop);title = (TextView) findViewById(R.id.title);seekBar = (SeekBar) findViewById(R.id.seek);seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Overridepublic void onStopTrackingTouch(SeekBar seekBar) {//seekBar.setProgress(mPlayer.getCurrentPosition() *seekBar.getMax() / total); //Log.i("sss", seekBar.getProgress()+"");//mPlayer.seekTo(mPlayer.getCurrentPosition());mPlayer.seekTo(seekBar.getProgress() * mPlayer.getDuration() /100 );}@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {}@Overridepublic void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {// Log.i("progress", ""+progress);// Log.i("qqq", seekBar.getProgress()+"");// progress = currentPosition * 100 / duration;//progress*duration/100//mPlayer.seekTo(progress * mPlayer.getDuration() /100 );}});file = new File(TITLE);title.setText(file.getName());mPlayer = new MediaPlayer();try {mPlayer.setDataSource(TITLE);mPlayer.prepare();} catch (Exception e) {e.printStackTrace();}}public void play(View v) {if (!mPlayer.isPlaying()) {mPlayer.start();}}public void pause(View v) {if (mPlayer.isPlaying()) {mPlayer.pause();}}public void replay(View v) {mPlayer.reset();initWidgets();// 重新构建播放器// mPlayer.start();play(v);}public void stop(View v) {isStop = true;mPlayer.stop();play.setImageResource(R.drawable.player_play);}// ⽤图⽚代替按钮public void playOrPause(View v) {if (isStop) {// 停⽌后重新开始播放mPlayer.reset();initWidgets();mPlayer.start();play.setImageResource(R.drawable.player_pause);isStop = false;} else if (mPlayer.isPlaying()) {// 播放状态play.setImageResource(R.drawable.player_play);mPlayer.pause();} else {// 暂停状态play.setImageResource(R.drawable.player_pause);mPlayer.start();}// 异步任务new MusicTask().execute();}@Overrideprotected void onDestroy() {super.onDestroy();// 释放资源mPlayer.release();}// ⾳乐播放异步任务class MusicTask extends AsyncTask<Void, Void, Void> {//int current = mPlayer.getCurrentPosition();// 当前播放是什么位置,int total = mPlayer.getDuration(); // ⾳乐总共多长时间@Overrideprotected Void doInBackground(Void... params) {// 让SeekBar跟着⾳乐⼀起向右边⾛while (mPlayer.getCurrentPosition() <= total&&!isStop) { //!isPause不是停⽌状态try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}publishProgress();}return null;}@Overrideprotected void onProgressUpdate(Void... values) {super.onProgressUpdate(values);// Log.i("msg", ""+mPlayer.getCurrentPosition() * 100 / total);seekBar.setProgress(mPlayer.getCurrentPosition() *seekBar.getMax() / total); }@Overrideprotected void onPostExecute(Void result) {super.onPostExecute(result);}}}。
Android手机平台音乐播放器策划方案和源代码
目录第一章引言................................................................................................... - 1 -1.1 项目背景............................................................................................ - 1 -1.2 编写目的............................................................................................ - 2 -1.3 参考资料............................................................... 错误!未定义书签。
第二章系统需求分析..................................................................................... - 3 -2.1 功能需求(用例图分析)................................................................ - 3 -2.1.1 播放器的基本控制需求......................................................... - 3 -2.1.2 播放清单列表管理需求......................................................... - 5 -2.1.3 播放友好性需求..................................................................... - 7 -2.1.4 播放器扩展卡需求................................................................. - 8 -2.1.5 功能需求(时序图)分析.......................................................... - 9 -2.2 系统结构图和流程图...................................................................... - 10 -2.3 系统界面需求.................................................................................. - 11 -2.4 系统性能需求.................................................................................. - 12 -2.5 运行环境需求.................................................................................. - 12 - 第三章Android数据库设计 ........................................................................ - 13 -3.1 数据库及字段属性设计.................................................................. - 13 -3.1.1 字段设计(表、图)........................................................... - 13 -3.1.2 音乐播放器E-R图 .............................................................. - 15 -3.2 数据库连接...................................................................................... - 15 -3.2.1 创建数据库........................................................................... - 15 -3.2.2 操作数据库........................................................................... - 16 -3.2.3 数据显示............................................................................... - 17 - 第四章Android项目介绍 ............................................................................ - 18 -4.1 什么是Android? ........................................................................... - 18 -4.1.1 Android简介 ......................................................................... - 18 -4.1.2 Android Features特性........................................................... - 18 -4.1.3 Android基本框架(Android Architecture) ....................... - 19 -4.2 搭建Android开发环境 .................................................................. - 23 -4.3 Android常用工具的使用 ................................................................ - 25 -4.3.1 命令行的使用....................................................................... - 25 -4.3.2 Dalvik Debug Monitor Service (DDMS)的使用................... - 26 -4.4 Android 音乐播放器的工程 ........................................................... - 26 -4.4.1 Android项目 ......................................................................... - 26 -4.4.2 Android工程程序结构 ......................................................... - 27 -4.4.3 AndroidManifest.xml文件.................................................... - 29 - 第五章播放器系统功能详细设计............................................................... - 31 -5.1音乐播放器主界面功能实现........................................................... - 31 -5.1.1 播放器主界面....................................................................... - 31 -5.1.2 播放界面音轨的实现........................................................... - 32 -5.1.3 播放器播放、暂停、停止等功能....................................... - 35 -5.2 播放列表功能.................................................................................. - 36 -5.3 菜单功能.......................................................................................... - 38 -5.3.1 菜单界面............................................................................... - 38 -5.3.2 菜单功能实现....................................................................... - 39 -5.4 播放设置界面.................................................................................. - 41 -5.4.1 界面实现............................................................................... - 41 -5.4.2 歌词显示实现....................................................................... - 42 -5.5 手机扩展卡的访问.......................................................................... - 44 -5.5.1 文件浏览器界面................................................................... - 45 -5.5.2 文件浏览器功能实现........................................................... - 46 -5.6 数据存储方式.................................................................................. - 47 -5.6.1 SharedPreferences .................................................................. - 47 -5.6.2 File存储方式 ........................................................................ - 48 -5.6.3 SQLiteDatabase数据库 ........................................................ - 48 - 第六章结论...................................................................... 错误!未定义书签。
音乐播放器源代码
P align=center><TABLE borderColor=#4f3256 align=centerbackground=/zh_cn/home4u/sucai/gifanimation/line/0022.gifborder=1><TBODY><TR><TD style="FILTER: alpha(opacity=100,style=3)"> <P align=center><EMBED src=width=369 height=39type=audio/mpeg loop="-1" autostart="ture"volume="0"></P></TD></TR></TBODY></TABLE></P>autostart="true"中true或1表示自动播放,false或0表示手动播放loop="true" 中的true或1表示重复播放,false或0表示只播放一次width= height= 中的数字分别表示播放器的宽度和高度=0表示隐藏播放器EnableContextMenu="0" 禁右键ShowStatusBar="1" (带显示文件播放信息)=======================================================隐藏(hidden=true)播放器(不循环)<EMBED src=音乐网址hidden=true type=audio/x-ms-wma AUTOSTART="1">-----------------------------------------------------------隐藏(hidden=true)播放器(循环)<EMBED src=音乐网址hidden=true type=audio/mpeg AUTOSTART="1" loop="-1"> ---------------------------------------------------------------黑色[style="FILTER: xray()"]循环[loop="-1"]播放器<EMBED style="FILTER: xray()" src=音乐网址width=360 height=30type=audio/mpeg volume="0" autostart="true" loop="-1">--------------------------------------------------------------------------------浅兰色循环(loop="-1")播放器<EMBED src=音乐网址width=300 height=45 type=audio/mpeg loop="-1"autostart="true" volume="0">--------------------------------------------------------------------------掩饰自动播放器<TABLE style="FILTER: Alpha(Opacity=100, FinishOpacity=0, Style=2, StartX=20, StartY=40, FinishX=0, FinishY=0)gray(); WIDTH: 200px; HEIGHT: 83px"><TBODY><TR><TD><EMBED src=音乐网址width=200 height=40 type=audio/mpeg panel="0" autostart="true" loop="true"></TD></TR></TBODY></TABLE>-------------------------------------连播放时选择曲目的播放器<EMBEDpluginspage=/windows/mediaplayer/download/default.as p width=400 height=172 type=application/x-mplay er2 FileName="音乐网址" SHOWCONTROLS="1" SHOWSTATUSBAR="1" SHOWDISPLAY="1" SHOWGOTOBAR="1" AUTOSTART="true" PlayCount="1">----------------------------------------------------------------------------------------------显示曲名的黑色带彩自动播放器<EMBED style="FILTER: invert()" src=音乐网址width=320 height=45type=audio/x-ms-wma ShowStatusBar="1" loop="true" autostart="true">-------------------------------------------------------------------------显示曲名的灰白色面板<EMBED style="FILTER: Gray()" src="链接地址" width=300 height=69type=application/x-mplayer2 loop="-1" showcontrols="1" ShowDisplay="0" ShowStatusBar="1" autostart="1"></EMBED>------------------------------------------灰白面板<embed style="FILTER: Gray()" src=链接地址width=300 height=45 loop="-1" autostart="true"></EMBED>---------------------------------------------------------------(带显示文件播放信息)<EMBED src="链接地址" width=300 height=69 type=application/x-mplay er2loop="-1" showcontrols="1" ShowDisplay="0" ShowStatusBar="1"autostart="1"></EMBED>-----------------------------------------------黑色带彩棕色面板<EMBED style="FILTER: invert()" src=链接地址width=300 height=45 loop="-1" autostart="true"></EMBED>---------------------------------------------------------------------浅紫播放器<TABLE borderColor=#4F3256background=/DownloadImg/2010/09/0718/5119955_3.jpg border=1><TBODY><TR><TD style="FILTER: alpha(opacity=50,style=3)"><P align=center><EMBED src=音乐网址width=300 height=25 type=audio/mpeg loop="-1" autostart="false" volume="0"></P></TD></TR></TBODY></TABLE>----------------------------------------------------------------------------------------------粉色<TABLE borderColor=navybackground=/UploadFile/2005-9/200592522275884778.jpg border=0><TBODY><TR><TD style="FILTER: alpha(opacity=50,style=3)"><P align=center><EMBED src=音乐网址width=300 height=45 type=audio/mpeg loop="-1" autostart="0" volume="0"></P></TD></TR></TBODY></TABLE>------------------------------------------------------------------------------------黄色闪光<TABLE style="BORDER-RIGHT: #000000 3px dashed; BORDER-TOP: #000000 3px dashed; BORDER-LEFT: #000000 3px dashed; BORDER-BOTTOM: #000000 3px dashed" cellSpacing=0 cellPadding=0 bgColor=#00000><TBODY><TR><TD><TABLE borderColor=navybackground=/s-helpSite/domName/nxm/20041114123131568.gi f border=0><TBODY><TR><TD style="FILTER: alpha(opacity=50,style=3)"><P align=center><EMBED src=音乐网址width=400 height=35 type=audio/mpeg loop="-1" autostart="0" loop="-1"></P></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE>--------------------------------------------------------------------------------蓝色闪光<TABLE borderColor=#dee4fe cellSpacing=3 cellPadding=0background=/UploadFile/2004-12/2004123023101352.gif border=2><TBODY><TR><TD><TABLE align=center border=0><TBODY><TR><TD style="FILTER: alpha(opacity=60,style=3)"><P align=center><EMBED style="FILTER: Gray" src=音乐网址width=400 height=35 type=audio/mpeg volume="0" autostart="false" loop="-1"></P></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE>-------------------------------------------------------------------------花边黑色<TABLE style="BORDER-RIGHT: #000000 3px dashed; BORDER-TOP: #000000 3px dashed; BORDER-LEFT: #000000 3px dashed; BORDER-BOTTOM: #000000 3px dashed" cellSpacing=0 cellPadding=0 bgColor=#00000><TBODY><TR><TD><TABLE borderColor=#000000 align=center border=1><TBODY><TR><TD><P align=center><EMBED style="FILTER: Xray" src=音乐网址width=400 height=35 type=audio/mpeg volume="0" autostart="false" loop="-0"></P></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE>-----------------------------------------------------------------------------------------------------粉色花边<TABLE style="BORDER-RIGHT: #ff69b4 3px dotted; BORDER-TOP: #ff69b4 3px dotted; BORDER-LEFT: #ff69b4 3px dotted; BORDER-BOTTOM: #ff69b4 3px dotted" cellSpacing=0 cellPadding=0 align=center bgColor=white><TBODY><TR><TD><TABLE borderColor=#ff69b4 align=center bgColor=#ffccf5 border=2><TBODY><TR><TD style="FILTER: alpha(opacity=100,style=3)"><P align=center><EMBED src=音乐网址width=300 height=25 type=audio/mpeg volume="0" autostart="false" loop="-0"></P></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE>-------------------------------------------------------------------------------------------禁右键播放器<EMBED style="BORDER-RIGHT: silver 1px solid; BORDER-TOP: silver 1px solid; BORDER-LEFT: silver 1px solid; BORDER-BOTTOM: silver 1px solid" src=音乐网址width=200 height=40 type=audio/x-mplayer2 console="video" showstatusbar="0" EnableContextMenu="0" volume="0" autostart="0" loop="-1">---------------------------------------------------------------------------------上下移动<MARQUEE style="LEFT: 230px; ; TOP: 300px" scrollAmount=1 scrollDelay=200 direction=up behavior=alternate width=300 height=400><br><MARQUEE scrollAmount=1 scrollDelay=100 behavior=alternate><br><TABLE style="FILTER: progid:DXImageTransform.Microsoft.Shadow(color:#7ec0ee ,direction:145,strengt h:20)" cellSpacing=0 cellPadding=0 border=1><br><TBODY><br><TR><br><TD><EMBED style="FILTER: gray()" src=音乐网址width=200 height=20type=audio/mpeg showstatusbar="1" volume="0" loop="-1" autostart="1"></TD></TR></TBODY></TABLE></MARQUEE></MARQUEE>-------------------------------------------------------------------(显示文件标签信息)蓝色<DIV><EMBED src="链接地址" loop="-1" width=300 height=140 balance="true" showpositioncontrols="true" showtracker="true" showaudiocontrols="true" showcontrols="true" showstatusbar="true" showdisplay="true" displaysize="0" volume="100" autosize="true" autostart="true" animationatstart="true" transparentatstart="true"></EMBED></div>--------------------------------------------------(显示文件标签信息)灰白<DIV><EMBED style="FILTER: Gray()" src="链接地址" loop="-1" width=300height=140 balance="true" showpositioncontrols="true" showtracker="true" showaudiocontrols="true" showcontrols="true" showstatusbar="true" showdisplay="true" displaysize="0" volume="100" autosize="true"autostart="true" animationatstart="true"transparentatstart="true"></EMBED></div>----------------------------------------------------(显示文件标签信息)黑彩<DIV><EMBED style="FILTER: invert()" src="链接地址" loop="-1" width=300 height=140 balance="true" showpositioncontrols="true" showtracker="true"showaudiocontrols="true" showcontrols="true" showstatusbar="true" showdisplay="true" displaysize="0" volume="100" autosize="true"autostart="true" animationatstart="true"transparentatstart="true"></EMBED></div>-----------------------------------------------------------(显示文件标签信息)黑<DIV><EMBED style="FILTER: xray()" src="链接地址" loop="-1" width=300height=140 balance="true" showpositioncontrols="true" showtracker="true" showaudiocontrols="true" showcontrols="true" showstatusbar="true" showdisplay="true" displaysize="0" volume="100" autosize="true"autostart="true" animationatstart="true"transparentatstart="true"></EMBED></div>===================================================连放<EMBED style="FILTER: Gray()" src=音乐网址width=500 height=35type=audio/x-ms-wma controls="StatusBar,TACCtrl,ControlPanel" border="0" autostart="1" playcount="0" showtracker="1" volume="0"></EMBED>=========================================================图片播放器!<TABLE style="FILTER: alpha(opacity=100 Style=0 FinishOpacity=100)" borderColor=#000000 height=249 cellSpacing=0 cellPadding=0 width=314 background=/DownloadImg/2010/09/0718/5119955_4.gif border=0><TBODY><TR><TD width=314 height=180 cellpadding="0" cellspacing="0"></TD></TR><TR><TD align=left><P align=center><EMBED style="FILTER: alpha(opacity=100 Style=3 FinishOpacity=0)black(); style: " src=音乐网址width=310 height=28 type=video/x-ms-asf loop="-1" autostart="1" volume="0"></P></TD></TR></TBODY></TABLE>=================================================以上效果分见如下::为免各效果同时播放,以下autostart=0autostart="true"中true或1表示自动播放,false或0表示手动播放loop="true" 中的true或1表示重复播放,false或0表示只播放一次width= height= 中的数字分别表示播放器的宽度和高度=0表示隐藏播放器EnableContextMenu="0" 禁右键ShowStatusBar="1" (带显示文件播放信息)=======================================================隐藏(hidden=true)播放器(不循环)src="/LIU/all_about_you.wma" hidden="true"type="audio/x-ms-wma" allowscriptaccess="never" autostart="0">-----------------------------------------------------------隐藏(hidden=true)播放器(循环)src="/LIU/all_about_you.wma" hidden="true"type="audio/mpeg" allowscriptaccess="never" autostart="0" loop="-1">---------------------------------------------------------------黑色[style="FILTER: xray()"]循环[loop="-1"]播放器style="FILTER: xray()" src="/LIU/all_about_you.wma" width="360" height="30" type="audio/mpeg" allowscriptaccess="never"volume="0" autostart="0" loop="-1">--------------------------------------------------------------------------------浅兰色循环(loop="-1")播放器src="/LIU/all_about_you.wma" width="300" heigh t="45" type="audio/mpeg" allowscriptaccess="never" loop="-1" autostart="0"volume="0">--------------------------------------------------------------------------掩饰自动播放器src="/LIU/all_about_you.wma"width="200" height="40" type="audio/mpeg"allowscriptaccess="never" panel="0" autostart="0"loop="true">-------------------------------------连播放时选择曲目的播放器pluginspage="/windows/mediaplayer/download/default.a sp" width="400" height="172" type="application/x-mplayer2"allowscriptaccess="never"filename="/LIU/all_about_you.wma" showcontrols="1" showstatusbar="1" showdisplay="1" showgotobar="1" autostart="0"playcount="1">----------------------------------------------------------------------------------------------显示曲名的黑色带彩自动播放器style="FILTER: invert()" src="/LIU/all_about_you.wma" width="320" height="45" type="audio/x-ms-wma" allowscriptaccess="never" showstatusbar="1" loop="0" autostart="0">-------------------------------------------------------------------------显示曲名的灰白色面板style="FILTER: Gray()" src="/LIU/all_about_you.wma" width="300" height="69" type="application/x-mplay er2" allowscriptaccess="never" loop="-1" showcontrols="1" showdisplay="0" showstatusbar="1" autostart="0"> ------------------------------------------灰白面板style="FILTER: Gray()" src="/LIU/all_about_you.wma" width="300" height="45" type="audio/x-ms-wma" allowscriptaccess="never"loop="-1" autostart="0">---------------------------------------------------------------(带显示文件播放信息)src="/LIU/all_about_you.wma" width="300" height="69" type="application/x-mplay er2" allowscriptaccess="never" loop="-1"showcontrols="1" showdisplay="0" showstatusbar="1" autostart="0">-----------------------------------------------黑色带彩棕色面板style="FILTER: invert()" src="/LIU/all_about_you.wma" width="300" height="45" type="audio/x-ms-wma" allowscriptaccess="never"loop="-1" autostart="0"><CENTER><TABLE style="BORDER-RIGHT: #f1dda1 2px ridge; BORDER-TOP: #bdb76b 2px ridge; BORDER-LEFT: #f1dda1 2px ridge; BORDER-BOTTOM: #bdb76b 2px ridge; BACKGROUND-COLOR: white" borderColor=#ffffff cellPadding=0width=300 align=centerbackground=/fileuploaddir/4B2686448.4.gifborder=0><TBODY><TR><TD width=300 height=20 cellPadding="0"cellSpacing="0"><TABLE align=center border=0><TBODY><TR><TDstyle="FILTER: alpha(opacity=60,style=3)"><P align=center><EMBED style="FILTER: invert(); WIDTH: 290px; HEIGHT: 28px" src=/Q/.Wma type=audio/x-ms-wma autostart="true"loop="-1"volume="0"></P></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE></CENTER一、音乐播放器源代码(神采飞扬版)P align=center><TABLE borderColor=#4f3256 align=center background=http://tech.china.com/zh_cn/home4u/sucai/gifanimation/line/0022.gif border=1><TBODY><TR><TD style="FILTER: alpha(opacity=100,style=3)"><P align=center><EMBED src=width=369 height=39type=audio/mpeg loop="-1" autostart="ture" volume="0"></P></TD></TR> </TBODY></TABLE></P>二、具体操作步骤1、在“BLOG发表文章”网页里,也即是写文章的网页里,写好文字后,选中文字上方的“查看HTML源代码”项(选项前的方框内出现√则为选中),这时我们看见原来的文字成了汉字、英文字母和一些诸如<、/、=等符号组成的乱码。
一个完整android音乐播放器源码
本文出自:欢迎转载,转载请注明出自:安卓开发网下面将和大家一起介绍一个音乐播放器项目,完成后的播放器具有暂停,下一首,前一首,歌曲列表,播放条进度等一些基本功能,它只是播放SDCARD上的.map文件,Android SDK为我们提供了一个MeidaPlayer类,有了这个类我们可以很方便的创建一个mdeiaplayer服务,该类中具有一些方法:MediaPlayer mp = new MediaPlayer();// 设置文件存储路径setDataSource("/sdcard/path_to_song");// 播放mp.start();// 暂短mp.pause();// 复位mp.reset();// 获取当前播放时长mp.getDuration();// 进度条mp.getCurrentDuration();// Move song to particular second - used for Forward or Backwardmp.seekTo(positon); // position in milliseconds// 检测歌曲是否正在播放mp.isPlaying(); // returns true or false1:音乐播放器的界面:播放器界面中所用的一些布局图片,这些图片大家可以到android SDK文件夹下或是到网络中去寻找一些类似就可以,并不一定要这些图片,代码才是我们的关键,3:然后我们需要写一个XML布局文件用于播放器的播按钮在不同状态下的图片,此XML文件保存在drawable文件夹下,btn_play.xml<selector xmlns:android=""><item android:drawable="@drawable/img_btn_play_pressed"android:state_focused="true"android:state_pressed="true" /><item android:drawable="@drawable/img_btn_play_pressed"android:state_focused="false"android:state_pressed="true" /><item android:drawable="@drawable/img_btn_play_pressed"android:state_focused="true" /><item android:drawable="@drawable/img_btn_play"android:state_focused="false"android:state_pressed="false" /></selector>提示:大家可以根据此XML文件完成其它的一些按钮布局文件,在这里就没有再为大家一一提供了,4:为了让播放器更绚,我们可以自定义一个SeekBar作为歌曲的播放进度,自定义风格代如下:(4.1)更换背景图片:seekbar_progress_bg.xml<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android=""><item><clip><bitmap xmlns:android=""android:src="@drawable/img_seekbar_progress_blue"android:tileMode="repeat"android:antialias="true"android:dither="false"android:filter="false"android:gravity="left"/></clip></item>(4.2)Changing SeekBar Progress:seekbar_progress.xml<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android=""><item android:id="@android:id/background"android:drawable="@drawable/img_seekbar_bg"android:dither="true"></item><item android:id="@android:id/secondaryProgress"><clip><shape><gradientandroid:startColor="#80028ac8"android:centerColor="#80127fb1"android:centerY="0.75"android:endColor="#a004638f"android:angle="270"/></shape></clip></item><itemandroid:id="@android:id/progress"android:drawable="@drawable/seekbar_progress_bg"/></layer-list>(4.3)实际的Seekbar控件定义如下:<SeekBarandroid:id="@+id/songProgressBar"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginRight="20dp"android:layout_marginLeft="20dp"android:layout_marginBottom="20dp"android:layout_above="@id/player_footer_bg"android:thumb="@drawable/seek_handler"android:progressDrawable="@drawable/seekbar_progress"android:paddingLeft="6dp"android:paddingRight="6dp"/>5:接下来我们将实现播放的整体界面的布局文件:player.xml<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android=""android:layout_width="match_parent"android:layout_height="match_parent"android:background="@color/player_background"><!-- Player Header --><LinearLayoutandroid:id="@+id/player_header_bg"android:layout_width="fill_parent"android:layout_height="60dip"android:background="@layout/bg_player_header"android:layout_alignParentTop="true"android:paddingLeft="5dp"android:paddingRight="5dp"><!-- Song Title --><TextViewandroid:id="@+id/songTitle"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:textColor="#04b3d2"android:textSize="16dp"android:paddingLeft="10dp"android:textStyle="bold"android:text="The Good, The Bad And The Ugly"android:layout_marginTop="10dp"/><!-- Playlist button --><ImageButtonandroid:id="@+id/btnPlaylist"android:layout_width="wrap_content"android:layout_height="fill_parent"android:src="@drawable/btn_playlist"android:background="@null"/></LinearLayout><!-- Song Thumbnail Image --><LinearLayoutandroid:id="@+id/songThumbnail"android:layout_width="fill_parent"android:layout_height="wrap_content"android:paddingTop="10dp"android:paddingBottom="10dp"android:gravity="center"android:layout_below="@id/player_header_bg"><ImageView android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/adele"/></LinearLayout><!-- Player Footer --><LinearLayoutandroid:id="@+id/player_footer_bg"android:layout_width="fill_parent"android:layout_height="100dp"android:layout_alignParentBottom="true" android:background="@layout/bg_player_footer" android:gravity="center"><!-- Player Buttons --><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="horizontal"android:gravity="center_vertical"android:background="@layout/rounded_corner"android:paddingLeft="10dp"android:paddingRight="10dp"><!-- Previous Button --><ImageButtonandroid:id="@+id/btnPrevious"android:src="@drawable/btn_previous"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@null"/><!-- Backward Button --><ImageButtonandroid:id="@+id/btnBackward"android:src="@drawable/btn_backward"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@null"/><!-- Play Button --><ImageButtonandroid:id="@+id/btnPlay"android:src="@drawable/btn_play"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@null"/><!-- Forward Button --><ImageButtonandroid:id="@+id/btnForward"android:src="@drawable/btn_forward"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@null"/><!-- Next Button --><ImageButtonandroid:id="@+id/btnNext"android:src="@drawable/btn_next"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@null"/></LinearLayout></LinearLayout><!-- Progress Bar/Seek bar --><SeekBarandroid:id="@+id/songProgressBar"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginRight="20dp"android:layout_marginLeft="20dp"android:layout_marginBottom="20dp"android:layout_above="@id/player_footer_bg"android:thumb="@drawable/seek_handler"android:progressDrawable="@drawable/seekbar_progress"android:paddingLeft="6dp"android:paddingRight="6dp"/><!-- Timer Display --><LinearLayoutandroid:id="@+id/timerDisplay"android:layout_above="@id/songProgressBar"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginRight="20dp"android:layout_marginLeft="20dp"android:layout_marginBottom="10dp"><!-- Current Duration Label --><TextViewandroid:id="@+id/songCurrentDurationLabel"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_weight="1"android:gravity="left"android:textColor="#eeeeee"android:textStyle="bold"/><!-- Total Duration Label --><TextViewandroid:id="@+id/songTotalDurationLabel"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_weight="1"android:gravity="right"android:textColor="#04cbde"android:textStyle="bold"/></LinearLayout><!-- Repeat / Shuffle buttons --><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_above="@id/timerDisplay"android:gravity="center"><!-- Repeat Button --><ImageButtonandroid:id="@+id/btnRepeat"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/btn_repeat"android:layout_marginRight="5dp"android:background="@null"/><!-- Shuffle Button --><ImageButtonandroid:id="@+id/btnShuffle"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/btn_shuffle"android:layout_marginLeft="5dp"android:background="@null"/></LinearLayout></RelativeLayout>6:有了播放器的播放界面后,我们再将所有歌曲显示的界面实现了,播放器的歌曲列表用的一个listview控件,同样我们也为该listview控件自定义,适合播放的整体界面风格,list_selector.xml<?xml version="1.0" encoding="utf-8"?><selector xmlns:android=""><!-- Selector style for listrow --><itemandroid:state_selected="false"android:state_pressed="false"android:drawable="@drawable/gradient_bg" /><item android:state_pressed="true"android:drawable="@drawable/gradient_bg_hover" /><item android:state_selected="true"android:state_pressed="false"android:drawable="@drawable/gradient_bg_hover" /></selector>歌曲列表界面布局文件:playlist.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android=""android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical"><ListViewandroid:id="@android:id/list"android:layout_width="fill_parent"android:layout_height="fill_parent"android:divider="#242424"android:dividerHeight="1dp"android:listSelector="@drawable/list_selector" /></LinearLayout>listviewr的item界面布局,用于定义单个歌曲的显示界面:playlist_item.xml<?xml version="1.0"encoding="utf-8"?><LinearLayout xmlns:android=""android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:gravity="center"android:background="@drawable/list_selector"android:padding="5dp"><TextViewandroid:id="@+id/songTitle"android:layout_width="fill_parent"android:layout_height="wrap_content"android:textSize="16dp"android:padding="10dp"android:color="#f3f3f3"/></LinearLayout>歌曲列表界面图:7:到此为止我们在上面已经完成了该项目的所有布局文件,下面我们就来实现SongManager.java类,这个类用于扫描设备中所有.mp3文件,SongsManager.mp3public class SongsManager {// SDCard Pathfinal String MEDIA_PATH = new String("/sdcard/");private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();// Constructorpublic SongsManager(){}/*** Function to read all mp3 files from sdcard* and store the details in ArrayList* */public ArrayList<HashMap<String, String>> getPlayList(){= new );if (home.listFiles(new ()).length > 0) {for ( : home.listFiles(new ())) {HashMap<String, String> song = new HashMap<String, String>();song.put("songTitle", ().substring(0, (().length() - 4)));song.put("songPath", ());// Adding each song to SongListsongsList.add(song);}}// return songs list arrayreturn songsList;}/*** Class to filter files which are having .mp3 extension* */class implements {public boolean accept(, String name) {return (name.endsWith(".mp3") || name.endsWith(".MP3"));}}}8:创建一个新的Activity 类,该类用于显示在ongsManager.java中扫描到的所有歌曲,PlayListActivity.javapackage com.androidhive.musicplayer;import java.util.ArrayList;import java.util.HashMap;import android.app.ListActivity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.ListAdapter;import android.widget.ListView;import android.widget.SimpleAdapter;public class PlayListActivity extends ListActivity {// Songs listpublic ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.playlist);ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();SongsManager plm = new SongsManager();// get all songs from sdcardthis.songsList = plm.getPlayList();// looping through playlistfor (int i = 0; i < songsList.size(); i++) {// creating new HashMapHashMap<String, String> song = songsList.get(i);// adding HashList to ArrayListsongsListData.add(song);}// Adding menuItems to ListViewListAdapter adapter = new SimpleAdapter(this, songsListData,yout.playlist_item, new String[] { "songTitle" }, new int[] {R.id.songTitle });setListAdapter(adapter);// selecting single ListView itemListView lv = getListView();// listening to single listitem clicklv.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view,int position, long id) {// getting listitem indexint songIndex = position;// Starting new intentIntent in = new Intent(getApplicationContext(),AndroidBuildingMusicPlayerActivity.class);// Sending songIndex to PlayerActivityin.putExtra("songIndex", songIndex);setResult(100, in);// Closing PlayListViewfinish();}});}}9:下面我们再来实现播放的主类AndroidBuildingMusicPlayerActivity.java:该类主要实现功能如下:1:在歌曲列表界面点击一首歌曲进入播放界面;2:播放,暂停,快进,复位等功能实现3:重复播放单一歌曲,随机播放等该类的完整代码如下:public class AndroidBuildingMusicPlayerActivity extends Activity implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {private ImageButton btnPlay;private ImageButton btnForward;private ImageButton btnBackward;private ImageButton btnNext;private ImageButton btnPrevious;private ImageButton btnPlaylist;private ImageButton btnRepeat;private ImageButton btnShuffle;private SeekBar songProgressBar;private TextView songTitleLabel;private TextView songCurrentDurationLabel;private TextView songTotalDurationLabel;// Media Playerprivate MediaPlayer mp;// Handler to update UI timer, progress bar etc,.private Handler mHandler = new Handler();;private SongsManager songManager;private Utilities utils;private int seekForwardTime = 5000; // 5000 millisecondsprivate int seekBackwardTime = 5000; // 5000 millisecondsprivate int currentSongIndex = 0;private boolean isShuffle = false;private boolean isRepeat = false;private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.player);// 所有的播放按钮btnPlay = (ImageButton) findViewById(R.id.btnPlay);btnForward = (ImageButton)findViewById(R.id.btnForward);btnBackward = (ImageButton)findViewById(R.id.btnBackward);btnNext = (ImageButton) findViewById(R.id.btnNext);btnPrevious = (ImageButton)findViewById(R.id.btnPrevious);btnPlaylist = (ImageButton)findViewById(R.id.btnPlaylist);btnRepeat = (ImageButton)findViewById(R.id.btnRepeat);btnShuffle = (ImageButton)findViewById(R.id.btnShuffle);songProgressBar = (SeekBar)findViewById(R.id.songProgressBar);songTitleLabel = (TextView)findViewById(R.id.songTitle);songCurrentDurationLabel = (TextView)findViewById(R.id.songCurrentDurationLabel);songTotalDurationLabel = (TextView)findViewById(R.id.songTotalDurationLabel);// Mediaplayermp = new MediaPlayer();songManager = new SongsManager();utils = new Utilities();// ListenerssongProgressBar.setOnSeekBarChangeListener(this); // Importantmp.setOnCompletionListener(this); // Important// 获取所有歌曲列表songsList = songManager.getPlayList();// 默认从第一首开始播放playSong(0);/*** Play button click event* plays a song and changes button to pause image* pauses a song and changes button to play image* */btnPlay.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {// check for already playingif(mp.isPlaying()){if(mp!=null){mp.pause();// Changing button image to play buttonbtnPlay.setImageResou rce(R.drawable.btn_play);}}else{// Resume songif(mp!=null){mp.start();// Changing button image to pause buttonbtnPlay.setImageResou rce(R.drawable.btn_pause);}}}});/*** Forward button click event* Forwards song specified seconds* */btnForward.setOnClickListener(newView.OnClickListener() {@Overridepublic void onClick(View arg0) {// get current song positionint currentPosition =mp.getCurrentPosition();// check if seekForward time is lesser than song durationif(currentPosition + seekForwardTime <= mp.getDuration()){// forward songmp.seekTo(currentPosition + seekForwardTime);}else{// forward to end positionmp.seekTo(mp.getDuration());}}});/*** Backward button click event* Backward song to specified seconds* */btnBackward.setOnClickListener(newView.OnClickListener() {@Overridepublic void onClick(View arg0) {// get current song positionint currentPosition =mp.getCurrentPosition();// check if seekBackward time is greater than 0 secif(currentPosition - seekBackwardTime >= 0){// forward songmp.seekTo(currentPosition - seekBackwardTime);}else{// backward to starting positionmp.seekTo(0);}}});/*** Next button click event*点击后一首歌事件* */btnNext.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {// check if next song is there or notif(currentSongIndex < (songsList.size() - 1)){playSong(currentSongIndex + 1);currentSongIndex = currentSongIndex + 1;}else{// play first songplaySong(0);currentSongIndex = 0;}}});/*** 单击:前一首按钮事件* */btnPrevious.setOnClickListener(newView.OnClickListener() {@Overridepublic void onClick(View arg0) {if(currentSongIndex > 0){playSong(currentSongIndex - 1);currentSongIndex = currentSongIndex - 1;}else{// play last songplaySong(songsList.size() - 1);currentSongIndex = songsList.size() - 1;}}});/***循环播放按钮事件* */btnRepeat.setOnClickListener(newView.OnClickListener() {@Overridepublic void onClick(View arg0) {if(isRepeat){isRepeat = false;Toast.makeText(getApplication Context(), "Repeat is OFF", Toast.LENGTH_SHORT).show();btnRepeat.setImageResource(R. drawable.btn_repeat);}else{// make repeat to trueisRepeat = true;Toast.makeText(getApplication Context(), "Repeat is ON", Toast.LENGTH_SHORT).show();// make shuffle to falseisShuffle = false;btnRepeat.setImageResource(R. drawable.btn_repeat_focused);btnShuffle.setImageResource(R .drawable.btn_shuffle);}}});/*** 随机播放按钮事件* */btnShuffle.setOnClickListener(newView.OnClickListener() {@Overridepublic void onClick(View arg0) {if(isShuffle){isShuffle = false;Toast.makeText(getApplication Context(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();btnShuffle.setImageResource(R .drawable.btn_shuffle);}else{// make repeat to trueisShuffle= true;Toast.makeText(getApplication Context(), "Shuffle is ON", Toast.LENGTH_SHORT).show();// make shuffle to falseisRepeat = false;btnShuffle.setImageResource(R .drawable.btn_shuffle_focused);btnRepeat.setImageResource(R. drawable.btn_repeat);}}});/*** Button Click event for Play list click event* Launches list activity which displays list of songs* */btnPlaylist.setOnClickListener(newView.OnClickListener() {@Overridepublic void onClick(View arg0) {Intent i = newIntent(getApplicationContext(), PlayListActivity.class);startActivityForResult(i, 100);}});}/*** Receiving song index from playlist view* and play the song* */@Overrideprotected void onActivityResult(int requestCode,int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);if(resultCode == 100){currentSongIndex =data.getExtras().getInt("songIndex");// play selected songplaySong(currentSongIndex);}}/*** Function to play a song* @param songIndex - index of song* */public void playSong(int songIndex){// Play songtry {mp.reset();mp.setDataSource(songsList.get(songIndex).get ("songPath"));mp.prepare();mp.start();// Displaying Song titleString songTitle =songsList.get(songIndex).get("songTitle");songTitleLabel.setText(songTitle);// Changing Button Image to pause imagebtnPlay.setImageResource(R.drawable.btn_pause );// set Progress bar valuessongProgressBar.setProgress(0);songProgressBar.setMax(100);// Updating progress barupdateProgressBar();} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalStateException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}/*** Update timer on seekbar* */public void updateProgressBar() {mHandler.postDelayed(mUpdateTimeTask, 100);}/*** Background Runnable thread* */private Runnable mUpdateTimeTask = new Runnable() {public void run() {long totalDuration = mp.getDuration();long currentDuration =mp.getCurrentPosition();// Displaying Total Duration timesongTotalDurationLabel.setText(""+utils .milliSecondsToTimer(totalDuration));// Displaying time completed playingsongCurrentDurationLabel.setText(""+uti liSecondsToTimer(currentDuration));// Updating progress barint progress =(int)(utils.getProgressPercentage(currentDuration, totalDuration));//Log.d("Progress", ""+progress);songProgressBar.setProgress(progress);// Running this thread after 100 millisecondsmHandler.postDelayed(this, 100);}};/**** */@Overridepublic void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {}/*** When user starts moving the progress handler* */@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {// remove message Handler from updating progress barmHandler.removeCallbacks(mUpdateTimeTask);}/*** When user stops moving the progress hanlder* */@Overridepublic void onStopTrackingTouch(SeekBar seekBar) {mHandler.removeCallbacks(mUpdateTimeTask);int totalDuration = mp.getDuration();int currentPosition =utils.progressToTimer(seekBar.getProgress(), totalDuration);// forward or backward to certain secondsmp.seekTo(currentPosition);// update timer progress againupdateProgressBar();}/*** On Song Playing completed* if repeat is ON play same song again* if shuffle is ON play random song* */@Overridepublic void onCompletion(MediaPlayer arg0) {// check for repeat is ON or OFFif(isRepeat){// repeat is on play same song againplaySong(currentSongIndex);} else if(isShuffle){// shuffle is on - play a random songRandom rand = new Random();currentSongIndex =rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;playSong(currentSongIndex);} else{// no repeat or shuffle ON - play next songif(currentSongIndex < (songsList.size() - 1)){playSong(currentSongIndex + 1);currentSongIndex = currentSongIndex + 1;}else{// play first songplaySong(0);currentSongIndex = 0;}}}@Overridepublic void onDestroy(){super.onDestroy();mp.release();}}10:项目的功能配置文件AndroidManifest.xmlAndroidManifest.xml<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android=""package="com.androidhive.musicplayer"android:versionCode="1"android:versionName="1.0" ><uses-sdk android:minSdkVersion="8" /><applicationandroid:icon="@drawable/ic_launcher"android:label="@string/app_name" ><activityandroid:name=".AndroidBuildingMusicPlayerActivity"android:label="@string/app_name"android:configChanges="keyboardHidden|orientation"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="UNCHER" /> </intent-filter></activity><activityandroid:name=".PlayListActivity" /></application></manifest>。
android音乐播放器---源代码
android:background="@drawable/bg1">
<TextView android:layout_x="93px" android:layout_height="wrap_content"
<TextView android:layout_x="145px" android:layout_height="wrap_content"
android:text="" android:layout_y="65px" android:id="@+id/current_music"
android:textSize="18px" android:textColor="#C0FF3E"
<dimen name="button_size">40px</dimen>
</resources>
color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="white">#ffffff</color>
android:layout_height="wrap_content" />
简单实现Android本地音乐播放器
简单实现Android本地⾳乐播放器⾳乐播放需要调⽤service,在此,只是简单梳理播放流程。
public class PlayMusicService extends Service {//绑定服务调⽤服务的⽅法。
@Overridepublic IBinder onBind(Intent intent) {return null;}}<LinearLayout xmlns:android="/apk/res/android"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity" ><EditTextandroid:id="@+id/et_path"android:layout_width="fill_parent"android:layout_height="wrap_content"android:hint="请输⼊要播放⽂件的路径" /><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal" ><Buttonandroid:id="@+id/bt_play"android:onClick="play"android:layout_width="0dip"android:layout_height="wrap_content"android:layout_weight="1"android:text="播放" /><Buttonandroid:id="@+id/bt_pause"android:onClick="pause"android:layout_width="0dip"android:layout_height="wrap_content"android:layout_weight="1"android:text="暂停" /><Buttonandroid:id="@+id/bt_stop"android:onClick="stop"android:layout_width="0dip"android:layout_height="wrap_content"android:layout_weight="1"android:text="停⽌" /><Buttonandroid:id="@+id/bt_replay"android:onClick="replay"android:layout_width="0dip"android:layout_height="wrap_content"android:layout_weight="1"android:text="重播" /></LinearLayout></LinearLayout>public class MainActivity extends Activity {private EditText et_path;private MediaPlayer mediaPlayer;private Button bt_play,bt_pause,bt_stop,bt_replay;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);et_path = (EditText) findViewById(R.id.et_path);bt_play = (Button) findViewById(R.id.bt_play);bt_pause = (Button) findViewById(R.id.bt_pause);bt_stop = (Button) findViewById(R.id.bt_stop);bt_replay = (Button) findViewById(R.id.bt_replay);}/*** 播放* @param view*/public void play(View view) {String filepath = et_path.getText().toString().trim();File file = new File(filepath);if(file.exists()){try {mediaPlayer = new MediaPlayer();mediaPlayer.setDataSource(filepath);//设置播放的数据源。
android音乐播放器代码
81.});
82.
83.forwardBtn.setOnTouchListener(new OnTouchListener() { //点击“快进”按钮时回调
84. @Override
85. public boolean onTouch(View v, MotionEvent event) {
01./*变量声明*/
02.private ImageButton playBtn = null;//播放、暂停
03.private ImageButton latestBtn = null;//上一首
04.private ImageButton nextButton = null;//下一首
37.playBtn.setOnClickListener(new View.OnClickListener() { //点击“播放、暂停”按钮时回调
38. @Override
39. public void onClick(View v) {
testBtn = (ImageButton)findViewById(testBtn); //播放上一首按钮
31.nextButton = (ImageButton)findViewById(R.id.nextBtn); //播放下一首按钮
32.forwardBtn = (ImageButton)findViewById(R.id.forwardBtn); //快进按钮
64. play(); //开始播放
65. }
66.});
67.
68.nextButton.setOnClickListener(new View.OnClickListener(){//点击“播放下一首”按钮时回调
Android实现简单音乐播放器(MediaPlayer)
Android实现简单⾳乐播放器(MediaPlayer)Android实现简单⾳乐播放器(MediaPlayer),供⼤家参考,具体内容如下开发⼯具:Andorid Studio 1.3运⾏环境:Android 4.4 KitKat⼯程内容实现⼀个简单的⾳乐播放器,要求功能有:播放、暂停功能;进度条显⽰播放进度功能拖动进度条改变进度功能;后台播放功能;停⽌功能;退出功能;代码实现导⼊歌曲到⼿机SD卡的Music⽬录中,这⾥我导⼊了4⾸歌曲:仙剑六⾥⾯的《誓⾔成晖》、《剑客不能说》、《镜中⼈》和《浪花》,也推荐⼤家听喔(捂脸然后新建⼀个类MusicService继承Service,在类中定义⼀个MyBinder,有⼀个⽅法⽤于返回MusicService本⾝,在重载onBind()⽅法的时候返回public class MusicService extends Service {public final IBinder binder = new MyBinder();public class MyBinder extends Binder{MusicService getService() {return MusicService.this;}}@Overridepublic IBinder onBind(Intent intent) {return binder;}}在MusicService中,声明⼀个MediaPlayer变量,进⾏设置歌曲路径,这⾥我选择歌曲1作为初始化时候的歌曲private String[] musicDir = new String[]{Environment.getExternalStorageDirectory().getAbsolutePath() + "/Music/仙剑奇侠传六-主题曲-《誓⾔成晖》.mp3",Environment.getExternalStorageDirectory().getAbsolutePath() + "/Music/仙剑奇侠传六-主题曲-《剑客不能说》.mp3",Environment.getExternalStorageDirectory().getAbsolutePath() + "/Music/仙剑奇侠传六-主题曲-《镜中⼈》.mp3",Environment.getExternalStorageDirectory().getAbsolutePath() + "/Music/仙剑奇侠传六-主题曲-《浪花》.mp3"};private int musicIndex = 1;public static MediaPlayer mp = new MediaPlayer();public MusicService() {try {musicIndex = 1;mp.setDataSource(musicDir[musicIndex]);mp.prepare();} catch (Exception e) {Log.d("hint","can't get to the song");e.printStackTrace();}}设计⼀些歌曲播放、暂停、停⽌、退出相应的逻辑,此外我还设计了上⼀⾸和下⼀⾸的逻辑public void playOrPause() {if(mp.isPlaying()){mp.pause();} else {mp.start();}}public void stop() {if(mp != null) {mp.stop();try {mp.prepare();mp.seekTo(0);} catch (Exception e) {e.printStackTrace();}}}public void nextMusic() {if(mp != null && musicIndex < 3) {mp.stop();try {mp.reset();mp.setDataSource(musicDir[musicIndex+1]);musicIndex++;mp.prepare();mp.seekTo(0);mp.start();} catch (Exception e) {Log.d("hint", "can't jump next music");e.printStackTrace();}}}public void preMusic() {if(mp != null && musicIndex > 0) {mp.stop();try {mp.reset();mp.setDataSource(musicDir[musicIndex-1]);musicIndex--;mp.prepare();mp.seekTo(0);mp.start();} catch (Exception e) {Log.d("hint", "can't jump pre music");e.printStackTrace();}}}注册MusicService并赋予权限,允许读取外部存储空间<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/><service android:name="com.wsine.west.exp5_AfterClass.MusicService" android:exported="true"></service>在MainAcitvity中声明ServiceConnection,调⽤bindService保持与MusicService通信,通过intent的事件进⾏通信,在onCreate()函数中绑定Serviceprivate ServiceConnection sc = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName componentName, IBinder iBinder) {musicService = ((MusicService.MyBinder)iBinder).getService();}@Overridepublic void onServiceDisconnected(ComponentName componentName) {musicService = null;}};private void bindServiceConnection() {Intent intent = new Intent(MainActivity.this, MusicService.class);startService(intent);bindService(intent, sc, this.BIND_AUTO_CREATE);}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);Log.d("hint", "ready to new MusicService");musicService = new MusicService();Log.d("hint", "finish to new MusicService");bindServiceConnection();seekBar = (SeekBar)this.findViewById(R.id.MusicSeekBar);seekBar.setProgress(musicService.mp.getCurrentPosition());seekBar.setMax(musicService.mp.getDuration());musicStatus = (TextView)this.findViewById(R.id.MusicStatus);musicTime = (TextView)this.findViewById(R.id.MusicTime);btnPlayOrPause = (Button)this.findViewById(R.id.BtnPlayorPause);Log.d("hint", Environment.getExternalStorageDirectory().getAbsolutePath()+"/You.mp3");}bindService函数回调onSerciceConnented函数,通过MusiceService函数下的onBind()⽅法获得binder对象并实现绑定通过Handle实时更新UI,这⾥主要使⽤了post⽅法并在Runnable中调⽤postDelay⽅法实现实时更新UI,Handle.post⽅法在onResume()中调⽤,使得程序刚开始时和重新进⼊应⽤时能够更新UI在Runnable中更新SeekBar的状态,并设置SeekBar滑动条的响应函数,使歌曲跳动到指定位置public android.os.Handler handler = new android.os.Handler();public Runnable runnable = new Runnable() {@Overridepublic void run() {if(musicService.mp.isPlaying()) {musicStatus.setText(getResources().getString(R.string.playing));btnPlayOrPause.setText(getResources().getString(R.string.pause).toUpperCase());} else {musicStatus.setText(getResources().getString(R.string.pause));btnPlayOrPause.setText(getResources().getString(R.string.play).toUpperCase());}musicTime.setText(time.format(musicService.mp.getCurrentPosition()) + "/"+ time.format(musicService.mp.getDuration()));seekBar.setProgress(musicService.mp.getCurrentPosition());seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {@Overridepublic void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {if (fromUser) {musicService.mp.seekTo(seekBar.getProgress());}}@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {}@Overridepublic void onStopTrackingTouch(SeekBar seekBar) {}});handler.postDelayed(runnable, 100);}};@Overrideprotected void onResume() {if(musicService.mp.isPlaying()) {musicStatus.setText(getResources().getString(R.string.playing));} else {musicStatus.setText(getResources().getString(R.string.pause));}seekBar.setProgress(musicService.mp.getCurrentPosition());seekBar.setMax(musicService.mp.getDuration());handler.post(runnable);super.onResume();Log.d("hint", "handler post runnable");}给每个按钮设置响应函数,在onDestroy()中添加解除绑定,避免内存泄漏public void onClick(View view) {switch (view.getId()) {case R.id.BtnPlayorPause:musicService.playOrPause();break;case R.id.BtnStop:musicService.stop();seekBar.setProgress(0);break;case R.id.BtnQuit:handler.removeCallbacks(runnable);unbindService(sc);try {System.exit(0);} catch (Exception e) {e.printStackTrace();}break;case R.id.btnPre:musicService.preMusic();break;case R.id.btnNext:musicService.nextMusic();break;default:break;}}@Overridepublic void onDestroy() {unbindService(sc);super.onDestroy();}在Button中赋予onClick属性指向接⼝函数<Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/BtnPlayorPause"android:text="@string/btnPlayorPause"android:onClick="onClick"/>效果图打开界⾯->播放⼀会⼉进度条实时变化->拖动进度条->点击暂停->点击Stop->点击下⼀⾸(歌曲时间变化)->点击上⼀⾸->点击退出⼀些总结读取SD卡内存的时候,应该使⽤android.os.Environment库中的getExternalStorageDirectory()⽅法,然⽽并不能⽣效。
酷狗音乐源码分享,安卓源码
酷狗⾳乐源码分享,安卓源码本地⾳乐播放器,界⾯模仿Android版酷狗⾳乐V5.3某些功能点的业务逻辑的实现可提供⼀定的参考价值,故在此分享给需要的⼈。
⽬前已实现的功能有:1. 歌曲后台⾃动扫描。
2. 歌曲搜索,⽀持全键盘输⼊,T9键盘简拼、全拼搜索。
3. 歌曲排序,按歌曲名称、按歌⼿名称排序。
4. 歌曲分类,按⽂件夹、歌⼿、专辑分类。
5. 歌曲批量操作,全部播放、收藏到播放列表、删除。
6. 收藏列表的建⽴、修改、删除。
7. 歌曲播放、暂停、上⼀⾸、下⼀⾸,播放模式切换(随机、顺序、列表循环、单曲循环)。
8. 歌词同步显⽰,调⽤百度⾳乐盒接⼝⾃动下载歌词。
看截图,看代码,代码⽐较完善,值得学习。
下载地址:百度⽹盘,链接:https:///s/1nRiUMQf5Sszik0antAdpEA提取码:1234备⽤下载地址:https:///iLZh0gjo6je1/** 处理来⾃服务端的消息 */2private static class ClientIncomingHandler extends Handler {3// 使⽤弱引⽤,避免Handler造成的内存泄露(Message持有Handler的引⽤,内部定义的Handler类持有外部类的引⽤)4 WeakReference<PlayerActivity> mFragmentWeakReference = null;5 PlayerActivity mActivity = null;67public ClientIncomingHandler(PlayerActivity a) {8 mFragmentWeakReference = new WeakReference<PlayerActivity>(a);9 mActivity = mFragmentWeakReference.get();10 }1112 @Override13public void handleMessage(Message msg) {14switch (msg.what) {15case MSG_SET_LYRIC_INDEX:16if (mActivity.mLyricAdapter.isEmpty()) {17 Log.i(TAG, "歌词为空");18 mActivity.mView_tv_lyric_empty19 .setText(R.string.there_is_no_lyric_yet);20 } else {21 mActivity.mView_lv_lyricshow.setSelectionFromTop(msg.arg1,22 mActivity.mView_lv_lyricshow.getHeight() / 2);23 }24break;25default:26super.handleMessage(msg);27break;28 }29 }30 }3132/** 与Service连接时交互的类 */33private ServiceConnection mServiceConnection = new ServiceConnection() {34public void onServiceConnected(ComponentName className, IBinder service) {35 Log.i(TAG, "onServiceConnected");3637// 保持对Service的Binder引⽤,以便调⽤Service提供给客户端的⽅法38 mMusicServiceBinder = (MusicPlaybackLocalBinder) service;3940// 传递LyricListener对象给Service,以便歌词发⽣变化时通知本Activity41 mMusicServiceBinder.registerLyricListener(mLyricListener);4243// 传递OnPlaybackStateChangeListener对象给Service,以便⾳乐回放状态发⽣变化时通知本Activity44 mMusicServiceBinder45 .registerOnPlaybackStateChangeListener(mOnPlaybackStateChangeListener);4647// 请求加载歌词48 mMusicServiceBinder.requestLoadLyric();4950 initCurrentPlayInfo(mMusicServiceBinder.getCurrentPlayInfo());51 }5253// 与服务端连接异常丢失时才调⽤,调⽤unBindService不调⽤此⽅法哎54public void onServiceDisconnected(ComponentName className) {55 Log.i(TAG, "onServiceDisconnected");5657if (mMusicServiceBinder != null) {58 mMusicServiceBinder59 .unregisterOnPlaybackStateChangeListener(mOnPlaybackStateChangeListener);60 }61 }62 };。
安卓简单的音乐播放代码
1. [代码][Java]代码view sourceprint?001 package com.yongzheng.mymusic;002003 import java.io.File;004 import java.io.IOException;005 import java.util.ArrayList;006 import java.util.HashMap;007 import java.util.List;008 import java.util.Map;009 import java.util.Timer;010 import java.util.TimerTask;011012 import android.media.AudioManager;013 import android.media.MediaPlayer;014 import android.media.MediaPlayer.OnCompletionListener; 015 import android.media.MediaPlayer.OnErrorListener;016 import android.media.MediaPlayer.OnPreparedListener; 017 import android.os.Bundle;018 import android.os.Environment;019 import android.os.Handler;020 import android.os.Message;021 import android.annotation.SuppressLint;022 import android.app.Activity;023 import android.content.DialogInterface;024 import android.view.Menu;025 import android.view.View;026 import android.view.View.OnClickListener;027 import android.widget.AdapterView;028 import android.widget.AdapterView.OnItemClickListener; 029 import android.widget.Button;030 import android.widget.ListView;031 import android.widget.SeekBar;032 import android.widget.SimpleAdapter;033 import android.widget.TextView;034 import android.widget.Toast;035036 public class MainActivity extends Activity{037038 private TextView musicName ;//歌曲名称039 private TextView startTime;//播放时间040 private TextView endTime;//结束时间041 private SeekBar seekbar;//进度条042043 private Button start;//开始按钮044 private Button pause;//暂停按钮045 private Button restart;//重新开始046 private Button stop;//停止按钮047048 private ListView mylist;//列表049 private SimpleAdapter adapter = null; // 适配器050051 private Timer timer;052053 private MediaPlayer media = null;054 private List<Map<String, String>> musicListData;055056 private String lastPlayName = null;//记录最后一次播放的歌曲057058 @Override059 protected void onCreate(Bundle savedInstanceState) { 060 super.onCreate(savedInstanceState);061 setContentView(yout.activity_main);062 init();063 }064065 //初始化066 private void init(){067068 musicListData =069 new ArrayList<Map<String, String>>(); // 保存所有的List数据070071 this.musicName = (TextView) this.findViewById(R.id.musicName); 072 this.startTime = (TextView)this.findViewById(R.id.startTime); 073 this.endTime = (TextView)this.findViewById(R.id.endTime);074 this.seekbar = (SeekBar)this.findViewById(R.id.seekbar);075 this.start = (Button)this.findViewById(R.id.start);076 this.pause = (Button)this.findViewById(R.id.pause);077 this.restart = (Button)this.findViewById(R.id.restart);078 this .stop = (Button)this .findViewById(R.id.stop);079 this .mylist = (ListView)this .findViewById(R.id.mylist);080 addList();081 //点击事件082 this .start.setOnClickListener(new MyClickListener());083 this .pause.setOnClickListener(new MyClickListener());084 this .restart.setOnClickListener(new MyClickListener());085 this .stop.setOnClickListener(new MyClickListener());086087 this .seekbar.setOnSeekBarChangeListener(new SeekBarOnClickListenerImpl());088 //开启搜索sd 卡中MP3文件的线程089 new Thread(){090 public void run(){091 getMusicDate();//搜索sd 卡下面的mp3后缀的文件092 }093 }.start();094 }095096 //待搜索线程完成后,执行这个添加数据到界面上097 public void addList(){098 this .adapter = new SimpleAdapter(this ,this .musicListData,yout.list,099 new String[]{"name","size"},new int []{,R.id.size});100 this .mylist.setAdapter(adapter);101 this .mylist.setOnItemClickListener(new OnItemClickListener() {102 @Override103 public void onItemClick(AdapterView<?> adapt, View v, int postition,104 long id) {105 Map<String,String> map = MainActivity.this .musicListData.get(postition);106 if (MainActivity.this .media!=null ){107 stop();108 }109 play(map.get("path"));110 }111 });112 }113114 //获取播放列表115 public void getMusicDate(){116117 if(!(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED ))){118 //如果不sd卡存在119 return;120 }121 File rootPath = Environment.getExternalStorageDirectory(); 122 File[] listFile = rootPath.listFiles();123 if(listFile!=null){124 for(File f : listFile){125 if(f.isDirectory()){//如果是目录126 System.out.println("根文件夹:"+f.getName()); 127 getFile(f);128 }else{//如果是文件129 getAFile(f);130 }131 }132 }133134 Message message = new Message();135 message.what = 3;136 MainActivity.this.handler.sendMessage(message);137 return;138 }139140 //文件141 private void getAFile(File f){142 String fName = f.getName();143 if(!fName.endsWith("mp3")){144 return;145 }146 Map<String,String> map = new HashMap<String,String>();147 map.put("name",fName);148 map.put("size", String.valueOf(f.length()/1024/1024)+"MB"); 149 map.put("path",f.getAbsolutePath());150 musicListData.add(map);151 System.out.println("音乐文件路径:"+f.getAbsolutePath()); 152 }153 //路径154 private void getFile(File f){155 if(!f.isDirectory()){156 getAFile(f);157 return;158 }159 File[] listFile = f.listFiles();160 if(listFile!=null){161 for(File ff : listFile){162 if(f.isDirectory()){//如果是目录163 System.out.println("文件夹:"+ff.getName()); 164 getFile(ff);165 }else{//如果是文件166 System.out.println("文件:"+ff.getName()); 167 getAFile(ff);168 }169 }170 }171 }172173 //进度条监听回调174 private class SeekBarOnClickListenerImpl implementsSeekBar.OnSeekBarChangeListener {175176 @Override177 public void onProgressChanged(SeekBar seekBar, int progress, 178 boolean fromUser) {179 if(!fromUser)return;180 if(MainActivity.this.media!=null){181182 Message message = new Message();183 Bundle b = new Bundle();184 b.putInt("p", progress);185 message.setData(b);186 message.what = 2;187 MainActivity.this.handler.sendMessage(message);188 MainActivity.this.media.seekTo(progress);189 }190 }191192 @Override193 public void onStartTrackingTouch(SeekBar seekBar) {194 // TODO Auto-generated method stub195196 }197198 @Override199 public void onStopTrackingTouch(SeekBar seekBar) {200201 }202203 }204205 //播放控制的按钮事件206 class MyClickListener implements OnClickListener{207208 @Override209 public void onClick(View v) {210 switch(v.getId()){211 case R.id.start:212play(Environment.getExternalStorageDirectory()+File.separator+"my.mp3"); 213 break;214 case R.id.pause:215 pause();break;216 case R.id.restart:217 restart();break;218 case R.id.stop:219 stop();break;220 }221 }222223 }224225226 @Override227 public boolean onCreateOptionsMenu(Menu menu) {228 // Inflate the menu; this adds items to the action bar if it is present. 229 getMenuInflater().inflate(R.menu.main, menu);230 return true;231 }232233 //停止播放234 private void stop(){235 if(MainActivity.this.media!=null){236 MainActivity.this.start.setClickable(true); 237 MainActivity.this.media.release();238 MainActivity.this.media = null;239 }240 }241242 //从头开始播放243 private void restart(){244 if(MainActivity.this.media!=null){245 MainActivity.this.media.seekTo(0);246 }247 }248249 //暂停获取继续播放250 private void pause(){251 if(MainActivity.this.media==null){252 MainActivity.this.pause.setText("暂停"); 253 return;254 }255 if("继续".equals(MainActivity.this.pause.getText().toString())){ 256 MainActivity.this.media.start();257 MainActivity.this.pause.setText("暂停");258 }else if(MainActivity.this.media.isPlaying()){259 MainActivity.this.media.pause();260 MainActivity.this.pause.setText("继续");261 }262 }263264 //开始播放265 private void play(String path){266 if(path==null||"".equals(path)){267 Toast.makeText(this, "请选择播放文件", Toast.LENGTH_SHORT); 268 return;269 }270 this.musicName.setText(path.substring(stIndexOf("/")+ 1)); 271 File file = new File(path);272 if(file.exists()&&file.length()>0){273 try {274 this.media = new MediaPlayer();275 this .media.setAudioStreamType(AudioManager.STREAM_MUSIC);//设置播放类型276 this .media.setDataSource(path);277 this .media.setOnCompletionListener(new MediaCompletionListener());278 this .media.setOnErrorListener(new MediaErrorListener());279 this .media.prepare();280 this .media.start();281 this .start.setClickable(false );282 //启动事件更新及进度条更新任务,每0.5s 更新一次283 MainActivity.this .timer = new Timer();284 MainActivity.this .timer.schedule(new MyTask(), 0, 1000);285 } catch (Exception e) {286 e.printStackTrace();287 Toast.makeText(this , "播放文件错误", Toast.LENGTH_SHORT).show();288 }289290 }else {291 Toast.makeText(this , "播放文件不存在", Toast.LENGTH_SHORT).show();292 }293 }294295 @Override296 protected void onDestroy() {297 super.onDestroy();298299 if(this.media != null) { //如果播放器对象不为空300 this.media.release(); //释放播放器资源301 this.media = null; //设置对象为空302 }303 }304305 @SuppressLint("HandlerLeak")306 private Handler handler = new Handler() {307 public void handleMessage(Message msg) {308 switch(msg.what) {309 case1:310 if(MainActivity.this.media != null) {311 int progress =MainActivity.this.media.getCurrentPosition(); //当前播放毫秒312 int allTime = MainActivity.this.media.getDuration();//总毫秒313 MainActivity.this.seekbar.setMax(allTime);//设置进度条314MainActivity.this.startTime.setText(getTimeFormat(progress));315MainActivity.this.endTime.setText(getTimeFormat(allTime));316 MainActivity.this.seekbar.setProgress(progress);317 }318 break;319 case2:320 break;321 case3:322 addList();323 break;324 }325326 super.handleMessage(msg);327 }328 };329330 private String getTimeFormat(int time) {331 String timeStr = "00:00:00";332 int s = time/1000; //秒333 int h = s / 3600; //求整数部分,小时334 int r = s % 3600; //求余数335 int m = 0;336 if(r > 0) {337 m = r / 60; //分338 r = r % 60; //求分后的余数,即为秒339 }340341 if(h < 10) {342 timeStr = "0" + h;343 } else {344 timeStr = "" + h;345 }346347 if(m < 10) {348 timeStr = timeStr + ":" + "0" + m; 349 } else {350 timeStr = timeStr + ":" + m;351 }352353 if(r < 10) {354 timeStr = timeStr + ":" + "0" + r;355 } else {356 timeStr = timeStr + ":" + r;357 }358359 return timeStr;360 }361362363 private class MyTask extends TimerTask {364365 @Override366 public void run() {367 Message message = new Message();368 message.what = 1;369 MainActivity.this.handler.sendMessage(message); 370 }371 }372373 //播放时候错误回调374 private class MediaErrorListener implements OnErrorListener{375 @Override376 public boolean onError(MediaPlayer arg0, int arg1, int arg2) {377 MainActivity.this .media.stop();378 MainActivity.this .media.release();379 MainActivity.this .media = null ;380 Toast.makeText(MainActivity.this , "播放时候遇到错误,播放停止", Toast.LENGTH_LONG).show();381 return false ;382 }383 }384 //播放完成事件385 private class MediaCompletionListener implements OnCompletionListener{386 @Override387 public void onCompletion(MediaPlayer arg0) {388 MainActivity.this .media.stop();389 MainActivity.this .media.release();390 MainActivity.this .media = null ;391 MainActivity.this .musicName.setText("当前没有播放");392 MainActivity.this.startTime.setText("00:00"); 393 MainActivity.this.endTime.setText("00:00"); 394 MainActivity.this.start.setClickable(true); 395 }396397 }398 }。
音乐播放器程序源代码及注释
音乐播放器程序源代码及注释:#include <reg52.h>#define uchar unsigned char#define uint unsigned intsbit duan=P2^6;sbit key1=P3^2;//按key1可切换花样sbit key2=P3^3;//按key2可切换歌曲sbit fm=P2^4;//蜂鸣器连续的IO口sbit P30=P3^0;//矩阵键盘的一列uchar code huayang1[]={0x7f,0xbf,0xdf,0xef,0xf7,0xfb,0xfd,0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf};//花样1uchar code huayang2[]={0x7f,0xfe,0xbf,0xfd,0xdf,0xfb,0xef,0xf7,0xef,0xfb,0xdf,0xfd,0xbf,0xfe};//花样2uchar code huayang3[]={0x7f,0x3f,0x1f,0x0f,0x07,0x03,0x01,0x0,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff}; char codehuayang4[]={ 0x55,0xaa,0xcc,0x33,0x99,0x66,0x0f,0xf0}; uchar count1;//花样标志uchar count2;//歌曲标志uchar timeh,timel,i;//编程规则:字节高位是简谱,低位是持续时间,//代表多少个十六分音符//1-7代表中央C调,8-E代表高八度,0代表停顿//最后的0是结束标志uchar code qnzl[]={ //千年之恋0x12,0x22,0x34,0x84,0x74,0x54,0x38,0x42,0x32,0x22,0x42,0x34,0x84,0 x72,0x82,0x94,0xA8,0x08,//前奏0x32,0x31,0x21,0x32,0x52,0x32,0x31,0x21,0x32,0x62,//竹林的灯火到过的沙漠0x32,0x31,0x21,0x32,0x82,0x71,0x81,0x71,0x51,0x32,0x22,//七色的国度不断飘逸风中0x32,0x31,0x21,0x32,0x52,0x32,0x31,0x21,0x32,0x62,//有一种神秘灰色的旋涡0x32,0x31,0x21,0x32,0x83,0x82,0x71,0x72,0x02,//将我卷入了迷雾中0x63,0xA1,0xA2,0x62,0x92,0x82,0x52,//看不清的双手0x31,0x51,0x63,0x51,0x63,0x51,0x63,0x51,0x62,0x82,0x7C,0x02, //一朵花传来谁经过的温柔0x61,0x71,0x82,0x71,0x62,0xA2,0x71,0x76,//穿越千年的伤痛0x61,0x71,0x82,0x71,0x62,0x52,0x31,0x36,//只为求一个结果0x61,0x71,0x82,0x71,0x62,0xA3,0x73,0x62,0x53,//你留下的轮廓指引我0x42,0x63,0x83,0x83,0x91,0x91,//黑夜中不寂寞0x61,0x71,0x82,0x71,0x62,0x0A2,0x71,0x76,//穿越千年的哀愁0x61,0x71,0x82,0x71,0x62,0x52,0x31,0x36,//是你在尽头等我0x61,0x71,0x82,0x71,0x62,0xA3,0x73,0x62,0x53,//最美丽的感动会值得0x42,0x82,0x88,0x02,0x74,0x93,0x89,0xff//结束标志//用一生守候};uchar code jmszl[]={ //寂寞沙洲冷0x12,0x12,0x22,0x32,0x31,0x22,0x21,0x22,//自你走后心憔悴0x21,0x31,0x51,0x52,0x31,0x52,0x61,0x15,0x14,//白色油桐风中纷飞0x51,0x52,0x31,0x52,0x62,0x13,0x11,0x13,0x32,0x28,0x08,0x28, //落花似人有情这个季节0x31,0x32,0x31,0x32,0x11,0x21,0x51,0x52,0x51,0x52,//河畔的风放肆拼命地吹0x51,0x51,0x31,0x32,0x31,0x32,0x81,0x72,0x63,//不断拨弄离人的眼泪0x62,0x71,0x81,0x72,0x61,0x61,0x52,0x31,0x21,0x32,0x51,0x54, //那样浓烈的爱再也无法给0x22,0x12,0x11,0x12,0x11,0x12,0x12,0x14,0x26,0x32,0x26,//伤感一夜一夜0x32,0x61,0x51,0x51,0x31,0x31,0x21,0x31,0x51,0x61,0x51,0x31,0x51, //当记忆的线缠绕过往支离破碎0x02,0x32,0x81,0x81,0x81,0x81,0x62,0x52,0x34,//是慌乱占据了心扉0x31,0x81,0x81,0x81,0x61,0x91,0x82,//有花儿伴着蝴蝶0x51,0x51,0x51,0x51,0x31,0x61,0x53,//孤雁可以双飞0x21,0x11,0x21,0x11,0x22,0x11,0x21,0x26,//夜深人静独徘徊0x32,0x61,0x51,0x51,0x31,0x31,0x21,0x31,0x51,0x61,0x51,0x31,0x51,0 x52,//当幸福恋人寄来红色分享喜悦0x31,0x31,0x81,0x81,0x81,0x61,0x91,0x81,0x61,0x31,0x56,//闭上双眼难过头也不敢回0x32,0x32,0x81,0x81,0x81,0x81,0x91,0x81,0x61,0x81,0x61,0x51,0x31,0 x51,0x34,//仍然捡尽寒枝不肯安歇微带着后悔0x21,0x31,0x51,0x31,0x21,0x11,0x61,0x21,0x16,//寂寞沙洲我该思念谁0xff};uchar code cuzhi[]={0xff,0xff,//占位0xFC,0x8E,//中央C调1-70xFC,0xED,0xFD,0x43,0xFD,0x6A,0xFD,0xB3,0xFD,0xF3,0xFE,0x2D,0xFE,0x47, //高八度1-70xFE,0x76,0xFE,0xA1,0xFE,0xC7,0xFE,0xD9,0xFE,0xF9,0xFF,0x16};ucharyinyue[]={0xff,0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f,0x0,0x0}; //将音调转化为对应的LED样式void delay1(uint z); //延时1MSvoid delay(uint z); //延时165MS,即十六分音符void song();void beep();//蜂鸣器叫一声main(){ uchar x;count1=0;//流水灯无花样count2=1;//唱第一首歌P30=0;//选取矩阵键盘的一列EA=1;//开总中断EX0=1;//开外部中断0IT0=1;//外部中断0下降沿触发方式EX1=1;//开外部中断1IT1=1;//外部中断1下降沿触发方式TMOD=0x01;//定时器0工作在方式1 TH0=0;TL0=0;ET0=1;while(1){if(count1!=0){switch(count1){case 1:for(x=0;x<14;x++) {duan=1;P1=huayang1[x]; beep();delay1(300); duan=0;if(count1!=1) break;}break;case 2:for(x=0;x<14;x++) {duan=1;P1=huayang2[x]; beep();delay1(300); duan=0;if(count1!=2) break;}break;case 3:for(x=0;x<16;x++) {duan=1;P1=huayang3[x]; beep();delay1(300); duan=0;if(count1!=3) break;}break;case 4:for(x=0;x<8;x++) {duan=1;P1=huayang4[x]; beep();delay1(300); duan=0;if(count1!=4) break;}break;}}else{song();delay1(1000);}}}void int0() interrupt 0 {EA=0;//关总中断delay1(1);//去抖if(key1==0){count2=0;//不让蜂鸣器唱歌TR0=0;count1++;if(count1==5)count1=1;}EA=1;//开总中断}void int1() interrupt 2 {EA=0;//关总中断delay1(1);//去抖if(key2==0){count1=0;//流水灯无花样TR0=1;i=0;//从头开始唱count2++;if(count2==3)count2=1;}EA=1;//开总中断}void timer0() interrupt 1 //用于产生各种音调{ TH0=timeh;TL0=timel;fm=~fm;}void song(){uint temp;uchar jp;//jp是简谱i=0;while(1){ if(count2==0){break;}if(count2==1) //选曲temp=qnzl[i];if(count2==2)temp=jmszl[i];if(temp==0xff)break;jp=temp/16; //取数的高4位duan=1;P1=yinyue[jp];duan=0;if(jp!=0){timeh=cuzhi[jp*2];timel=cuzhi[jp*2+1];}else{TR0=0;fm=1;//关蜂鸣器}delay(temp%16); //取数的低4位TR0=0; //唱完一个音停10MSfm=1;delay1(10);TR0=1;i++;}TR0=0;fm=1;}void delay(uint z) //延时165MS,即十六分音符{ uint x,y; for(x=z;x>0;x--)for(y=19000;y>0;y--);}void delay1(uint z) //延时1MS{ uint x,y;for(x=z;x>0;x--)for(y=112;y>0;y--);}void beep() //蜂鸣器叫一声{ uchar i;for(i=0;i<50;i++){ fm=~fm;delay1(1);}fm=1;}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
基于an droid平台的音乐播放器开发实验报告学生姓名:_______ 温从林 _________________学号: ___________________________________班级:计自1201 _____________第一章引言1.1项目背景当今社会的生活节奏越来越快,人们对手机的要求也越来越高,由于手机市场发展迅速,使得手机操作系统也出现了不同各类,现在的市场上主要有三个手机操作系统,Win dowsmobile,symbia n,以及谷歌的An droid操作系统,其中占有开放源代码优势的An droid系统有最大的发展前景。
那么能否在手机上拥有自己编写的个性音乐播放器呢?能的,谷歌An droid系统就能做到。
本文的音乐播放器就是基于谷歌An droid手机平台的播放器。
An droid :是谷歌于2007年公布的开放式源代码手机系统,它的开放性就优于其它封闭式的手机系统,因此,任何人都可能根据自己的喜好将手机系统中的所有功能重新编写。
这使得越来越多的人关注这个操作系统。
本次作品音乐播放器就是基于An droid平台的。
1.2编写目的现今社会生活紧张,而欣赏音乐是其中最好的舒缓压力的方式之一,本项目的目的是开发一个可以播放主流音乐文件格式的播放器,本设计实现的主要功能是播放Mp3 Wav多种格式的音乐文件,并且能够控制播放,暂停,停止,播放列等基本播放控制功能,界面简明,操作简单。
本项目是一款基于An droid手机平台的音乐播放器,使An droid手机拥有个性的多媒体播放器,使手机显得更生动灵活化,与人们更为接近,让手机主人随时随地处于音乐视频的旋律之中。
使人们的生活更加多样化。
也使设计者更加熟练An droid的技术和其它在市场上的特点。
1.3开发环境Eclipse、An droid SDK 320第二章系统需求分析2.1功能需求(用例图分析)根据项目的目标,我们可获得项目系统的基本需求,以下从不同角度来描述系统的需求,并且使用用例图来描述,系统的功能需求,我们分成四部分来概括,即播放器的基本控制需要,播放列表管理需求,播放器友好性需求和播放器扩展卡需求。
以下分别描述:2.1.1播放器的用例图假设安装了音乐播放器的用户是系统的主要设计对象,其拥有以下操作,启动软件、播放音乐、暂停播放、停止播放、退出软件,其用例图如下图2.1 播放器基本用例图2.1.2用例分析用例名称:退出参与者:用户目标:使得用户退出或者后台播放音乐前置条件:程序在运行基本事件流:1.用户按返回键2. 播放器退出或者进入后台播放第三章概要设计3.1软件播放流程图Stepl.启动软件后,软件自动检索手机和sd卡的音频文件,并组织显示成列表Step2.点击列表的歌曲名字。
Step3.播放音乐。
Step4.点击暂停,音乐暂停Step5.点击播放转到step3Step6.点击停止停止播放音乐Step7 .点击退出。
自动检索手机中暂停/退出软件图3.1音乐播放器流第四章界面展示4.1 软件部署系统编译生成apk 文件,将apk 文件拷到手机或者sd 卡中,直接打开即可安装。
4.2 启动软件打开软件后的界面4.3 歌曲列表界面歌曲列表界面4.4 播放界面4.5 收藏界面4.6 在线搜索音乐界面第五章结论(1) 通过本次幵发解决了诸如SD卡音乐文件搜索并显示、联网搜索歌曲等难题,对安卓的开发有了更深入的认识。
(2) 通过对Android 手机平台的音乐播放器软件的开发,使我对Android 音乐播放器系统的整体设计有一个深入的了解,对整个流程也会有一个清晰的认识。
开发Android 音乐播放器,要抓住开发的核心部分,音乐播放器大体由播放主界面、播放列表、菜单、播放设置、文件浏览、歌曲搜索六大核心组成。
(3) 本次程序设计,对播放器的系统结构框架做了精心的构思与设计,采用主要开发工具是Eclips4.0+Java 语言的支持,Android Development Tool 的插件,和Android SDK2.1 版本的全面结合,才使整个音乐播放器系统得以实现第五章部分源代码以下给出功能实现代码,布局,风格等代码量过大,放在压缩文件中MainActivity.java:packageimportimportimportimportimportimportimportimportimportimportpublic class MainActivity extends ActionBarActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super .onCreate(savedInstanceState);requestWindowFeature(Window. FEATURE_NO_TITLE);setContentView(yout. fragment_main );Thread thread = new Thread() {public void run() {try {sleep (2500);} catch (InterruptedException e) {e.printStackTrace();}finish();Intent intent = new Intent(MainActivity. this , MusicActivity. class ); startActivity(intent);}};thread.start();}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu. main , menu);return true ;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) { //Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId();if (id == R.id. action_settings ) {return true ;}return super .onOptionsItemSelected(item);}* A placeholder fragment containing a simple view. */public static class PlaceholderFragment extends Fragment {public PlaceholderFragment() {}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {View rootView = inflater.inflate(yout. fragment_main false );, container, return rootView;}}}BandanActivity.javapackage ;importimportimportimportimportimportimportimportimportimportimportimportimportsuper .onCreate(savedInstanceState);setContentView(yout. bangdanmusic_list );listview = (ListView) findViewById(R.id. bangdan_music_list );listview .setOnItemClickListener( new MusicListOnClickListener()); ShowMp3List(); }*显示MP3言息,其中」ds 保存了所有音乐文件的_ID ,用来确定到底要播放哪一首歌曲,_titles 存放音乐名,用来显示在播放界面,*而_path 存放音乐文件的路径(删除文件时会用到)*/private void ShowMp3List() {// 用游标查找媒体详细信息this .getContentResolver().query(DISPLAY_NAME , // 显示名称 ,4cursor.moveToFirst();/** 分别将各个标题数组实例化 **/ _ids = new int [cursor.getCount()];_titles = new String[cursor.getCount()];_artists = new String[cursor.getCount()];_path =new Strin g[cursor.getCo un t()]; _album =new Strin g[cursor.getCo un t()]; privateListView listview ; privateString musicpath ; privateint _ids []; // 存放音乐文件的 id 数组 privateString _titles []; // 存放音乐文件的标题数组 privateString _artists []; // 存放音乐艺术家的标题数组 privateString[] _path ; // 存放音乐路径的标题数组 privateString[] _times ; // 存放总时间的标题数组 privateString[] _album ; // 存放专辑的标题数组 privateint _sizes []; // 存放文件大小的标题数组 private String[] displayname ; // 存放名称的标题数组@Overrideprotected void onCreate(Bundle savedInstanceState) {extends Activity { public class BangdanActivityCursor cursor = EXTERNAL_CONTENT new String[] {TITLE ,DURATION ,ARTIST , , UR ,I// 标题,游标从 0读取 // 持续时间 ,1 // 艺术家 ,2 // id ,3 DATA ,ALBUM_ID , ALBUM ,SIZE }, null/** 将游标移到第一位 **/ // 数据, 5 // 专辑名称 ID ,6// 专辑 ,7 , null ART IST ); // 大小 ,8_times = new Strin g[cursor.getCo un t()];_displa yn ame = new Strin g[cursor.getCo un t()];_sizes = new int [cursor.getCount()];到的内容格式为/mnt/sdcard/[ 子文件夹名/]音乐文件名,而我们想要得到的是/sdcard/[ 子文件夹名]音乐文件名*/for (int i = 0; i < cursor.getCount(); i++) {_ids [i] = cursor.getInt(3);_titles [i] = cursor.getStri ng(0);_artists [i] = cursor.getStri ng(2);_path [i] = cursor.getString(5).substring(4);/***** 以下是为提供音乐详细信息而生成的******/_album [i] = cursor.getString(7);_times [i] = toTime(cursor.getInt(1));_sizes [i] = cursor.getInt(8);_displa yn ame [i] = cursor.getStri ng(4);cursor.moveToNext();}listview .setAdapter( new MusicListAdapter( this , cursor));}/**时间的转换*/public String toTime( int time) {time /= 1000;int minute = time / 60;int second = time % 60;minute %= 60;/**返回结果用string 的format方法把时间转换成字符类型**/return Stri ng. format ("%02d:%02d" , min ute, seco nd);}/**音乐列表添加监听器,点击之后播放音乐*/public class MusicList On ClickListe ner impleme nts On ItemClickListe ner { @Overridepublic void on ltemClick(AdapterView<?>argO, View view, int positi on, long id) {musicpath ="/mnt" +_path [position];playMusic( musicpath );/*putExtraMusic(positio n); */Intent intent = new Inten t(Ba ngda nActivity. this PlayMusicActivity. class );startActivity(i ntent);fin ish();}}public void playMusic(String musicpath) {try {MediaPlayer mp = new MediaPlayer();mp.reset();mp.setDataSource(musicpath);mp.prepare();mp.start();} catch (Exception e){Toast. makeText (getApplicationContext(), Toast. LENGTH_SHOR)T.show();}}public void putExtraMusic( int position) { Intent intentIntent(BangdanActivity. this ,PlayMusicActivity. class );/*intent.putExtra("_ids", _ids);intent.putExtra("_path", _path);intent.putExtra("_titles", _titles);intent.putExtra("_artists", _artists);intent.putExtra("position", position);startActivity(intent);finish();*/intent = new Intent();Bundle bundle = new Bundle();bundle.putInt( "position" , 25);intent.putExtras(bundle);intent.setClass(BangdanActivity. this , PlayMusicActivity. class ); startActivity(intent);finish();}@Overrideprotected void onStop() {super .onStop();}private long exitTime = 0;public boolean onKeyDown( int keyCode, KeyEvent event) {if (keyCode == KeyEvent. KEYCODE_BACK && event.getAction() KeyEvent.ACTION_DOWN){if ((System. currentTimeMillis ()- exitTime ) > 2000){Toast. makeText (getApplicationContext(), " 再按一次退出程序 Toast.LENGTH_SHOR)T.show();exitTime = System. currentTimeMillis ();else {finish();System. exit (0);}return true ;无法播放此文件new}return super .onKeyDown(keyCode, event);}}CollectionActivity.javapublic class CollectionActivity extends ExpandableListActivity { @Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// 一级条目List<Map<String, String>>groups=new ArrayList<Map<String,String>>();Map<String, String> group1=new HashMap<String, String>();group1.put("group"," 【歌手】");Map<String, String> group2=new HashMap<String, String>();group2.put("group"," 【专辑】");groups.add(group1);groups.add(group2);// 二组条目List<List<Map<String, String>>> childs=newArrayList<List<Map<String,String>>>();// 第一组二级科目数据List<Map<String, String>> ArrayList<Map<String,String>>(); Map<String, String> item1=new HashMap<String, String>(); item1.put("child"," 林俊杰");Map<String, String> item2=new HashMap<String, String>(); item2.put("child"," 周杰伦");child1.add(item1);child1.add(item2);// 第二组二级科目数据List<Map<String, String>> ArrayList<Map<String,String>>(); Map<String, String> item3=new HashMap<String, String>(); item3.put("child","<< 因你而在>>");Map<String, String> item4=new HashMap<String, String>(); item4.put("child","<< 流行主教>>");Map<String, String> item5=new HashMap<String, String>(); item5.put("child","<< 第二天堂>>");child2.add(item3);child2.add(item4);child2.add(item5);childs.add(child1); child1=new child2=newchilds.add(child2);//SimpleExpandableListAdapter构造函数参数//1.content//2. 一级条目数据//3. 一级条目布局文件// 4 . 一级条目Key//5. 一级条目显示信息控件id//6. 二级条目数据//7. 二级条目布局文件//8. 二级条目Key//9. 二级条目显示信息控件idsetListAdapter(adapter);}private long exitTime = 0;public boolean onKeyDown(int keyCode, KeyEvent event) {if(keyCode == KeyEvent.KEYCODE_BACK&& event.getAction() KeyEvent.ACTION_DOWN){if((System.currentTimeMillis()-exitTime) >2000){ Toast.makeText(getApplicationContext(), " 再按一次退出程序", Toast.LENGTH_SHORT).show();exitTime = System.currentTimeMillis();}else { finish();System.exit(0);}return true;}return super.onKeyDown(keyCode, event);}/*** 初始化菜单*/public boolean onMenuKeyDown(int keyCode, KeyEvent event) { if(keyCode==KeyEvent.KEYCODE_MENU&& event.getAction() = KeyEvent.ACTION_DOWN){Toast.makeText(getApplicationContext(), " 未定义菜单" Toast.LENGTH_SHORT).show();}return true;}}Contsant.javapublic class Contsant {* 获取屏幕的大小0:宽度1 :高度}**/public static int[] getScreen(Context context) { WindowManager windowManagercontext.getSystemService(Context.WINDOW_SERVICE);Display display = windowManager.getDefaultDisplay();DisplayMetrics outMetrics = new DisplayMetrics(); display.getMetrics(outMetrics);return new int[] { (int) (outMetrics.density * outMetrics.widthPixels), (int)(outMetrics.density * outMetrics.heightPixels) };}/**获取文件的后缀名,返回大写**/ public static String getSuffix(String str) {int i = stIndexOf('.');if (i != -1) {return str.substring(i + 1).toUpperCase(); } return str;}/**格式化文件大小Byte->MB**/public static String formatByteToMB(int size){ float mb=size/1024f/1024f;return String.format("%.2f",mb);LRCbean.javapackage/** 歌词实体*/public class LRCbean {private int beginTime = 0; // 开始时间public int getBeginTime() {return beginTime;}public void setBeginTime( int beginTime) { this .beginTime = beginTime;}public int getLineTime() {return lineTime;(WindowManager)public void setLineTime( int lineTime) { this .lineTime = lineTime;}public String getLrcBody() { return lrcBody;public void setLrcBody(String lrcBody) {this .lrcBody = lrcBody;}private int lineTime = 0;private String lrcBody = null ; // 歌词实体}MDialog.java* 自定义的对话框*/public class MDialog extends Dialog {public MDialog(Context context) {super(context);}public MDialog(Context context, int theme) { super(context, theme);}public static class Builder {private Context context;private int mIcon = -1; // 提示图标private CharSequence mTitle; // 提示标题private CharSequence mMessage;// 提示内容private CharSequence mPositiveButtonText;// privateCharSequence mNegativeButtonText;// privateCharSequence mNeutralButtonText; // private booleanmCancelable = true;//private int mViewSpacingLeft; private int mViewSpacingTop;private int mViewSpacingRight;private int mViewSpacingBottom;private boolean mViewSpacingSpecified = false; // 提示内容Viewprivate View mView; private OnClickListener mPositiveButtonClickListener, mNegativeButtonClickListener, mNeutralButtonClickListener;private OnCancelListener mCancelListener;// private OnKeyListener mKeyListener; //取消键事件按键处理确定按钮文本拒绝按钮文本中间按钮文本是否启用取消键public Builder(Context context) {this.context = context;}public Builder setMessage(CharSequence message) { this.mMessage = message;return this;}public Builder setMessage(int message) { this.mMessage = context.getText(message);return this;}public Builder setTitle(int title) {this.mTitle = context.getText(title); return this;}public Builder setTitle(CharSequence title) {this.mTitle = title;return this;}public Builder setIcon(int icon) {this.mIcon = icon;return this;}public Builder setView(View view) {this.mView = view;mViewSpacingSpecified = false;return this;}public Builder setView(View view, int left, int top, int right, int bottom) {this.mView = view;this.mViewSpacingLeft = left; this.mViewSpacingTop = top; this.mViewSpacingRight = right; this.mViewSpacingBottom = bottom; mViewSpacingSpecified = true; return this; }public Builder setPositiveButton(int textId,final OnClickListener listener) { this.mPositiveButtonText = context.getText(textId);this.mPositiveButtonClickListener = listener; return this;}public Builder setPositiveButton(String text,final OnClickListener listener) { this.mPositiveButtonText = text;this.mPositiveButtonClickListener = listener; return this;}public Builder setNeutralButton(int textId,final OnClickListener listener) { this.mNeutralButtonText = context.getText(textId);this.mNeutralButtonClickListener = listener; return this;}public Builder setNeutralButton(String text,final OnClickListener listener) { this.mNeutralButtonText = text;this.mNeutralButtonClickListener = listener; return this;}public Builder setNegativeButton(int textId,final OnClickListener listener) { this.mNegativeButtonText = context.getText(textId);this.mNegativeButtonClickListener = listener; return this;}public Builder setNegativeButton(String text,final OnClickListener listener) { this.mNegativeButtonText = text;this.mNegativeButtonClickListener = listener; return this;}public Builder setCancelable(boolean cancelable) { this.mCancelable = cancelable;return this;}public Builder setOnCancelListener(OnCancelListener listener) { this.mCancelListener = listener;return this;}public Builder setOnKeyListener(OnKeyListener listener) { this.mKeyListener = listener;return this;}public MDialog create() {LayoutInflater inflater = (LayoutInflater) context.getSystemService(YOUT_INFLATER_SERVICE);dialog.setCancelable(mCancelable);// 设置取消键事件if (mCancelListener != null) {dialog.setOnCancelListener(mCancelListener);}// 设置键盘监听事件if (mKeyListener != null) { dialog.setOnKeyListener(mKeyListener);}// 获取对话框布局layout.setLayoutParams(newLayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));// 设置标题// 设置图标if (mIcon != -1) {}int count = 0;// 设置确定按钮count++;// 设置拒绝按钮count++;// 设置中间按钮count++;if(count==0){}// 一个按钮时,显示两边空间if (count == 1) {}// 设置提示消息if (!TextUtils.isEmpty(mMessage)) {} else {}// 设置提示内容布局if (mView != null) {if (mViewSpacingSpecified) {customPanel.setPadding(mViewSpacingLeft, mViewSpacingTop,mViewSpacingRight, mViewSpacingBottom);}customPanel.addView(mView);} else {}dialog.setContentView(layout);return dialog;}public MDialog show() {MDialog dialog = create();dialog.show();return dialog;}private boolean setButton(View layout, mPositiveButtonText2, int id,final Dialog dialog, final OnClickListener listener) {CharSequence if (!TextUtils.isEmpty(mPositiveButtonText2)) {final Button button1 = (Button) layout.findViewById(id);button1.setText(mPositiveButtonText2);if (listener != null) {button1.setOnClickListener(new View.OnClickListener(){ public void onClick(View v) {listener.onClick(dialog,DialogInterface.BUTTON_POSITIVE);}});}else{// 默认事件为关闭对话框button1.setOnClickListener(newView.OnClickListener() { public void onClick(View v) {dialog.cancel(); dialog.dismiss();}});}return true;} else { layout.findViewById(id).setVisibility(View.GONE); return false;}}}}MusicActivity.java/* 以Tabhost+RadioGroup 组合*/public class MusicActivity extends TabActivity OnCheckedChangeListener{private TabHost tabhost;private RadioGroup radiogroup;@OverrideimplementsrequestWindowFeature(Window.FEATURE_NO_TITLE); tabhost=getTabHost(); radiogroup.setOnCheckedChangeListener(this); radiogroup.setClickable(true);tabhost.addTab(tabhost.newTabSpec("local_music").setIndicator("local_musi c").setContent(new Intent(this,MusicListActivity.class)));tabhost.addTab(tabhost.newTabSpec("my_collect").setIndicator("my_collect" ).setContent(new Intent(this,CollectionActivity.class)));tabhost.addTab(tabhost.newTabSpec("net_music").setIndicator("net_music"). setContent(new Intent(this,NetMusicActivity.class)));}@Overridepublic void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { tabhost.setCurrentTabByTag("local_music");break; tabhost.setCurrentTabByTag("my_collect"); break; tabhost.setCurrentTabByTag("net_music"); break;}}}MusicListActivity.javapublic class MusicListActivity extends Activity {/** 音乐列表 **/private LayoutParams params; private Toast toast; // 提示 public static final int Ringtone = 0; public static final int Alarm = 1; public static final int Notification = 2; private TextView timers;// 显示倒计时的文字 public MusicListAdapter adapter; @Overrideprivate ListView listview; private String musicpath; private int _ids[]; // private String _titles[]; // private String _artists[]; // private String[] _path; // private String[] _times; // private String[] _album; // private int _sizes[]; // private String[] _displayname;// private int num; //num private LayoutInflater inflater;//存放音乐文件的 id 数组 存放音乐文件的标题数组 存放音乐艺术家的标题数组 存放音乐路过的标题数组 存放总时间的标题数组 存放专辑的标题数组 存放文件大小的标题数组 存放名称的标题数组确定一个标识 装载布局/** 选择子项点击事件***/ listview.setOnItemClickListener(new MusicListOnClickListener());listview.setOnCreateContextMenuListener(newMusicListContextListener());inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);params = newLayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);ShowMp3List();}/**显示MP3信息,其中」ds保存了所有音乐文件的_ID,用来确定到底要播放哪一首歌曲,_titles 存放音乐名,用来显示在播放界面,_path 存放音乐文件的路径(删除文件时会用到) 。