1. Use MediaPlayer to play audio files

Use MediaPlayer to play audio files

MediaPlayer Overview | Android Developers | Android Developers (google.cn)

MediaPlayer | Android Developers (google.cn)

1. Application requirements

  1. Asynchronous playback, using services for background playback; (there is currently no audio focus transfer function)
  2. Display the audio file list, select different songs, and play different audio files (not implemented);
  3. Add a progress bar to make the audio progress adjustable. (not implemented)

Note that audio focus transfer needs to be implemented. It cannot be like the beatbox application. When you click quickly, many audios will sound at the same time.

Currently only one background playback is implemented.

2. MediaPlayer

MediaPlayer supports three different media sources:

  1. Local resources, (files in the res/raw folder)
  2. Internal URI, for example, can be obtained through ContentResolver
  3. External URL (stream) For the list of media formats supported by Android,

Except for the first type of file, which does not require the prepare() operation, all other media resources require prepare().

Note one point:

reset

public void reset ()

Resets the MediaPlayer to its uninitialized state. After calling this method, you will have to initialize it again by setting the data source and calling prepare().

After reset(), you need to reset the data source and prepare() again.

Common API descriptions

getCurrentPosition(): Get the current playback position
getDuration(): Get the time of the file
getVideoHeight(): Get the video height
getVideoWidth(): Get the video width
isLooping(): Whether to loop
isPlaying(): Whether it is playing
pause(): pause
prepare(): prepare (synchronize)
prepareAsync(): Prepare (asynchronous)
release(): Release the MediaPlayer object
reset(): reset the MediaPlayer object
seekTo(int msec): Specifies the position of playback (time in milliseconds)
setAudioStreamType(int streamtype): Specifies the type of streaming media
setDisplay(SurfaceHolder sh): Set up SurfaceHolder to display multimedia
setLooping(boolean looping): Set whether to loop playback
setOnBufferingUpdateListener(MediaPlayer.OnBufferingUpdateListener listener): Buffer listening for network streaming media
setOnCompletionListener(MediaPlayer.OnCompletionListener listener): Listening for the end of network streaming media playback
setOnErrorListener(MediaPlayer.OnErrorListener listener): Set error message listening
setOnVideoSizeChangedListener(MediaPlayer.OnVideoSizeChangedListener listener): Video size listening
setScreenOnWhilePlaying(boolean screenOn): Set whether to use SurfaceHolder to display
setVolume(float leftVolume, float rightVolume): Set the volume
start(): Start playing
stop(): Stop playing

3. Play audio

(1) Files in the res/raw directory

Play audio provided as a local raw resource (saved in the application’s res/raw/ directory):

MediaPlayer mediaPlayer =MediaPlayer.create(context, R.raw.sound_file_1);
mediaPlayer.start();// no need to call prepare(); create() does that for you

“Raw” resources are files that the system does not attempt to parse in any particular way. However, the content of this resource should not be raw audio. It should be a properly encoded and formatted media file in one of the supported formats.

(2) Internal URI

Change line 30 in the MediaPlayerAudioService.java file

The file address here can be obtained using adb shell, enter the relevant folder, pwd

mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
File file = new File("//sdcard/Music/fly.mp3");
mPlayer.setDataSource(getApplicationContext(), Uri.parse(file.getAbsolutePath()));
mPlayer.prepare(); // might take long! (for buffering, etc)

(3) External URL (streaming)

4. Use the service to play music in the background

(1)Use startService

(2) Using binderService

binderService is better than startService. We can implement customized functional methods in binder, and binder can connect the caller and service.

MediaPlayerAudioService.java

public class MediaPlayerAudioService extends Service {<!-- -->
    private static final String TAG = "IntentService";
    private static final String EXTRA_AUDIO_RES_ID = "android.byd.audiovedio.audio_res_id";


    private MediaPlayer mPlayer = null;
    private boolean isRelease = true; //Flag to determine whether MediaPlayer is released
    private int mMusicResId;


    public MediaPlayerAudioService() {<!-- -->
    }

    public static Intent newIntent(Context context, int musicResId) {<!-- -->
        Intent intent = new Intent(context, MediaPlayerAudioService.class);
        intent.putExtra(EXTRA_AUDIO_RES_ID, musicResId);
        return intent;
    }

