Home  >  Article  >  Web Front-end  >  How does uniapp keep music playing during page switching?

How does uniapp keep music playing during page switching?

PHPz
PHPzOriginal
2023-04-18 15:20:051762browse

With the continuous development of mobile Internet technology, APP has become an indispensable part of people's lives, and its music playback function is even more loved by users. In today's APP design, many APPs have added special effects to play music when switching pages to enhance the user experience. This article will take uniapp as an example to discuss how to keep music playing during page switching, and give the code implementation.

1. Background introduction

Uniapp is a full-end development framework based on Vue.js. It can compile and generate multi-end applications such as small programs, H5, and APPs with a set of codes. In the development of Uniapp, page switching is a common operation and is also a good user experience design. In order to improve the user experience, we can create more beautiful music effects by controlling the play and pause of music when switching pages.

2. Solution implementation

In Uniapp development, we can use the life cycle function of Vue.js and the global events provided by uni-app to realize the non-stop playing of music when switching pages. The specific steps are as follows:

  1. Install the global music player plug-in

We can install the uni-audio-player plug-in through npm or yarn, which can be applied in uni-app A global music player is provided and supports continued playback when switching pages.

npm installation method:

npm install uni-audio-player

yarn installation method:

yarn add uni-audio-player

  1. The page component references the global music player

Reference the uni-audio-player plug-in in the page component, and link the music resources of the current page in the page mounted() life cycle function Pass in the global music player.

  1. Modify the music playback status when switching pages

Before switching pages, use the beforeEnter global event provided by uni-app to pause the playback of music on the current page; after switching pages Finally, play the music again through the afterEnter global event provided by uni-app.

The following is the specific code implementation:

  1. Install uni-audio-player plug-in

npm install uni-audio-player

  1. Page component references the global music player