Android Development-mediaplayer Simple music player
Function Introduction
function Implementation
1. Implementation of MediaPlayer
- Introduction to common methods of MediaPlayer
The implementation of the MediaPlayer includes initialization of the Mediaplayer,mediaplayer function implementation, including playback, pause, stop, leave, etc., the details are as follows:
MediaPlayer initialization includes reading a music file in a MP3 format and setting it to play in a loop:
publicvoidinitMediaPlayer() { try { //String file_path = "/storage/0123-4567/K.Will-Melt.mp3"; String file_path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/K.Will-Melt.mp3"; //String file_path = "/data/K.Will-Melt.mp3"; mediaPlayer.setDataSource(file_path); mediaPlayer.prepare(); mediaPlayer.setLooping(true); // 设置循环播放 catch (Exception e) { e.printStackTrace(); } }
The Play/Pause feature is placed in the Play/pause button, so it takes two to select a MediaPlayer state to set the playback and pause of the music:
publicvoidplayOrPause() { flag++; if10002; "pause"; if(mediaPlayer.isPlaying()){ mediaPlayer.pause(); animator.pause(); else { mediaPlayer.start();
Similarly, the implementation of the STOP function is placed in the Stop button to stop the music and place it in the initial state as "00:00":
publicvoidstop() { "stop"; animator.pause(); ifnull) { mediaPlayer.pause(); mediaPlayer.stop(); try { mediaPlayer.prepare(); mediaPlayer.seekTo(0); catch (Exception e) { e.printStackTrace(); } } }
Description: Since the call to stop (), sometimes the music does not stop immediately, so I added a pause () to ensure that the music stops playing.
Similarly, leaving the implementation of the function is placed in the Quit button, the main implementation of the entire application exit, specifically including the service, end activity and so on:
privatevoidquit() { musicService.animator.end(); handler.removeCallbacks(runnable); unbindService(sc); try { finish(); System.exit(0); catch (Exception e) { e.printStackTrace(); } }
2. Application of service
The
- service, which is the application component of the same level as the activity, represents the executable program. The difference is that the activity has a user interface running in the foreground, and the service cannot run itself and needs to be called through an activity or other context object. The service runs in the background, and it cannot interact directly with the user. By default, the service runs in the main thread of the application process. The service can be started in two ways, Context.startservice () and Context.bindservice ().
- enables programs to respond to events or user actions after exiting, or to continue running certain program functions in the background, through service.
- Android gives services a higher priority than inactive (inactivity) activities, so their processes are not easily killed by the system.
- The interaction of the activity with the service is:
with the accumulation of knowledge above, it is essential to implement the necessary parts of the service as follows:
1. Create a new Musicservice class that inherits from the service
public class musicservice extends service { public final ibinder binder = new mybinder (); public class mybinder extends binder { musicservice getService () { return Musicservice. this ; } }
/** * onBind 是 Service 的虚方法,因此我们不得不实现它。 * 返回 null,表示客服端不能建立到此服务的连接。 */ @Override publiconBind(Intent intent) { return binder; }
2. And bind Musicservice in activity:
@Override protectedvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getOverflowMenu(); setContentView(R.layout.activity_main); bindServiceConnection(); new MusicService();
PrivateServiceconnection sc =NewServiceconnection () {@Override Public void onserviceconnected(ComponentName componentname, IBinder IBinder) {Musicservice = ((Musicservice.mybinder) ibinder). GetService (); }@Override Public void onservicedisconnected(ComponentName componentname) {Musicservice =NULL; } };Private void bindserviceconnection() {Intent Intent =NewIntent ( This, Musicservice.class); StartService (Intent); Bindservice (Intent, SC, This. Bind_auto_create); }
3. Handler Update UI Interface
Using handler to manage the UI, you need to use both post and postdelayed two functions:
1. Post (Runnable R)
adding r to the message queue (in fact, executing a piece of code with the main thread of the UI so that the control can be adjusted in other threads at any time)
2. postdelayed (runnabled r,long delaymillis)
Adds r to the message queue and fires after a specified time (in milliseconds)
Therefore, in order to achieve the music playback display functions, you need to rewrite the runnable run function, the implementation of the following:
PublicHandler Handler =NewHandler (); PublicRunnable Runnable =NewRunnable () {@Override Public void Run() {Isplay.setonclicklistener (NewMyonclicklistener ()); Stop.setonclicklistener (NewMyonclicklistener ()); Quit.setonclicklistener (NewMyonclicklistener ());if(MusicService.mediaPlayer.isPlaying ()) {Statetext.settext ("Playing"); }Else{if(MusicService.which.equals ("Stop") {Statetext.settext ("Stop"); }Else if(MusicService.which.equals ("Pause") {Statetext.settext ("Pause"); }} playingtime.settext (Time.format (MusicService.mediaPlayer.getCurrentPosition ())); Totaltime.settext (Time.format (MusicService.mediaPlayer.getDuration ())); Seekbar.setprogress (MusicService.mediaPlayer.getCurrentPosition ()); Seekbar.setonseekbarchangelistener (NewSeekbar.onseekbarchangelistener () {@Override Public void onprogresschanged(SeekBar SeekBar,intProgressBooleanFromuser) {if(Fromuser) {MusicService.mediaPlayer.seekTo (seekbar.getprogress ()); } }@Override Public void Onstarttrackingtouch(SeekBar SeekBar) { }@Override Public void Onstoptrackingtouch(SeekBar SeekBar) { } }); Handler.postdelayed (runnable, -); } };
4. Achieve the rotation of the picture
The animation effect of the picture needs to use the Objectanimator class, the Objectanimator class can be used for the image translation, rotation, zooming and other animations, here we only need to use its rotation function, the implementation of the following:
public voidAnimatorAction() { if (mediaPlayer.isPlaying()) { animator.setDuration(5000); animator.setInterpolator(new// 均速旋转 // 无限循环 animator.setRepeatMode(ValueAnimator.INFINITE); animator.start(); } }
Description: Animator is an instance object of Objectanimator, Setduration 5000 means that the time required to rotate a week is 5000, so it can be used to set the speed of rotation, set to the wireless cycle mode, and add a interpolator to achieve a uniform rotation of the purpose , and finally call pause () to dynamically control the animation state as follows:
5. Progress bar Seekbar Function Realization
Seekbar features include displaying the song playback progress and dragging seekbar to any position to change the playback progress, because Android has encapsulated these functions, so the direct call is good, but also better understanding, the implementation of the following:
seekBar = (SeekBar) findViewById(R.id.seekBar); seekBar.setProgress(musicService.mediaPlayer.getCurrentPosition()); seekBar.setMax(musicService.mediaPlayer.getDuration());
Seekbar.setprogress (MusicService.mediaPlayer.getCurrentPosition ()); Seekbar.setonseekbarchangelistener (NewSeekbar.onseekbarchangelistener () {@Override Public void onprogresschanged(SeekBar SeekBar,intProgressBooleanFromuser) {if(Fromuser) {MusicService.mediaPlayer.seekTo (seekbar.getprogress ()); } }@Override Public void Onstarttrackingtouch(SeekBar SeekBar) { }@Override Public void Onstoptrackingtouch(SeekBar SeekBar) { } });
6. Dynamic Permission Request
See Android Dynamic permission request
7. Determine if the program is in the background
As the music needs to support background play, again from backstage into the foreground will have an impact on the event function of the foreground, so you can add a background judgment function, and add a flag to record whether the application into the background.
privateisApplicationBroughtToBackground() { ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1); if (!tasks.isEmpty()) { ComponentName topActivity = tasks.get(0).topActivity; if (!topActivity.getPackageName().equals(getPackageName())) { returntrue; } } returnfalse; }
At this point, simple music player based on MediaPlayer can be implemented, such as the need for complete project code, can leave the mailbox.
Android Development---MediaPlayer simple music player