Simple example of Android music playback (mediaplayer)

Use mediaplayer to complete the simplest music playback. After mastering this basic control, it can be directly used as the control of background music.

In order to play, we need three control buttons on the interface: play, pause and stop

See activity_ main.xml

In mainactivity.java, first declare a mediaplayer player.

Because music playback also requires special permissions, you can dynamically apply for permissions in oncreate before initializing the player.

Initialization method of player

Three buttons need to be instantiated in oncreate

Btnplay. Setonclicklistener (this) requires class extension support. Therefore, mainactivity adds implements view.onclicklistener

The part of obtaining permission requires user operation. According to the granting of permission, the software should make different responses. Once the permission is obtained, it is initialized; If you don't get permission, notify the user.

Handle the click events of all buttons in the interface in one onclick method.

Note that in case r.id.btnstop, we reinitialize the player after mediaplayer. Reset(). Without this statement, the measured effect is that clicking the stop button and then clicking the start button can not play music smoothly. Interested friends can experiment.

The logic of ondestroy () is easy to understand, which is to completely clean up the resources occupied by music playback.

Complete code example:

Of course, you can't forget to add a permission statement in androidmanifest. XML.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>