Javascript-播放声音以及数组中的随机值

时间:2018-10-12 17:26:41

标签: javascript arrays audio random

我正在尝试对随机问题进行测验。我希望每个问题都伴随有一个声音片段,该声音片段会在问题显示后立即自动播放。我还希望有一个按钮,使用户可以重播声音剪辑。我该如何实现呢?

我知道如何使用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>

2 个答案:

答案 0 :(得分:1)

对于这个问题,您正在考虑使用数组,而您需要考虑对象。将相关信息组合到一个对象中,即可使用清晰易读的代码实现目标。

要完成这项工作,我不得不广泛地重构您的代码。这是我想出的。

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,建议您在调用new Audio("file_name")方法之前设置音频文件类型.play()

虽然answer002answer003input002input003等不在您的问题范围内,但是可以轻松地修改此代码,接受此类参数以解决更多问题广泛的测验。

答案 1 :(得分:0)

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.
}`
相关问题