【问题标题】:MP3 file not playing within a custom controlMP3 文件不在自定义控件中播放
【发布时间】:2021-04-30 06:55:36
【问题描述】:

所以我想使用这个非常酷的按钮:

https://css-tricks.com/making-pure-css-playpause-button/

我遇到的两个问题是我无法播放声音。我已将 mp3 文件放在根目录中,所以我假设我需要放置类似的东西

<button class='button'>
  <sound src="play.mp3" type="audio/mpeg">
</button>

当我使用标准音频控制时,它工作得很好,但我真的很想使用这个很酷的 bean 按钮。另外,如果我想将文本放在按钮的右侧,我该怎么办?

另外,如果我想要一个音频文件列表,如何实现?

谢谢你的帮助????

【问题讨论】:

  • 尝试发布您尝试过的内容以及您遇到的问题,堆栈溢出旨在帮助用户在社区的帮助下解决问题

标签: javascript html css mp3


【解决方案1】:

要将文本放在按钮的右侧,您可以将所有内容放在另一个带有显示的地方:flex;属性和弹性方向:行;

对于音频,我在 javascript 中创建了一个新的音频对象。然后我可以很容易地从代码中启动和停止它。

要使用多种声音,我们编辑 toggleSound() 函数以使用字符串作为歌曲名称。然后我们遍历字符串以检查是否有与之关联的声音。这是无限扩展的。只需在 switch 语句和按钮中添加更多音频对象和新案例来控制它们。

您可以看到,我们必须在每个按钮中提供音频名称,因此每个声音可以有多个按钮。

// some example audio
const song1 = new Audio(
  "https://ia800905.us.archive.org/19/items/FREE_background_music_dhalius/backsound.mp3"
);

// some other audio
const song2 = new Audio(
  "https://ia800905.us.archive.org/19/items/FREE_background_music_dhalius/FormulaFantasy.mp3"
);

function toggleSound(audioName) {
  // switch for every case of the song name.
  switch(audioName.toString()) {
    case "song1":
      var x = song1;
      break;
    case "song2":
      var x = song2;
      break;
    default:
      // set default song
      var x = song1;
  }
  
  if (x.paused) {
    x.play();
  } else {
    x.pause();
  }
}
.button {
  margin: 0 10px 10px 0;
  background: lightgray;
}

.button:hover {
  cursor: pointer;
}

.parent {
  display: flex;
  flex-direction: column;
}
<div class="parent">
  <div style="display: flex; flex-direction: row;">
    <!-- your cool button div -->
    <div onclick="toggleSound('song1');" class="button">
      Song 1
    </div>
    Neat button for the first song.
  </div>
  <div style="display: flex; flex-direction: row;">
    <!-- your cool button div -->
    <div onclick="toggleSound('song2');" class="button">
      Song 2
    </div>
    Button for the second song.
  </div>
</div>

【讨论】:

  • 非常感谢!如果我想通过声音列表来扩展它,有没有办法编写数组来使它更容易?而不必复制每个项目的代码?例如函数 toggleSound 1,2... .button 1,2...
  • 你好布兰登,我已经编辑了我的原始答案以添加一个有效的系统。我意识到您也可以使用关联数组来存储歌曲,但我没有在答案中添加。
  • 你看过电影抢夺吗?你是刀锋鲍里斯!这真是太棒了。非常感谢绝地网络开发大师?
  • 没问题!如果您没有其他问题,您可以将答案设置为正确,以便其他人也可以使用。
【解决方案2】:

你可以像这样使用html

<button onclick="play_pause()">play/pause</button>
<audio src="music.mp3" id="music"></audio>

还有像这样的javascript

function play_pause(){

            if(document.getElementById("music").paused){ //check whether music is paused
            document.getElementById("music").play();     //if paused then play it
            }

            else{document.getElementById("music").pause();} //else pause it
        }

【讨论】:

    猜你喜欢
    • 2010-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多