注意:有些设备可能支持其他的文件格式。
1.Audio
AAC LC/LTP、HE-AACv1(AAC+)、AMR-NB、AMR-WB、MP3、MIDI、Ogg Vorbis、PCM/WAVE、FLAC(3.1或3.1以上)
2.Image
JPEG、PNG、WEBP、GIF、BMP
3.Video
H.263、H.264 AVC、MPEG-4 SP、VP8(2.3.3或2.3.3以上)
大致步骤:
1.初始化MediaPlayer,附上要播放的媒体。
2.准备播放 prepare
3.开始播放 start
4.在播放结束前:停止或者暂停播放 pause or stop
5.播放完成 complete
android只支持有限数量的可同步的MediaPlayer,不释放它们会导致运行时错误,所以当你完成播放的时候,记得:
mediaPlayer.release(); 来释放所涉及的资源。
MediaPlayer可以播放本地文件、Content Providers、远程URL流。
加载:
// Load an audio resource from a package resource. MediaPlayer resourcePlayer = MediaPlayer.create(this, R.raw.my_audio); // Load an audio resource from a local file. MediaPlayer filePlayer = MediaPlayer.create(this, Uri.parse(“file:///sdcard/localfile.mp3”)); // Load an audio resource from an online resource. MediaPlayer urlPlayer = MediaPlayer.create(this, Uri.parse(“http://site.com/audio/audio.mp3”)); // Load an audio resource from a Content Provider. MediaPlayer contentPlayer = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
注意:上述这种create后返回mediaPlayer的方式,其实已经调用了prepare方法,所以不能再调用了。
涉及网络的,记得加网络权限。
方法2:
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(“/sdcard/mydopetunes.mp3”);
mediaPlayer.prepare();
与上面类似。
想要播放视频,比播放音频复杂许多。播放视频你必须有一个surface来支持。
2种方式来播放视频:
方法一:使用VideoView,内置了surface,通过MediaPlayer加载。
方法二:自己指定surface,直接操作底层的MediaPlayer。
播放视频通过VideoView:
final VideoView videoView = (VideoView)findViewById(R.id.videoView); // Assign a local file to play videoView.setVideoPath(“/sdcard/mycatvideo.3gp”); // Assign a URL of a remote video stream videoView.setVideoUri(myAwesomeStreamingSource);
当Video被初始化后,你可以控制它的播放通过使用start、stopPlayback、pause、seekTo方法。
VideoView还包含setKeepScreenOn方法,在播放中屏幕不锁屏。
方法一:使用VideoView:
// Get a reference to the Video View. final VideoView videoView = (VideoView)findViewById(R.id.videoView); // Configure the video view and assign a source video. videoView.setKeepScreenOn(true); videoView.setVideoPath(“/sdcard/mycatvideo.3gp”); // Attach a Media Controller MediaController mediaController = new MediaController(this); videoView.setMediaController(mediaController);
方法二:利用surface
SurfaceHolder是异步创建的,所以你必须等surfaceCreated触发后,你才能将Holder给mediaPlayer。
直接看框架代码:
public class SurfaceViewVideoViewActivity extends Activity implements SurfaceHolder.Callback { static final String TAG = “SurfaceViewVideoViewActivity”; private MediaPlayer mediaPlayer; public void surfaceCreated(SurfaceHolder holder) { try { // When the surface is created, assign it as the // display surface and assign and prepare a data // source. mediaPlayer.setDisplay(holder); mediaPlayer.setDataSource(“/sdcard/test2.3gp”); mediaPlayer.prepare(); } catch (IllegalArgumentException e) { Log.e(TAG, “Illegal Argument Exception”, e); } catch (IllegalStateException e) { Log.e(TAG, “Illegal State Exception“, e); } catch (SecurityException e) { Log.e(TAG, “Security Exception“, e); } catch (IOException e) { Log.e(TAG, “IO Exception“, e); } } public void surfaceDestroyed(SurfaceHolder holder) { mediaPlayer.release(); } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.surfaceviewvideoviewer); // Create a new Media Player. mediaPlayer = new MediaPlayer(); // Get a reference to the Surface View. final SurfaceView surfaceView = (SurfaceView)findViewById(R.id.surfaceView); // Configure the Surface View. surfaceView.setKeepScreenOn(true); // Configure the Surface Holder and register the callback. SurfaceHolder holder = surfaceView.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); holder.setFixedSize(400, 300); // Connect a play button. Button playButton = (Button)findViewById(R.id.buttonPlay); playButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mediaPlayer.start(); } }); // Connect a pause button. Button pauseButton = (Button)findViewById(R.id.buttonPause); pauseButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mediaPlayer.pause(); } }); // Add a skip button. Button skipButton = (Button)findViewById(R.id.buttonSkip); skipButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mediaPlayer.seekTo(mediaPlayer.getDuration()/2); } }); } }
mediaPlayer.start()后就开始播放。 getDuration方法获得播放的长度,getCurrentPosition找到当前播放到的位置。使用seekTo方法跳到指定的位置。
去确保一致的体验,Android提供了MediaController-一个标准的提供常用的Media控制按钮,就像:
你若想使用MediaController去控制播放,最好在代码中实例化它。当你这么做了,MediaController只会在你设置它为visible之后或者触摸它的Video View,或者与其交互。
如果你使用VideoView去显示你的视频内容,你可以简单得通过VideoView的setMediaController方法:
// Attach a Media Controller MediaController mediaController = new MediaController(this); videoView.setMediaController(mediaController);
去控制一个MediaPlayer,你需要去实现一个新的MediaController.MediaPlayerControl:
MediaController mediaController = new MediaController(this); mediaController.setMediaPlayer(new MediaPlayerControl() { public boolean canPause() { return true; } public boolean canSeekBackward() { return true; } public boolean canSeekForward() { return true; } public int getBufferPercentage() { return 0; } public int getCurrentPosition() { return mediaPlayer.getCurrentPosition(); } public int getDuration() { return mediaPlayer.getDuration(); } public boolean isPlaying() { return mediaPlayer.isPlaying(); } public void pause() { mediaPlayer.pause(); } public void seekTo(int pos) { mediaPlayer.seekTo(pos); } public void start() { mediaPlayer.start(); } });
使用setAnchorView方法去决定MediaController依附在哪个View上,这个View可以是任意View。
调用show或者hide来显示或者隐藏。
mediaController.setAnchorView(myView); mediaController.show();
MediaPlayer提供方法去控制音量、锁屏亮度、设置循环模式。
控制音量通过setVolume方法。
mediaPlayer.setVolume(0.5f, 0.5f); 值在0-1之间浮点数,0表示静音,1表示最大音量。 2个参数分别代表左声道和右声道。
mediaPlayer.setScreenOnWhilePlaying(true); //播放时,屏幕不锁屏。 if (!mediaPlayer.isLooping()) mediaPlayer.setLooping(true);
有些设备,附上了耳机,或者蓝牙耳机,会提供播放、暂停、skip、上一个播放的 按键。
你可以监听Action为:android.intent.action.MEDIA_BUTTON。
public class MediaControlReceiver extends BroadcastReceiver { public static final String ACTION_MEDIA_BUTTON = “com.paad.ACTION_MEDIA_BUTTON”; @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) { Intent internalIntent = new Intent(ACTION_MEDIA_BUTTON); internalIntent.putExtras(intent.getExtras()); context.sendBroadcast(internalIntent); } } } public class ActivityMediaControlReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (MediaControlReceiver.ACTION_MEDIA_BUTTON.equals( intent.getAction())) { KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT); switch (event.getKeyCode()) { case (KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) : if (mediaPlayer.isPlaying()) pause(); else play(); break; case (KeyEvent.KEYCODE_MEDIA_PLAY) : play(); break; case (KeyEvent.KEYCODE_MEDIA_PAUSE) : pause(); break; case (KeyEvent.KEYCODE_MEDIA_NEXT) : skip(); break; case (KeyEvent.KEYCODE_MEDIA_PREVIOUS) : previous(); break; case (KeyEvent.KEYCODE_MEDIA_STOP) : stop(); break; default: break; } } } }
AudioManager的registMediaButtonEventReceiver方法去注册接受者,可以防止其他APP也在监听ACTION。
// Register the Media Button Event Receiver to // listen for media button presses. AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE); ComponentName component = new ComponentName(this, MediaControlReceiver.class); am.registerMediaButtonEventReceiver(component); // Register a local Intent Receiver that receives media button // presses from the Receiver registered in the manifest. activityMediaControlReceiver = new ActivityMediaControlReceiver(); IntentFilter filter = new IntentFilter(MediaControlReceiver.ACTION_MEDIA_BUTTON); registerReceiver(activityMediaControlReceiver, filter);