Android media player seekbar

这一生的挚爱 提交于 2019-12-05 01:14:43

问题


I have a service that creates, plays and handles a mediaplayer (just audio), yet I have a seekbar in the main activity that I want to, naturally, show the progress of the audio file and allow the user to seek to various positions.

What I'm having a hell of a time figuring out is: what would be the best or proper way to connect the seekbar in the UI to the mediaplayer in the service?


回答1:


Here is how I would do this:

  1. Bind to service that plays audio. The interface that server returns in onBind should have getCurrentPos() and getDuration() functions.

  2. In your Activity's onCreate bind to service

  3. In your Activity's onResume use Handler's postDelayed function to start updates.
  4. In your Activity's onPause stop all callbacks posted via postDelayed function.
  5. In runnable that is passed to postDelayed run boundService.getCurrentPos() and boundService.getDuration() and update the seekbar appropriately.

To summarize, you should use service binding and handler for recurring updates.

  1. For bound services read "Bound services" documentation (local bounded service should be sufficient in your scenario).
  2. How to user Handler for periodic updates read this question: Repeat a task with a time delay?



回答2:


Try taking a look at MediaController to see if it's of use to you.




回答3:


You can also try Otto from Square

You just need to create a class SeekBarSyncEvent.java, put the parameters you need in there:

  • int progress
  • int duration
  • boolean fromUser
  • whatever you need

Then you can initialize the seekbar from the activity by posting an event from the bus with your SeekBarSyncEvent class in the onPrepared() method from your service.

Finally create the @Subscribe method on your activity so it calls to your seekBarUpdate() method.

This should work fine, nice and easy to maintain.



来源:https://stackoverflow.com/questions/6255965/android-media-player-seekbar

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