首页 > 代码库 > 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耗时操作,容易引起主线程堵塞。第三种为异步方式,不会引发此问题,推荐此方式。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。