Skip to content Skip to sidebar Skip to footer

How To Get Duration Of Audio Stream And Continue Audio Streaming From Any Point

Description: I have following code for an Audio player. I can continue Audio playback from any duration by clicking on Progress Bar(between 0-to-mediaplayer.getDuration()). It is w

Solution 1:

Hope that it might solve your problem.

1) Duration and Progress of Audio Stream

I have looked into your code, you have a major error in your code to calculate time. You create new Date(durationInMillis). Date adds your locallity i.e GMT+XX hours, that is why you are getting 5- hours in the beginnging of streaming. You should use following method to calculate currentProgress/duration.

protected void setProgressText() {

    final int HOUR = 60*60*1000;
    final int MINUTE = 60*1000;
    final int SECOND = 1000;

    int durationInMillis = mediaPlayer.getDuration();
    int curVolume = mediaPlayer.getCurrentPosition();

    int durationHour = durationInMillis/HOUR;
    int durationMint = (durationInMillis%HOUR)/MINUTE;
    int durationSec = (durationInMillis%MINUTE)/SECOND;

    int currentHour = curVolume/HOUR;
    int currentMint = (curVolume%HOUR)/MINUTE;
    int currentSec = (curVolume%MINUTE)/SECOND;

    if(durationHour>0){
        System.out.println(" 1 = "+String.format("%02d:%02d:%02d/%02d:%02d:%02d", 
                currentHour,currentMint,currentSec, durationHour,durationMint,durationSec));            
    }else{
        System.out.println(" 1 = "+String.format("%02d:%02d/%02d:%02d", 
                currentMint,currentSec, durationMint,durationSec));
    }
}

2) Scrubbing for Stream.

MediaPlayer allows scrubbing of audio stream. I have implemented it in one of my projects, but it takes some time. It takes some time to resume audio streaming from another location.


Solution 2:

First big problem is your order of initialization: you call getDuration before you actually call setDataSource in resetAndStartPlayer. How is MediaPlayer supposed to know duration without data source?

Here's how to do that properly:

  1. call MediaPlayer.setDataSource() in Activity.onCreate

  2. execute AsyncTask, in its doInBackground call MediaPlayer.prepare(), this will take a while if it's streaming from http, but after it finishes, player should know lenght of media

  3. in the AsyncTask.onPostExecute call MediaPlayer.getDuration(), which should succeed if stream was opened successfully; afterwards you may call MediaPlayer.start()

Important things:

  • getDuration works after prepare was called
  • prepare may take longer time, and should be called in other thread
  • you may also use prepareAsync and avoid AsyncTask, then you'd use setOnPreparedListener callback to call getDuration

Post a Comment for "How To Get Duration Of Audio Stream And Continue Audio Streaming From Any Point"