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

前端 未结 2 1075
你的背包
你的背包 2021-01-31 22:55

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-mediapl

相关标签:
2条回答
  • 2021-01-31 23:21

    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
    0 讨论(0)
  • 2021-01-31 23:27

    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.

    0 讨论(0)
提交回复
热议问题