获取歌曲页信息

版权声明: https://blog.csdn.net/Helloyongwei/article/details/81662532

页面结构

歌曲也信息我们用song.html来展示。song.html中引入app.js来动态加载html结构

let view = {
   el: '#app',
   template: `
   <audio src="{{url}}"></audio>
   <div>
   <button class="play">播放</button>
   <button class="pause">暂停</button>
   </div>
   `,
   render(data) {
      $(this.el).html(this.template.replace('{{url}}', data.url))
   },
   play(){
       let audio = $(this.el).find('audio')[0]
       audio.play()
   },
   pause(){
       let audio = $(this.el).find('audio')[0]
       audio.pause()
   }
}

当我们在推荐音乐中的最新音乐模块点击播放图标的时候, 就会跳转到歌曲播放页。 其中url含有点击歌曲的id。通过这个id, 我们可以从leanCloud中获取歌曲的详细信息。并实现播放暂停功能。
歌曲id
歌曲页如下, 我们可以从url中看到歌曲的id。
歌曲页

获取歌曲信息

那么这个id从那里获取呢? js提供了一个API, window.location.search, 这个APi可以获取查询参数。 我们就通过这个API来获取歌曲的id。

getSongId(){
  let search = window.location.search
  if (search.indexOf('?')===0) {
      search = search.substring(1)
  }
  let array = search.split('&').filter((v=>v))
  let id = ''

  for (let i = 0; i < array.length; i++) {
      let keyValue = array[i].split('=')
      let key = keyValue[0]
      let value = keyValue[1]
      if (key === 'id') {
          id = value
      }
  }

  return id 
}

然后通过这个id从leanCloud后台获取歌曲的详细信息。

get(id) {
     var query = new AV.Query('Song');
     return query.get(id).then( (song)=> {
         Object.assign(this.data, {id: song.id, ...song.attributes})
     });
 }

get(id)中的代码为leanCloud官方提供的API。最后将数据渲染到歌曲就可以了

歌曲的播放暂停通过以下代码实现:

$(this.view.el).on('click', '.play', ()=>{
   this.view.play()

})
$(this.view.el).on('click', '.pause', ()=>{
    this.view.pause()
})

猜你喜欢

转载自blog.csdn.net/Helloyongwei/article/details/81662532