Create a Music Player on Android: Song Playback
2023-7-29 19:58:0 Author: code.tutsplus.com(查看原文) 阅读量:7 收藏

In this series, we are creating a music player on Android using the MediaPlayer and MediaController classes. In the first part, we created the app and prepared the user interface for playback. We presented the list of songs on the user device and specified a method to execute when the user makes a selection. In this part of the series, we will implement a Service class to execute music playback continuously, even when the user is not directly interacting with the application.

Looking for a Quick Solution?

This series takes you through the full process of creating an Android music player from scratch, but another option is to use one of the music player app templates on Envato Market, such as Android Music Player, which lets users browse and play music by albums, artists, songs, playlists, folders, and album artists.

Android Music PlayerAndroid Music PlayerAndroid Music Player
Android Music Player

Introduction

We will need the app to bind to the music playing Service in order to interact with playback, so you will learn some of the basic aspects of the Service life cycle in this tutorial if you haven't explored them before. Here is a preview of the final result that we're working towards:

Android Music PlayerAndroid Music PlayerAndroid Music Player

In the final installment of this series, we'll add user control over the playback and we'll also make sure the app will continue to function in various application states. Later, we will follow the series up with additional enhancements that you may wish to add, such as audio focus control, video and streaming media playback, and alternate ways of presenting the media files.

1. Create a Service

Step 1

Add a new class to your app, naming it MusicService or another name of your choice. Make sure it matches the name you listed in the Manifest. When creating the class in Eclipse, choose android.app.Service as its superclass. Eclipse should enter an outline:

1
public class MusicService extends Service {
2
3
  @Override
4
  public IBinder onBind(Intent arg0) {
5
    // TODO Auto-generated method stub

6
    return null;
7
  }
8
9
}

Extend the opening line of the class declaration to implement some interfaces we will use for music playback:

