Попытка получить случайное изображение и воспроизведение случайного звука при нажатии кнопки - PullRequest
1 голос
/ 29 апреля 2020

Изображения удаляются случайным образом при нажатии кнопки, но звуки не воспроизводятся. Я не знаю, что не так со звуком JS, но он меня озадачил. Я хотел бы, чтобы оба выполнялись случайным образом при нажатии на одну и ту же кнопку. Я использую Chrome для проверки своей работы.

<script type = "text/javascript">
        //Create random picture array
            
        function imgchange() {

            var myImages1 = new Array();
            myImages1[1] = "Matthew1.jpg";
            myImages1[2] = "Matthew2.jpg";
            myImages1[3] = "Matthew3.jpg";
            myImages1[4] = "Matthew4.jpg"; //Image Array
            myImages1[5] = "Matthew5.jpg";
            myImages1[6] = "Matthew6.jpg";
            myImages1[7] = "Matthew7.jpg";
            var rnd = Math.floor(Math.random() * myImages1.length);// Random Choice of Image
            if (rnd == 0) {
                rnd = 1;
            }

            document.getElementById("gen-img").src = myImages1[rnd];//Gets Image
       
        }      
        function playRandomSound() {

            //An array to house all of the URLs of your sounds
            var sounds = new Audio["sound1.mp3", "sound2.mp3", "sound3.mp3", "sound4.mp3"];

            //This line will select a random sound to play out of your provided URLS
            var soundFile = sounds[Math.floor(Math.random() * sounds.length)];

            //Find the player element that you created and generate an embed file to play the sound within it
            document.getElementById("Button").innerHTML = "<embed src=\"" + soundfile + "\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";

    </script>
image

1 Ответ

0 голосов
/ 29 апреля 2020

Вам нужно будет создать массив звуков, например:

var sounds = ["sound1.mp3", "sound2.mp3", "sound3.mp3", "sound4.mp3"].map(
  (sound) => new Audio(sound)
);

У вас также есть опечатка в строке, начинающаяся с document.getElementById("Button").innerHTML, soundFile имеет заглавную букву F. Хотя я не думаю, что вам нужна эта строка, вы можете воспроизвести звук, позвонив по ней play(), например soundFile.play(), пожалуйста, проверьте фрагмент ниже:

//Create random picture array

function imgchange() {
  var myImages1 = new Array();
  myImages1[1] = "Matthew1.jpg";
  myImages1[2] = "Matthew2.jpg";
  myImages1[3] = "Matthew3.jpg";
  myImages1[4] = "Matthew4.jpg"; //Image Array
  myImages1[5] = "Matthew5.jpg";
  myImages1[6] = "Matthew6.jpg";
  myImages1[7] = "Matthew7.jpg";
  var rnd = Math.floor(Math.random() * myImages1.length); // Random Choice of Image
  if (rnd == 0) {
    rnd = 1;
  }

  document.getElementById("gen-img").src = myImages1[rnd]; //Gets Image
}

function playRandomSound() {

  //An array to house all of the URLs of your sounds
  var sounds = [
    new Audio(
      "https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3"
    ),
  ];

  // var sounds = new Audio([
  //   ("sound1.mp3", "sound2.mp3", "sound3.mp3", "sound4.mp3")
  // ]();

  //This line will select a random sound to play out of your provided URLS
  var soundFile = sounds[Math.floor(Math.random() * sounds.length)];
  soundFile.play()

  //Find the player element that you created and generate an embed file to play the sound within it
  document.getElementById("Button").innerHTML =
    '<embed src="' +
    soundFile +
    '" hidden="true" autostart="true" loop="false" />';
}
image
...