根据正在播放的声音显示文字

时间:2017-04-27 18:41:01

标签: javascript html google-chrome

所以,我希望能够显示文字,告诉我按下按钮时播放的是什么声音,但我甚至不知道从哪里开始。

我的HTML是您按下的按钮

我的JavaScript会随机播放将要播放的声音

任何帮助将不胜感激

<a href="#" id="soundbutton" class="button button1"></a>
  <script type="text/javascript" src="meme.js"></script>
var sounds = ["Titanic.mp3",
"Legitness.mp3",
"Lying.mp3",
"Lebron.mp3",
"Yeahboy.mp3",
"Rocketlauncher.mp3",
"Billnye.mp3",
"Running.mp3",
"Donethis.mp3"
];
var sound;
function generateRandomNumber(max) {
  return Math.floor(Math.random() * max);
}
function playSound() {
  var x = generateRandomNumber(sounds.length - 1);
  var soundSrc = sounds[x];
  if (sound) {
      sound.pause();
  } else {
      sound = new Audio();
  }
  sound.src = soundSrc;
  sound.play();
}
document.getElementById('soundbutton').addEventListener('click', playSound);

2 个答案:

答案 0 :(得分:2)

soundSrc会告诉你正在播放的声音。在playSound()函数的示例中,我只是将显示状态的某个元素的.innerHTML设置为soundSrc

var sounds = [
    "Titanic.mp3",
    "Legitness.mp3",
    "Lying.mp3",
    "Lebron.mp3",
    "Yeahboy.mp3",
    "Rocketlauncher.mp3",
    "Billnye.mp3",
    "Running.mp3",
    "Donethis.mp3"
];

var sound;

function generateRandomNumber(max) {
    return Math.floor(Math.random() * max);
}

function playSound() {
    var x = generateRandomNumber(sounds.length - 1);
  
    var soundSrc = sounds[x];
  
    if (sound) {
        sound.pause();
    } else {
        sound = new Audio();
    }

    sound.src = soundSrc;
    sound.play();
  
    document.getElementById("song").innerHTML = "Now playing: " + soundSrc;
}

document.getElementById('soundbutton').addEventListener('click', playSound);
<a href="#" id="soundbutton" class="button button1">Play new song!</a>
<h1 id="song">Not playing anything yet!</h1>

答案 1 :(得分:0)

只需将div innerHTML设置为soundSrc

document.getElementById('result').innerHTML = soundSrc;

<div id='result'></div>