网页制作-音乐播放功能(二)

点击按钮实现播放音乐的切换

实现目标:1.点击左右按钮,实现音乐切换到上一首/下一首。2.同时实现音乐条上歌曲信息的更新。

​​

实现思路:1.实现音乐的切换本质上就是替换html文件中 <audio>元素的src属性值。

<audio src="./audio/起风了-权三岁.mp3" id="domMusic"></audio>

2.因此,可以创建一个二维数组,存储音乐的地址、歌曲名称、歌手名称。同时声明一个变量currentSong,来跟踪音乐播放位置。

3.所以我们创建三个主要函数:

(1)用来更新歌曲信息的函数updateSongInfo(index):通过函数传入的索引值,更新歌曲名字、歌手姓名、音乐图片。

(2)将歌曲切换到上一首prevSong():实现变量currentSong--,然后调用updateSongInfo(currentSong)更新相关信息。

(3)将歌曲切换到下一首nextSong():与prevSong()同理。

具体实现代码js:

// 更新歌曲信息

function updateSongInfo(index) {

 let wordsElement = document.querySelector('.words');

 if (wordsElement) {

  var songNameElement = wordsElement.querySelector('.song_name');

  var imgElement = document.querySelector('.music_icon img');

  if (songNameElement) {

   songNameElement.title = Array_songs[index][1]; // 修改title属性

   songNameElement.textContent = Array_songs[index][1]; // 修改文本内容

   imgElement.src='./images/song_img'+(index+1)+'.jpg';

  }

  var singerElement = wordsElement.querySelector('.singer');

  var imgElement = document.querySelector('.music_icon img');

  if (singerElement) {

   singerElement.title = Array_songs[index][2]; // 修改title属性

   singerElement.textContent = Array_songs[index][2]; // 修改文本内容

  }

 }

}
// 定义上一首的点击事件处理函数

function prevSong() {

 song_end();

 console.log('上一首被点击');

 currentSong--;

 if (currentSong < 0) {

  currentSong = Array_songs.length - 1;

 }

 domMusic.src = './audio/'+Array_songs[currentSong][0];

 domMusic.load();

 updateSongInfo(currentSong);

 playBtn.className='pause';

}

// 定义下一首的点击事件处理函数

function nextSong() {

 song_end();

 console.log('下一首被点击');

 currentSong++;

 if (currentSong === Array_songs.length) {

  currentSong = 0;

 }

 domMusic.src =  './audio/'+Array_songs[currentSong][0];

 domMusic.load();

 updateSongInfo(currentSong);

 playBtn.className='pause';

 

}

//

domMusic.addEventListener('canplay', function() {//在音频可以播放的第一时间执行操作

 initTime(); // 加载完成后初始化时长显示

});

// 获取上一首和下一首的元素

let prevBtn = document.querySelector('a.prev');

let nextBtn = document.querySelector('a.nxt');

prevBtn.addEventListener('click', prevSong);

nextBtn.addEventListener('click', nextSong);

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值