How to play video and audio on Android


SDK Version: 
M3

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

picture

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.  
  5.     try {
  6.         mp.setDataSource(path+"/"+fileName);
  7.     } catch (IllegalArgumentException e) {
  8.         // TODO Auto-generated catch block
  9.         e.printStackTrace();
  10.     } catch (IllegalStateException e) {
  11.         // TODO Auto-generated catch block
  12.         e.printStackTrace();
  13.     } catch (IOException e) {
  14.         // TODO Auto-generated catch block
  15.         e.printStackTrace();
  16.     }
  17.     try {
  18.         mp.prepare();
  19.     } catch (IllegalStateException e) {
  20.         // TODO Auto-generated catch block
  21.         e.printStackTrace();
  22.     } catch (IOException e) {
  23.         // TODO Auto-generated catch block
  24.         e.printStackTrace();
  25.     }
  26.     mp.start();
  27. }

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.  
  16.  }