    //Define the object returned by the onBinder method
    public class MyBinder extends Binder {<!-- -->
        //Set song ResId
        public void setResId(int resId) {<!-- -->
            mMusicResId = resId;
        }

        // play
        public void play(){<!-- -->
            if (isRelease) {<!-- -->
                mPlayer = MediaPlayer.create(getApplicationContext(), mMusicResId);
                isRelease = false;
            }
            mPlayer.start(); //Start playing
        }

        // pause
        public void pause(){<!-- -->
            mPlayer.pause(); //Pause playback
        }

        // stop
        public void stop(){<!-- -->
            mPlayer.reset(); //Reset MediaPlayer
            mPlayer.release(); //Release MediaPlayer
            isRelease = true;
        }
    }
    private MyBinder mBinder = new MyBinder();

    @Override
    public IBinder onBind(Intent intent) {<!-- -->
        // TODO: Return the communication channel to the service.
        Log.i(TAG, "onBind method was called!");
        mMusicResId = intent.getIntExtra(EXTRA_AUDIO_RES_ID, 0);
        return mBinder;
    }

    @Override
    public void onCreate() {<!-- -->
        Log.i(TAG, "onCreate method was called!");
        super.onCreate();
    }

    @Override
    public boolean onUnbind(Intent intent) {<!-- -->
        Log.i(TAG, "onUnbind method was called!");
        return true;
    }

    @Override
    public void onDestroy() {<!-- -->
        Log.i(TAG, "onDestroy method was called!");
        super.onDestroy();
    }

    @Override
    public void onRebind(Intent intent) {<!-- -->
        Log.i(TAG, "onRebind method was called!");
        super.onRebind(intent);
    }
}

MediaPlayerAudioActivity.java

public class MediaPlayerAudioActivity extends AppCompatActivity implements View.OnClickListener{<!-- -->

    private Button mStartButton;
    private Button mPauseButton;
    private Button mStopButton;

    public static Intent newIntent(Context packageContext) {<!-- -->
        Intent intent = new Intent(packageContext, MediaPlayerAudioActivity.class);
        return intent;
    }

    //Keep the IBinder object of the started Service and define a ServiceConnection object at the same time
    private MediaPlayerAudioService.MyBinder mBinder;
    private ServiceConnection conn = new ServiceConnection() {<!-- -->

        //This method is called back when Activity disconnects from Service
        @Override
        public void onServiceDisconnected(ComponentName name) {<!-- -->
            System.out.println("------Service DisConnected-------");
        }

        // This method is called when the connection between Activity and Service is successful.
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {<!-- -->
            System.out.println("------Service Connected-------");
            mBinder = (MediaPlayerAudioService.MyBinder) service;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {<!-- -->
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media_player_audio);

        mStartButton = (Button) findViewById(R.id.btn_media_player_audio_start);
        mPauseButton = (Button) findViewById(R.id.btn_media_player_audio_pause);
        mStopButton = (Button) findViewById(R.id.btn_media_player_audio_stop);

        Intent intentService = MediaPlayerAudioService.newIntent(this, R.raw.fly);
        //Bind service
        bindService(intentService, conn, Service.BIND_AUTO_CREATE);

        mStartButton.setOnClickListener(this);
        mPauseButton.setOnClickListener(this);
        mStopButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {<!-- -->
        switch (view.getId()){<!-- -->
            case R.id.btn_media_player_audio_start:
                mBinder.play();
                mStartButton.setEnabled(false);
                mPauseButton.setEnabled(true);
                mStopButton.setEnabled(true);
                break;
            case R.id.btn_media_player_audio_pause:
                mBinder.pause();
                mStartButton.setEnabled(true);
                mPauseButton.setEnabled(false);
                mStopButton.setEnabled(false);
                break;
            case R.id.btn_media_player_audio_stop:
                mBinder.stop();
                // If you want to play again after stop(), you have to prepare() again
                mStartButton.setEnabled(true);
                mPauseButton.setEnabled(false);
                mStopButton.setEnabled(false);
                break;
        }
    }
}