How to get duration of Audio Stream and continue audio streaming from any point

廉价感情. 提交于 2019-12-02 17:45:22

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!