首页 > 代码库 > Android多媒体-MediaPlayer使用方式

Android多媒体-MediaPlayer使用方式

先不多说,直接上代码

public class SimpleMediaPlayerActivity extends Activity {
	
	//private static final Uri mMusicUri = Uri.fromFile(new File("/sdcard/sound_file_1.mp3"));
	private static final Uri mMusicUri = Uri.parse("http://czanxi.azone.artron.net/users_info/88/czanxi/2009121322260351292.mp3");
	private MediaPlayer mMediaPlayer = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		playMusic1();
	}
	
	/**
	 * 第一种方式,通过create创建
	 */
	private void playMusic1() {
		stopCurrentMediaPlayer();
		mMediaPlayer = MediaPlayer.create(this, mMusicUri);  //prepared
		mMediaPlayer.start(); // no need to call prepare(); create() does that for you
	}

	/**
	 * 第二种方式,通过new MediaPlayer()创建,通过prepare
	 */
	private void playMusic2() {
		stopCurrentMediaPlayer();
		mMediaPlayer = new MediaPlayer();  //idle
		mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		try {
			mMediaPlayer.setDataSource(getApplicationContext(), mMusicUri);
			mMediaPlayer.prepare();			
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		mMediaPlayer.start();
	}
	
	/**
	 * 第三种方式,通过new MediaPlayer()创建,通过prepareAsync
	 */
	private void playMusic3() {
		mMediaPlayer = new MediaPlayer()  ;
		mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)  ;
		mMediaPlayer.setOnPreparedListener(new OnPreparedListener()
		{
			@Override
			public void onPrepared(MediaPlayer mediaPlayer) {
				mediaPlayer.start()  ;
			}
			
		}) ;
		try {
			mMediaPlayer.setDataSource(getApplicationContext(), mMusicUri);
			mMediaPlayer.prepareAsync()  ;//异步加载
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	@Override
	protected void onDestroy() {
		stopCurrentMediaPlayer();
		super.onDestroy();
	}
	
	private void stopCurrentMediaPlayer() {
		if (mMediaPlayer != null) {
			mMediaPlayer.stop();
			mMediaPlayer.release();
			mMediaPlayer = null;
		}
	}
	
}

第一种方式和二、三中的区别是:

new 之后是idle状态 ,create之后是 prepared状态。这也是为何我们在调用create之后不需要再手动调用prepare()方法去更改状态。

第一种、第二种和第三种的区别是:

前两种为同步方式,因为涉及到识别及解码等IO耗时操作,容易引起主线程堵塞。第三种为异步方式,不会引发此问题,推荐此方式。