iT邦幫忙

2021 iThome 鐵人賽

DAY 17
0
Modern Web

別再說我不會框架,網頁 Vue 起來!系列 第 17

[番外] 來個音樂撥放器 Play! (序)

  • 分享至 

  • twitterImage
  •  

前言

參考 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


上一篇
[Part 7 ] Vue.js 的精隨-元件生命週期 (續)
下一篇
[番外] 來個音樂撥放器 Play! (續)
系列文
別再說我不會框架,網頁 Vue 起來!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言