Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android多媒體-MediaPlayer使用方式

Android多媒體-MediaPlayer使用方式

編輯:關於Android編程

先不多說,直接上代碼

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耗時操作,容易引起主線程堵塞。第三種為異步方式,不會引發此問題,推薦此方式。


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved