Mobile Application Developer

Home » » How to play video and audio on Android

How to play video and audio on Android

Written By Mitul Nakum on Wednesday, May 12, 2010 | 7:00 PM

There is more than one way, to play media files on an Android phone, let me show you two of them.

Audio:
MediaPlayer is the easier way, if you just want to play an audio file in the background, somewhere in an appliaction. There are no ui controls here, but of course you can use MediaPlayer.stop(), play(), seekTo() ,etc. Just bind the needed functions to a button, gesture, or event. As you can see, it also throws a lot of exceptions, which you need to catch.


  1. public void audioPlayer(String path, String fileName){
  2. //set up MediaPlayer
  3. MediaPlayer mp = new MediaPlayer();
  4. try {
  5. mp.setDataSource(path+"/"+fileName);
  6. // TODO Auto-generated catch block
  7. e.printStackTrace();
  8. } catch (IllegalStateException e) {
  9. // TODO Auto-generated catch block
  10. e.printStackTrace();
  11. } catch (IOException e) {
  12. // TODO Auto-generated catch block
  13. e.printStackTrace();
  14. }
  15. try {
  16. mp.prepare();
  17. } catch (IllegalStateException e) {
  18. // TODO Auto-generated catch block
  19. e.printStackTrace();
  20. } catch (IOException e) {
  21. // TODO Auto-generated catch block
  22. e.printStackTrace();
  23. }
  24. mp.start();
  25. }

Video:
In this example, I open a video file, and decide if I want it to autoplay after it is loaded.
You propably want to store your video files, on the sd card. You can get the path to the sd card via: Environment.getExternalStorageDirectory().


  1. public
    void videoPlayer(String path, String fileName, boolean autoplay){
  2. //get current window information, and set format, set it up differently, if you need some special effects
  3. getWindow().setFormat(PixelFormat.TRANSLUCENT);
  4. //the VideoView will hold the video
  5. VideoView videoHolder = new VideoView(this);
  6. //MediaController is the ui control howering above the video (just like in the default youtube player).
  7. videoHolder.setMediaController(new MediaController(this));
  8. //assing a video file to the video holder
  9. videoHolder.setVideoURI(Uri.parse(path+"/"+fileName));
  10. //get focus, before playing the video.
  11. videoHolder.requestFocus();
  12. if(autoplay){
  13. videoHolder.start();
  14. }
  15. }





About Mitul Nakum

15+ years of experience in mobile application development which includes Symbian, J2ME, Android and iOS development

0 comments :

Post a Comment