【问题标题】:JavaScript - Sound does not play along with random valuesJavaScript - 声音不随随机值一起播放
【发布时间】:2018-10-20 16:05:11
【问题描述】:

我有一个函数,它以不重复的方式显示对象数组中的随机单词。

我的目标是让它播放每个单词的声音片段(那个声音就是单词的发音)。

但是,由于某种原因,我在任何浏览器中都听不到任何声音,也没有显示任何错误消息。可能是什么原因?

这是我正在使用的:

const p = document.getElementById("randomWord");
const myWords = [
    {
       text: "alpha",
       audio: "alpha.mp3"
    },
        {
       text: "bravo",
       audio: "bravo.mp3"
    },
        {
       text: "charlie",
       audio: "charlie.mp3"
    },
        {
       text: "delta",
       audio: "delta.mp3"
    },
    {
       text: "echo",
       audio: "echo.mp3"
    }
 ];
 let remainingWords = [];

function randomize() {
  if (remainingWords.length === 0) remainingWords = myWords.slice();
  let length = remainingWords.length;
  let randomIndex = Math.floor(Math.random() * length);
  const word = remainingWords[randomIndex];
  remainingWords.splice(randomIndex, 1);
  console.log(word);
  console.dir(p);
  p.textContent = word.text;
  document.getElementById("soundClip").play(word.audio);
}
    <audio id="soundClip">Your browser does not support the audio element.</audio>
    <button onclick="randomize()" type="button">Random Word</button>
    <p id="randomWord"></p>

【问题讨论】:

    标签: javascript arrays object audio random


    【解决方案1】:

    HTMLMediaElement.play() function 不接受参数,而您正在尝试传入一个参数。

    未使用的参数不是 JavaScript 中的致命错误;它们只是没有被使用,因此出于所有意图和目的,您只需调用.play()

    由于&lt;audio&gt; 元素没有与之关联的源,因此没有任何播放。

    试试

    const audioElement = document.getElementById("soundClip");
    audioElement.src = word.audio;
    audioElement.play();
    

    改为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-23
      相关资源
      最近更新 更多