示例代码:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_media_player, container, false);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioAttributes(new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build());
//...
}
@Override public void onStart() { super.onStart();
try {
// set data source and prepare
mMediaPlayer.setDataSource(requireContext(), mUri);
mMediaPlayer.prepare();
// register listener
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnErrorListener(this);
// start playback
mMediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Log.d(TAG, "onError: MEDIA_ERROR_UNKNOWN");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Log.d(TAG, "onError: MEDIA_ERROR_SERVER_DIED");
break;
}
switch (extra) {
case MediaPlayer.MEDIA_ERROR_IO:
Log.d(TAG, "onError: MEDIA_ERROR_IO");
break;
case MediaPlayer.MEDIA_ERROR_MALFORMED:
Log.d(TAG, "onError: MEDIA_ERROR_MALFORMED");
break;
case MediaPlayer.MEDIA_ERROR_UNSUPPORTED:
Log.d(TAG, "onError: MEDIA_ERROR_UNSUPPORTED");