一个完整android音乐播放器源码
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下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;}}。
安卓音乐播放器实现代码
1. Mp3Player.java 文件package com.jacky.multimedia;import java.io.File;import java.io.FilenameFilter;import java.io.IOException;import java.util.ArrayList;import java.util.List;import android.app.ListActivity;import android.media.MediaPlayer;import android.media.MediaPlayer.OnCompletionListener;import android.os.Bundle;import android.os.Handler;import android.view.KeyEvent;import android.view.View;import android.widget.ArrayAdapter;import android.widget.ImageButton;import android.widget.ListView;import android.widget.SeekBar;import android.widget.SeekBar.OnSeekBarChangeListener;import android.widget.TextView;public class Mp3Player extends ListActivity {/** Called when the activity is first created. *//* 定义5个图像按钮*/private ImageButton mFrontImageButton = null;private ImageButton mStartImageButton = null;private ImageButton mPauseImageButton = null;private ImageButton mStopImageButton = null;private ImageButton mNextImageButton = null;/*定义进度handler,显示百分比进度*/Handler mPercentHandler = new Handler();/*定义拖动条*/private SeekBar mSeekBar=null;/*定义显示文本框*/private TextView curProgressText=null;private TextView curtimeAndTotaltime=null;/* 定于一个多媒体对象*/public MediaPlayer mMediaPlayer = null;/*定于一个数据播放列表,用来存放从指定文件中搜索到的文件*/private List<String> mMusicList = new ArrayList<String>();/* 定义在播放列表中的当前选择项*/private int currentListItme = 0;/*定义要播放的文件夹路径*/private static final String MUSIC_PATH = new String("/mnt/sdcard/");/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(yout.main);/* 更新播放列表*/musicList();/*初始化多媒体对象*/mMediaPlayer = new MediaPlayer();/*初始化图像按钮*/mFrontImageButton = (ImageButton) findViewById(stImageButton); mStopImageButton = (ImageButton) findViewById(R.id.StopImageButton); mStartImageButton = (ImageButton) findViewById(R.id.StartImageButton); mPauseImageButton = (ImageButton) findViewById(R.id.PauseImageButton); mNextImageButton = (ImageButton) findViewById(R.id.NextImageButton);/*初始化拖动条和当前进度显示值*/mSeekBar=(SeekBar)findViewById(R.id.SeekBar01);curProgressText=(TextView)findViewById(R.id.currentProgress); curtimeAndTotaltime=(TextView)findViewById(R.id.curtimeandtotaltime);/*监听停止按钮*/mStopImageButton.setOnClickListener(new ImageButton.OnClickListener() {@Overridepublic void onClick(View v){/*判断是否正在播放歌曲*/if (mMediaPlayer.isPlaying()){/*如果在播放歌曲时,按下开始按钮,则重开开始播放*/mMediaPlayer.reset();}}});/*监听开始按钮*/mStartImageButton.setOnClickListener(new ImageButton.OnClickListener(){@Overridepublic void onClick(View v){ /*播放当前选择歌曲,通过listView列表中onListItemClick方法得到选择的时第几项*/playMusic(MUSIC_PATH + mMusicList.get(currentListItme));/*开始播放歌曲时,同步进行更新拖动条进度*/startSeekBarUpdate();}});/*监听暂停按钮*/mPauseImageButton.setOnClickListener(new ImageButton.OnClickListener(){public void onClick(View view){if (mMediaPlayer.isPlaying()){/*如果有播放歌曲,暂停*/mMediaPlayer.pause();}else{/*如果没有播放歌曲,则开始播放*/mMediaPlayer.start();}}});/*监听下一首按钮*/mNextImageButton.setOnClickListener(new ImageButton.OnClickListener(){@Overridepublic void onClick(View arg0){nextMusic();}/*监听上一首按钮*/mFrontImageButton.setOnClickListener(new ImageButton.OnClickListener() {@Overridepublic void onClick(View arg0){FrontMusic();}});/*监听拖动条*/mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {// TODO Auto-generated method stub/*如果拖动进度发生改变,则显示当前进度值*/curProgressText.setText("当前进度: "+progress);}@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {// TODO Auto-generated method stubcurProgressText.setText("拖动中...");}@Overridepublic void onStopTrackingTouch(SeekBar seekBar) {// TODO Auto-generated method stubint dest = seekBar.getProgress();int mMax = mMediaPlayer.getDuration();int sMax = mSeekBar.getMax();mMediaPlayer.seekTo(mMax*dest/sMax);}});}/*按键处理时间,当按下返回按键时的处理方法*/public boolean onKeyDown(int keyCode, KeyEvent event){if ( keyCode == KeyEvent.KEYCODE_BACK){mMediaPlayer.stop();mMediaPlayer.release();this.finish();return true;}return super.onKeyDown(keyCode, event);}/*ListView选择项监听方法,即当前鼠标在列表中选择的第几项*/protected void onListItemClick(ListView l, View v, int position, long id){currentListItme = position;playMusic(MUSIC_PATH + mMusicList.get(position));}/*更新播放列表*/public void musicList(){/*从指定的路径中读取文件,并与播放列表关联*/File home = new File(MUSIC_PATH);/*读取指定类型的文件,在本程序,指定播放类型为mp3*/if (home.listFiles(new MusicFilter()).length > 0){/*读取文件*/for (File file : home.listFiles(new MusicFilter())){mMusicList.add(file.getName());}/*播放文件与播放列表关联*/ArrayAdapter<String> musicList = new ArrayAdapter<String>(Mp3Player.this,yout.musicitme, mMusicList); setListAdapter(musicList);}}/*播放指定路径中的音乐*/private void playMusic(String path){{/* 重置多媒体*/mMediaPlayer.reset();/*读取mp3文件*/mMediaPlayer.setDataSource(path);/*准备播放*/mMediaPlayer.prepare();/*开始播放*/mMediaPlayer.start();/*监听播放是否完成*/mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {public void onCompletion(MediaPlayer arg0){/*播放完当前歌曲,自动播放下一首*/nextMusic();}});}catch (IOException e){}}/*播放下一首*/private void nextMusic(){if (++currentListItme >= mMusicList.size()){currentListItme = 0;}else{playMusic(MUSIC_PATH + mMusicList.get(currentListItme));}}/*播放上一首歌曲*/private void FrontMusic(){if (--currentListItme >= 0){currentListItme = 0;}{playMusic(MUSIC_PATH + mMusicList.get(currentListItme));}}/*更新拖动条进度*/public void startSeekBarUpdate(){mPercentHandler.post(start);}Runnable start=new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubmPercentHandler.post(updatesb);//用一个handler更新SeekBar}};Runnable updatesb =new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubint position = mMediaPlayer.getCurrentPosition();int mMax = mMediaPlayer.getDuration();int sMax = mSeekBar.getMax();mSeekBar.setProgress(position*sMax/mMax);curtimeAndTotaltime.setT ext("当前播放时间:"+position/1000+"秒"+"\n歌曲总时间: "+mMax/1000+"秒");mPercentHandler.postDelayed(updatesb, 1000);//每秒钟更新一次}};}/*播放文件选择类*/class MusicFilter implements FilenameFilter{public boolean accept(File dir, String name){/*指定扩展名类型*/return (name.endsWith(".mp3"));}}2.main.xls文件<?xml version="1.0" encoding="utf-8"?><AbsoluteLayoutxmlns:android="/apk/res/android" android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"><ListViewandroid:id="@id/android:list"android:layout_width="fill_parent"android:layout_height="fill_parent"android:layout_weight="1"android:drawSelectorOnT op="false"/><ImageButtonandroid:id="@+id/LastImageButton"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_x="10px"android:layout_y="70px"android:src="@drawable/last"/><ImageButtonandroid:id="@+id/StopImageButton"android:layout_height="wrap_content"android:layout_width="wrap_content"android:layout_x="70px"android:layout_y="70px"android:src="@drawable/stop"/><ImageButtonandroid:id="@+id/StartImageButton"android:layout_height="wrap_content"android:layout_width="wrap_content"android:layout_x="130px"android:layout_y="70px"android:src="@drawable/start"/><ImageButtonandroid:id="@+id/PauseImageButton"android:layout_height="wrap_content"android:layout_width="wrap_content"android:layout_x="190px"android:layout_y="70px"android:src="@drawable/pause"/><ImageButtonandroid:id="@+id/NextImageButton"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_x="250px"android:layout_y="70px"android:src="@drawable/next"/><SeekBar android:id="@+id/SeekBar01"android:layout_height="wrap_content"android:layout_x="0dp"android:layout_y="200dp"android:layout_width="fill_parent"android:max="100"android:progress="0"android:secondaryProgress="50"android:visibility="visible"></SeekBar><TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_y="250dp" android:id="@+id/currentProgress"></TextView><TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_y="300dp" android:id="@+id/curtimeandtotaltime"></TextView></AbsoluteLayout>3.musictime.xls<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="/apk/res/android" android:id="@+id/T extView01"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="@string/hello"/>4.AndroidManifest.xls<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="/apk/res/android" package="com.jacky.multimedia"android:versionCode="1"android:versionName="1.0"><application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Mp3Player"android:label="@string/app_name"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="UNCHER" /></intent-filter></activity></application><uses-sdk android:minSdkVersion="3" /></manifest>。
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 - 第六章结论...................................................................... 错误!未定义书签。
黑马程序员安卓教程:音乐播放器之编写框架
黑马程序员安卓教程:音乐播放器之编写框架我们已了解Service的原理和使用方法,下面就通过一个综合的案例来进一步掌握Service在项目中的编写方法。
设计需求:编写一个音乐播放器项目,实现功能:列表展示待播放的音乐,当点击列表中的某一条音乐时则后台开启一个服务用来播放该音乐。
具体实现步骤如下:1.新建工程【File】→【new】→【Android Application Project】命名为:03_百度音乐盒2.编写布局文件根据需求编写布局,效果如图1-1所示:图1-1所示图1-1对应的xml布局代码如例1-1:3.查找控件在主Activity中,根据控件的ID查找相关控件,代码如例1-2:4.编写实体bean新建一个包(com.itheima.baidubox.domain),在该包下新建一实体bean,用来封装每一首音乐信息。
代码如例1-3:例1-3例1-3是一个实体类,我们定义了该实体的name属性和path属性,并重写了其get方法和set方法。
同时,还在重写了该类的构造方法(无参构造方法和有参构造方法)。
5.编写适配器ListView 要展示待播放的音乐,我们需要调用ListView的setAdapter方法将待播放音乐部署到该ListView中。
具体步骤如下:模拟ListView数据源,代码如例1-4例1-4中new一个List 集合,然后向该集合中添加多个MusicInfo实体对象。
至此,数据源List集合已经编写完成,接下来就是编写适配器。
本例中,我们通过继承BaseAdapter来编写自己的适配器MyAdapter。
代码如例1-5所示:例1-5例1-5中MyAdapter继承BaseAdapter,并重写了getCount方法和getView方法,getCount方法返回了ListView列表中条目的数据,本例中就是数据源List集合的大小;getView方法返回了每一个条目的显示内容,本例new一个TextView用来展示待播放音乐的名称。
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小项目之“音乐播放器”
3 播放
播放
这是播放工作最基层的操作逻辑,当播放器第一次播放音乐、切歌,前期需要完成例如选歌等操作,最后的播放就交由该函数负责。
小技巧:如何让整个播放列表循环播放
mMediaPlayer.setDataSource(MusicService.this, mMusicUriList.get(currentIndex % mMusicUriList.size()));
MediaPlayer.create(context,R.raw.test);
////////////////////////////////////
res/raw里面的文件也可以使用setDataSource()方法加载哟
文章后面会讲解
手机内存SDCARD上的文件,如:/sdcard/test.mp3
Android小项目之“音乐播放器”
最近学习了Android的Activity、基本布局控件、自定义view、ListView、service、BroadcastReceiver等基础知识,就用它们来做个音乐播放器的小项目吧。
注意,该小项目还没添加扫描SDCARD音乐文件的功能,用这raw里面的资源。
本播放器需要用到的MediaPlayer方法已经介绍完毕,对上述MediaPlayer想要了解更多,请自行使用搜索引擎。
至此,我们应该学会了MediaPlayer的基本使用了。接下来,我们在Service中使用它来构建写功能函数,进行播放音乐的工作吧。
MusicService类
相信阅读此文的有些Service基础了,这里不会完整介绍Service编程,主要是讲解如何使用上述MediaPlayer类的方法来完成我们需要的业务。
所以,我们这里需要给Service封装许多函数以满足Activity的需要。
安卓简单的音乐播放代码
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 }。
android开发一个简单的Android音乐播放器
package com.basi;
import android.app.Activity; import android.content.Intent;
import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast;
public class MusicServiceActivity extends Activity {
private static String TAG = "MusicService";
@Override public void onCreate(Bundle savedInstanceState) {
mPlayer.start(); super.onStart(intent, startId);
}
@Override public void onDestroy() { Toast.makeText(this, "MusicSevice onDestroy()", Toast.LENGTH_SHORT)
super.onCreate(savedInstanceState); setContentView(yout.main);
Toast.makeText(this, "MusicServiceActivity", Toast.LENGTH_SHORT).show(); Log.e(TAG, "MusicServiceActivity"); initlizeViews(); }
一个完整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>。
安卓音乐播放器开发含源代码
基于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功能需求(用例图分析)根据项目的目标,我们可获得项目系统的基本需求,以下从不同角度来描述系统的需求,并且使用用例图来描述,系统的功能需求,我们分成四部分来概括,即播放器的基本控制需要,播放列表管理需求,播放器友好性需求和播放器扩展卡需求。
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 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项目源码,非常不错的开源项目,会让你事半功倍,希望大家补充。
谢谢!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音乐播放器歌词显示实例。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
本文出自:欢迎转载,转载请注明出自:安卓开发网下面将和大家一起介绍一个音乐播放器项目,完成后的播放器具有暂停,下一首,前一首,歌曲列表,播放条进度等一些基本功能,它只是播放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>。