1
public class MusicService extends Service implements
2
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
3
MediaPlayer.OnCompletionListener {

Eclipse will display an error over the class name. Hover over the error and choose Add unimplemented methods. We will add code to the methods in a few moments. The interfaces we are implementing will aid the process of interacting with the MediaPlayer class.

Your class will also need the following additional imports:

1
import java.util.ArrayList;
2
import android.content.ContentUris;
3
import android.media.AudioManager;
4
import android.media.MediaPlayer;
5
import android.net.Uri;
6
import android.os.Binder;
7
import android.os.PowerManager;
8
import android.util.Log;

Step 2

Add the following instance variables to the new Service class:

1
//media player

2
private MediaPlayer player;
3
//song list

4
private ArrayList<Song> songs;
5
//current position

6
private int songPosn;

We will pass the list of songs into the Service class, playing from it using the MediaPlayer class and keeping track of the position of the current song using the songPosn instance variable. Now, implement the onCreate method for the Service:

1
public void onCreate(){
2
  //create the service

3
}

Inside onCreate, call the superclass method, instantiating the position and MediaPlayer instance variables:

1
//create the service

2
super.onCreate();
3
//initialize position

4
songPosn=0;
5
//create player

6
player = new MediaPlayer();

Next, let's add a method to initialize the MediaPlayer class, after the onCreate method:

1
public void initMusicPlayer(){
2
  //set player properties

3
}

Inside this method, we configure the music player by setting some of its properties as shown below:

1
player.setWakeMode(getApplicationContext(),
2
  PowerManager.PARTIAL_WAKE_LOCK);
3
player.setAudioStreamType(AudioManager.STREAM_MUSIC);

The wake lock will let playback continue when the device becomes idle and we set the stream type to music. Set the class as listener for (1) when the MediaPlayer instance is prepared, (2) when a song has completed playback, and when (3) an error is thrown:

1
player.setOnPreparedListener(this);
2
player.setOnCompletionListener(this);
3
player.setOnErrorListener(this);

Notice that these correspond to the interfaces we implemented. We will be adding code to the onPrepared, onCompletion, and onError methods to respond to these events. Back in onCreate, invoke initMusicPlayer:

Step 3

It's time to add a method to the Service class to pass the list of songs from the Activity:

1
public void setList(ArrayList<Song> theSongs){
2
  songs=theSongs;
3
}

We will call this method later in the tutorial. This will form part of the interaction between the Activity and Service classes, for which we also need a Binder instance. Add the following snippet to the Service class after the setList method:

1
public class MusicBinder extends Binder {
2
  MusicService getService() {
3
    return MusicService.this;
4
  }
5
}

We will also access this from the Activity class.

2. Start the Service

Step 1

Back in your app's main Activity class, you will need to add the following additional imports:

1
import android.os.IBinder;
2
import android.content.ComponentName;
3
import android.content.Context;
4
import android.content.Intent;
5
import android.content.ServiceConnection;
6
import android.view.MenuItem;
7
import android.view.View;

And you'll also need to declare three new instance variables:

1
private MusicService musicSrv;
2
private Intent playIntent;
3
private boolean musicBound=false;

We are going to play the music in the Service class, but control it from the Activity class, where the application's user interface operates. To accomplish this, we will have to bind to the Service class. The above instance variables represent the Service class and Intent, as well as a flag to keep track of whether the Activity class is bound to the Service class or not. Add the following to your Activity class, after the onCreate method:

1
//connect to the service

2
private ServiceConnection musicConnection = new ServiceConnection(){
3
4
  @Override
5
  public void onServiceConnected(ComponentName name, IBinder service) {
6
    MusicBinder binder = (MusicBinder)service;
7
    //get service

8
    musicSrv = binder.getService();
9
    //pass list

10
    musicSrv.setList(songList);
11
    musicBound = true;
12
  }
13
14
  @Override
15
  public void onServiceDisconnected(ComponentName name) {
16
    musicBound = false;
17
  }
18
};

The callback methods will inform the class when the Activity instance has successfully connected to the Service instance. When that happens, we get a reference to the Service instance so that the Activity can interact with it. It starts by calling the method to pass the song list. We set the boolean flag to keep track of the binding status. You will need to import the Binder class we added to the Service class at the top of your Activity class:

1
import com.example.musicplayer.MusicService.MusicBinder;

Don't forget to alter the package and class names to suit your own if necessary.

Step 2

We will want to start the Service instance when the Activity instance starts, so override the onStart method:

1
@Override
2
protected void onStart() {
3
  super.onStart();
4
  if(playIntent==null){
5
    playIntent = new Intent(this, MusicService.class);
6
    bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
7
    startService(playIntent);
8
  }
9
}

When the Activity instance starts, we create the Intent object if it doesn't exist yet, bind to it, and start it. Alter the code if you chose a different name for the Service class. Notice that we use the connection object we created so that when the connection to the bound Service instance is made, we pass the song list. We will also be able to interact with the Service instance in order to control playback later.

Return to your Service class to complete this binding process. Add an instance variable representing the inner Binder class we added:

1
private final IBinder musicBind = new MusicBinder();

Now amend the onBind method to return this object:

1
@Override
2
public IBinder onBind(Intent intent) {
3
  return musicBind;
4
}

Add the onUnbind method to release resources when the Service instance is unbound:

1
@Override
2
public boolean onUnbind(Intent intent){
3
  player.stop();
4
  player.release();
5
  return false;
6
}

This will execute when the user exits the app, at which point we will stop the service.

3. Begin Playback

Step 1

Let's now set the app up to play a track. In your Service class, add the following method:

1
public void playSong(){
2
  //play a song

3
}

Inside the method, start by resetting the MediaPlayer since we will also use this code when the user is playing subsequent songs:

Next, get the song from the list, extract the ID for it using its Song object, and model this as a URI:

1
//get song

2
Song playSong = songs.get(songPosn);
3
//get id

4
long currSong = playSong.getID();
5
//set uri

6
Uri trackUri = ContentUris.withAppendedId(
7
  android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
8
  currSong);

We can now try setting this URI as the data source for the MediaPlayer instance, but an exception may be thrown if an error pops up so we use a try/catch block:

1
try{
2
  player.setDataSource(getApplicationContext(), trackUri);
3
}
4
catch(Exception e){
5
  Log.e("MUSIC SERVICE", "Error setting data source", e);
6
}

After the catch block, complete the playSong method by calling the asynchronous method of the MediaPlayer to prepare it:

Step 2

When the MediaPlayer is prepared, the onPrepared method will be executed. Eclipse should have inserted it in your Service class. Inside this method, start the playback:

1
@Override
2
public void onPrepared(MediaPlayer mp) {
3
  //start playback

4
  mp.start();
5
}

In order for the user to select songs, we also need a method in the Service class to set the current song. Add it now:

1
public void setSong(int songIndex){
2
  songPosn=songIndex;
3
}

We will call this when the user picks a song from the list.

Step 3

Remember that we added an onClick attribute to the layout for each item in the song list. Add that method to the main Activity class:

1
public void songPicked(View view){
2
  musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
3
  musicSrv.playSong();
4
}

We set the song position as the tag for each item in the list view when we defined the Adapter class. We retrieve it here and pass it to the Service instance before calling the method to start the playback.

Before you run your app, implement the end button we added to the main menu. In your main Activity class, add the method to respond to menu item selection:

1
@Override
2
public boolean onOptionsItemSelected(MenuItem item) {
3
  //menu item selected

4
}

Inside the method, add a switch statement for the actions:

1
switch (item.getItemId()) {
2
case R.id.action_shuffle:
3
  //shuffle

4
  break;
5
case R.id.action_end:
6
  stopService(playIntent);
7
  musicSrv=null;
8
  System.exit(0);
9
  break;
10
}
11
return super.onOptionsItemSelected(item);

We will implement the shuffle function in the next tutorial. For the end button, we stop the Service instance and exit the app. Pressing the back button will not exit the app, since we will assume that the user wants playback to continue unless they select the end button. Use the same process if the the app is destroyed, overriding the activity's onDestroy method:

1
@Override
2
protected void onDestroy() {
3
  stopService(playIntent);
4
  musicSrv=null;
5
  super.onDestroy();
6
}

When you run the app at this point, you will be able to play songs by selecting them from the list and you can also exit the app using the end button.

Conclusion

We have now implemented basic playback of music tracks selected from the user's list of music files. In the final part of this series, we will add a media controller through which the user will be able to control playback. We will add a notification to let the user return to the app after navigating away from it and we will carry out some housekeeping to make the app cope with a variety of user actions.

Did you find this post useful?

Sue Smith

Technical writer (and sometimes developer) based in Glasgow, UK. Having worked with the Mozilla Foundation and various online publications, I enjoy helping people to learn web and software development topics, regardless of their existing skill level. Particular areas of interest include education technology and open source projects.


文章来源: https://code.tutsplus.com/create-a-music-player-on-android-song-playback--mobile-22778t
如有侵权请联系:admin#unsafe.sh