[番外] 来个音乐拨放器 Play! (序)

前言

参考 Tyler Potts 的 Demo 影片- Build a Music app using VueJS | Tutorial for Beginners,一步一步来做个简易播放器

Source Code 在这
先将 Demo 载下来并启动,看看画面的样子以及功能有哪些
music app

画面分成两部分:

  • 上半部

    • 可控制目前歌曲拨放/暂停/切换上下首
  • 下半部

    • 显示完整拨放清单,现正拨放的音乐会加上底色凸显

Vue 实体要有的内容??

先想想画面上会显示什麽资料 & 会需要纪录的状态? 写入 data

  • 歌名
  • 歌手
  • 音乐档案路径
  • 是否正在拨放
  • 目前的曲目
  • 建立 Audio() 物件

再来是,需要什麽 methods 去执行相关的动作 ?

  • 拨放/暂停
  • 上/下一首

p.s. 当实体建立完成後,取得目前必须拨放第几首曲目的 data ,修改 Audio 的 src,故写在 created 生命周期中。


Start!

建立 Vue 专案

// 安装 Vue-CLI
$ npm i -g @vue/cli

// 确认安装
$ vue -V

// 建立专案
$ vue create music-app

// 进入专案
$ cd music-app

// 确认 Vue 预设画面能正常启动
$ yarn serve

建立新的专案後,先来整理一下专案中的内容,例如

  • index.html 中的 title
  • 移除用不到的 hello.vue
  • App.vue 移除不需要的 template script style
  • mp3档案 放入 assets 中

data ?

data () {
    return {
      current: {},
      index: 0, // 曲目index,从 songs 第一首开始
      isPlaying: false,
      songs: [
        {
          title: 'xxx',
          artist: 'xxx',
          src: require('./assets/xxxx.mp3')
        },
        {
          title: 'xxx',
          artist: 'xxxx',
          src: require('./assets/xxxx.mp3')
        }
      ],
      player: new Audio() // 这里的 Audio 还没有给 src !!
    }
  },

实体建立後,可以在 created 中给 audio src,例如:

created () {
    this.current = this.songs[this.index];  // 之後要换曲目,直接变更 index 值
    this.player.src = this.current.src;
  }

methods ?

以 play 为范例:

play (song) {
  if (typeof song.src != "undefined") { // 确认audio src 非 undefined
    this.current = song;

    this.player.src = this.current.src;
  }

  this.player.play();
  this.player.addEventListener('ended', function () { // 假设为播完状态,即跳下一首 index + 1
    this.index++;
    if (this.index > this.songs.length - 1) {
      this.index = 0;
    }

    this.current = this.songs[this.index];
    this.play(this.current);
  }.bind(this));
  this.isPlaying = true;
},

未完待续.....

每日一句:
离开台北的天空,最辽阔 /images/emoticon/emoticon02.gif


<<:  Day 17 - 专案实战-记帐系统

>>:  如何衡量万事万物 (10) 人的判断

Spring Framework X Kotlin Day 3 IOC/DI

GitHub Repo https://github.com/b2etw/Spring-Kotlin...

Day 20 - 装个 Nessus 试试

这个旅程走了 2/3 了,还有 1/3(抱头) MAC 环境下安装 Nessus 先到 Nessu...

Day18:Flow 的中间运算子,资料输出前还可以做很多事喔

我们在上一篇的文章中,介绍了 Flow 的基本概念,包括如何建立一个 Flow,以及 Flow 是一...

【Vue】new Vue() 和 export default 差别

new Vue():建立Vue实例 export default:输出模块 先前建立组件时输入和输出...

登录档改造(三)--因人而异的专业玩法

最近去图书馆借的登录档的参考书终於到了,感觉有点像读书心得,不过是11年前的用在Win 7的,但比笔...