【问题标题】:Javascript - Play sound along with random values from an arrayJavascript - 与数组中的随机值一起播放声音
【发布时间】:2018-10-13 06:24:16
【问题描述】:

我正在尝试用随机问题进行测验。我希望每个问题都附有一个声音片段,该片段会在问题出现后立即自动播放。我还想要一个按钮,让用户可以重播声音剪辑。我怎样才能做到这一点呢?

我知道如何使用audioClips.play(); 播放单个音频片段。 但是如何播放数组中的音频片段,与问题“同步”?

这是我目前所拥有的:

var country = ["Italy", "Spain", "Portugal", "France", "Greece", "Ireland", "Germany"];
var audioClips = ["italy.mp3", "spain.mp3", "portugal.mp3", "france.mp3", "greece.mp3", "ireland.mp3", "germany.mp3"];
var capital = ["rome", "madrid", "lisbon", "paris", "athens", "dublin", "berlin"];
var random001 = Math.floor(Math.random() * country.length);

document.getElementById("country").textContent = country[random001];

function submit001() {
    var b = input001.value.toLowerCase();
    var text;
    if (b === capital[random001]) {
    goToNextQuestion();
        text = "Correct!";
    } else {
        text = input001.value.bold() + " is not correct!";
    }
    document.getElementById("input001").value = "";
    document.getElementById("answer001").innerHTML = text;
}

function goToNextQuestion() {
    document.getElementById("answer001").innerHTML = "";
    random001 = Math.floor(Math.random() * country.length);
    document.getElementById("country").innerHTML = country[random001];
    document.getElementById("input001").focus();
}
<p id="message001">What is the capital of <text id="country"></text>?</p>
    <input type="text" id="input001" autofocus onKeyDown="if(event.keyCode==13) submit001()">
<p id="answer001"></p>
<button onclick="playAudio()" type="button">Replay Audio</button>

【问题讨论】:

  • 您将在问题和音频数组中拥有相同数量的条目。如果随机问题在第三个索引上,则使用与音频数组相同的索引。
  • 感谢您的帮助。我还在学习 JavaScript,所以如果这是一个菜鸟问题,我很抱歉,但我该怎么做呢?

标签: javascript arrays audio random


【解决方案1】:

对于这个问题,您需要从数组的角度思考,而您需要从对象的角度思考。将相关信息组合到一个 Object 中,您就可以通过清晰易读的代码实现您的目标。

为了完成这项工作,我不得不对您的代码进行广泛的重构。这就是我想出的。

HTML

<head>
  <style>
    #startButton {
      display: block;
    }

    #quiz {
      display: none;
    }
  </style>
</head>
<body>
  <div id="startButton">
    <button type="button" onclick="startQuiz()">Start Quiz</button>
  </div>
  <div id="quiz">
    <p id="message001">What is the capital of <text id="country"></text>?</p>
    <input type="text" id="input001" autofocus onKeyDown="if(event.keyCode==13) checkAnswer()" value="">
    <p id="answer001"></p>
    <button id="replayButton" type="button" onclick="setAudio()">Replay Audio</button>
  </div>
</body>

Javascript

<script>
  var country = {
    "Italy": {
      "audio": "italy.mp3",
      "capital": "rome"
    },
    "Spain": {
      "audio": "spain.mp3",
      "capital": "madrid"
    },
    "Portugal": {
      "audio": "portugal.mp3",
      "capital": "lisbon"
    },
    "France": {
      "audio": "france.mp3",
      "capital": "paris"
    },
    "Greece": {
      "audio": "greece.mp3",
      "capital": "athens"
    },
    "Ireland": {
      "audio": "ireland.mp3",
      "capital": "dublin"
    },
    "Germany": {
      "audio": "germany.mp3",
      "capital": "berlin"
    }
  };

  var countryArray = Object.keys(country);

  function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;

  }

  function nextCountryName(){
    let randIndex = getRandomInt(1, countryArray.length) - 1;
    return countryArray[randIndex];
  };

  function playAudio(file){
    let playFile = new Audio(file);
    playFile.play();
  }

  function newCountry(newCountryName) {

    document.getElementById("country").textContent = newCountryName;
    document.getElementById("input001").value = "";
  }

  function isAnswerCorrect(answer, useCountry) {
    let answerId = document.getElementById("answer001");
    let ans = answer.toLowerCase();
    let text;

    if(ans == country[useCountry].capital){
      answerId.innerHTML = "Correct!";
      return true;
    } else {
      answerId.innerHTML = ans.bold() + " is not correct!";
      return false;
    }
  };

  function setAudio(){
    let thisCountry = document.getElementById("country").textContent;
    let audioFile = country[thisCountry].audio;
    let callStr = "playAudio(\'" + audioFile + "\')";
    document.getElementById('replayButton').setAttribute('onclick', callStr);
  }

  function checkAnswer(){
    let inputId = document.getElementById('input001');
    let answer = inputId.value;
    let thisCountry = document.getElementById("country").textContent;
    let audioFile = country[thisCountry].audio;
    let result = isAnswerCorrect(answer, thisCountry);

    if(result) {
      let cntryName = nextCountryName();
      newCountry(cntryName);
      playAudio(country[cntryName].audio);
    }
  };

  function startQuiz(){
    let startingCountry = nextCountryName();
    newCountry(startingCountry);

    document.getElementById('startButton').style.display = "none";
    document.getElementById('quiz').style.display = "block";

    playAudio(country[startingCountry].audio);
  };    
</script>
  • 我将var countryvar audioClipsvar capital 数组转换为一个名为var country 的对象。这样您就可以使用country.capitalcountry.audio 来获得您正在寻找的价值。
  • 根据this answer建议在调用.play()方法前设置音频文件类型new Audio("file_name")

虽然answer002answer003input002input003 等超出了您的问题范围,但可以轻松修改此代码,接受此类参数以进行更广泛的测验。

【讨论】:

  • 非常感谢您的帮助。但这似乎没有按预期工作。只有在用户正确回答后,它才会播放每个国家的音频片段。相反,我希望在显示国家/地区时播放音频。
  • @MikeMichaels 很容易修复。我假设您想在提交答案后重播,因为按钮名称是“重播音频”。等一下,我会解决的。
  • @MikeMichaels 您想在单击按钮时检查答案还是只想播放声音?
  • 我希望按钮只重放当前问题的声音。要检查答案,用户将按 Enter 键。
  • @MikeMichaels 是的,我确实注意到了这一点。好的,请稍等
【解决方案2】:
function playAudio() {
  // if you know how to play audio then follow these step
  //1. get file name from audioClips array at index randome001 like
  audioClip = audioClips[random001]
  // do whatever you need to do before playing audio like loading audio file or whatever
  //2. play audioClip.
}`

【讨论】:

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