MediaPlayer使用
官方文档:
https://developer.android.com/guide/topics/media/mediaplayer.html
示例代码:
首先网络音频资源别忘加权限
<uses-permission android:name="android.permission.INTERNET" />
如果需要保持屏幕常亮做如下设置:
uses the MediaPlayer.setScreenOnWhilePlaying()
or MediaPlayer.setWakeMode()
加权限:<uses-permission android:name="android.permission.WAKE_LOCK" />
支持三种来源音频资源
- Local resources
- Internal URIs, such as one you might obtain from a Content Resolver
- External URLs (streaming)
简单地说是:apk里raw,sd卡,网络
example (saved in your 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
不需要调用prepare()方法,create()方法帮你做了。
Uri类型,sdcard等。示例如下:
Uri myUri = ....; // initialize Uri here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();
网络上的:
String url = "http://........"; // your URL here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepare(); // might take long! (for buffering, etc)可能需很较长时间,因为需要缓冲等
mediaPlayer.start();
示例项目代码:
https://github.com/googlesamples/android-SimpleMediaPlayer
生命周期图: