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

前端 未结 2 1079
你的背包
你的背包 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

提交回复
热议问题