Monday, April 2, 2012

Streaming Media Files using Media Player Example


A recent client for an Android project asked for an Android activity that would display an image that you can click to play a sound.  Starting with Android 2.2, streaming mp3 from a url became much easier and supported within the Android base code. Unfortunately, it doesn't work reliably. However, downloading the mp3 sound files and playing them locally is very reliable.  So an Android background service (not shown) downloads files as needed when the app starts and stores them locally. The mp3 sound files are small and this method pretty much ensures that they can be played i.e. doesn't depend on Internet connectivity and enables offline mode. Be sure to release the media player when you're done with the Android activity.

 if (mAudioURL!=null) {  
       try  
        {  
           String localFilePath = cacheDirectory  
                     + FileUtils.getFileNameForUrl( mAudioURL);  
                if (CustomApplication.DEBUG)  
                {  
                     Log.d(TAG, "Looking for Local Image File is at: "  
                          + filePath);  
                }  
                if (filePath != null && !filePath.equals(cacheDirectory)  
                     && FileUtils.doesFileExist(filePath))  
                {  
                     mMediaPlayer.setDataSource(filePath);   
                     mMediaPlayer.prepare();  
                     mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {  
                       public void onPrepared(MediaPlayer mp) {  
                          mp.start();  
                       }  
                     });;  
                  mMediaPlayer.setOnCompletionListener(new OnCompletionListener(){  
                      @Override  
                public void onCompletion(MediaPlayer mp) {  
                     mMediaPlayer.reset();  
                }  
                  });  
                }  
      } catch (IllegalStateException e)  
      {  
        // e.printStackTrace();  
      }  
      catch (IllegalArgumentException e)  
      {  
        //  e.printStackTrace();  
      }  
      catch (IOException e)  
      {  
        // e.printStackTrace();  
      }  
           }  
 }  
      @Override  
             protected void onDestroy() {  
               super.onDestroy();  
               if (mMediaPlayer != null) {  
                 mMediaPlayer.release();  
                 mMediaPlayer = null;  
               }  
        }