播放或暂停音频时更改 innerHTML

Posted

技术标签:

【中文标题】播放或暂停音频时更改 innerHTML【英文标题】:Change innerHTML when audio is playing or paused 【发布时间】:2021-12-15 02:25:15 【问题描述】:

我正在尝试在音频暂停时更改几个按钮内的文本。现在我的函数确实暂停并播放音频,但由于我不太明白的原因,我的函数不会更改按钮内部的 html

⚆ _ ⚆ 我做错了什么?

  var Audio = document.getElementById('Audio');
  var buttonPlay = document.querySelectorAll('.music-play-button');
  for (var i = 0; i < buttonPlay.length; i++) 
    buttonPlay[i].addEventListener("click", function () 
      if (Audio.paused) 
        Audio.play();
        buttonPlay[i].innerHTML = "Pause Music";
       else 
        Audio.pause();
        buttonPlay[i].innerHTML = "Play Music";
      
    );
   
<button class="music-play-button">Play Music</button>
<button class="music-play-button">Play Music</button>
<button class="music-play-button">Play Music</button>
<audio id="Audio" src='https://dl.dropboxusercontent.com/s/0xu2nln4mpathtw/The%20Wraith.mp3'></audio> 

更新: 这是基于Kevin Mpofu 解决方案的改进版本。 当音频暂停或播放时,它确实会更改所有按钮内的 HTML。

      var Audio = document.getElementById("Audio");
      var buttonPlay = document.querySelectorAll(".music-play-button");

        
      buttonPlay.forEach((prm) => 
        Audio.addEventListener('playing', (event) => prm.innerHTML = "Pause Music";));

      buttonPlay.forEach((prm) => 
        Audio.addEventListener('pause', (event) => prm.innerHTML = "Play Music";));

      buttonPlay.forEach((prm) => 
        prm.addEventListener("click", function () 
          if (Audio.paused) 
            Audio.play();
            prm.innerHTML = "Pause Music";
           else 
            Audio.pause();
            prm.innerHTML = "Play Music";
          
        );
      );
    <button class="music-play-button">Play Music</button>
    <button class="music-play-button">Play Music</button>
    <button class="music-play-button">Play Music</button>
    <audio id="Audio" src="https://dl.dropboxusercontent.com/s/0xu2nln4mpathtw/The%20Wraith.mp3"></audio>

【问题讨论】:

【参考方案1】:

var Audio = document.getElementById('Audio');
var buttonPlay = document.querySelectorAll('.music-play-button');


buttonPlay.forEach(btn => 
    btn.addEventListener("click", function () 
        if (Audio.paused) 
          Audio.play();
          btn.innerHTML = "Pause Music";
         else 
          Audio.pause();
          btn.innerHTML = "Play Music";
        
      ); 
);
<button class="music-play-button">Play Music</button>
<button class="music-play-button">Play Music</button>
<button class="music-play-button">Play Music</button>
<audio id="Audio" src='https://dl.dropboxusercontent.com/s/0xu2nln4mpathtw/The%20Wraith.mp3'></audio>

【讨论】:

以上是关于播放或暂停音频时更改 innerHTML的主要内容,如果未能解决你的问题,请参考以下文章

音频完成后更改按钮 Xcode

如何检查音频队列中的音乐是不是正在播放或暂停

点击时切换音频?

播放运行服务器 url 音频的媒体播放器时 UI 更改停止

应用程序第二次在列表视图的适配器中播放音频时崩溃

通知中的播放/暂停按钮图像,Android