写了这样一个剧本。
假设当您单击 voice-btn 按钮时,根据其 id,应随机播放 3 种声音之一。但是有些东西不起作用,告诉我我在哪里做错了?
//Deer sounds
let deer1 = new Audio('sounds/deer1.mp3');
let deer2 = new Audio('sounds/deer2.mp3');
let deer3 = new Audio('sounds/deer3.mp3');
//Fox sounds
let fox1 = new Audio('sounds/fox1.mp3');
let fox2 = new Audio('sounds/fox2.mp3');
let fox3 = new Audio('sounds/fox3.mp3');
//Voice random selection
function randomVoice() {
let rand = 1 + Math.random() * (4 - 1);
return Math.floor(rand);
}
//playingNow - воспроизводится ли звук
let playingNow = false;
//При нажатии на кнопку воспроизведения звука
//Определяем на какую именно кнопу нажали (currentAnimal)
//Рандомно выбираем номер звука 1-3 (voiceNumber)
$('.voice-btn').click(function () {
let currentAnimal = $(this).attr('id');
let voiceNumber = randomVoice();
if (!playingNow){
switch (voiceNumber) {
case 1:
playVoice(currentAnimal + '1');
break;
case 2:
playVoice(currentAnimal + '2');
break;
case 3:
playVoice(currentAnimal + '3');
break;
}
playingNow = true;
}
//Воспроизводит выбранный выше звук
function playVoice(voice) {
voice.play();
}
//Если один из звуков завершился
//разрешаем воспроизводить другой
(currentAnimal + '1').onended = function() {
playingNow = false
};
(currentAnimal + '2').onended = function() {
playingNow = false
};
(currentAnimal + '3').onended = function() {
playingNow = false
};
});
.voice-btn{
background: #000;
color: #fff;
padding: 20px;
margin: 5px 0
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="voice-btn" id="deer">Олень</div>
<div class="voice-btn" id="fox">Лиса</div>
你在这里得到这条线
该行已添加到其中
然后在这里你试图在这一行调用 play() 方法
当然字符串 (voice="deer1") 没有这样的方法
据我了解,您假设您的字符串(例如“deer1”)将“变成”变量名,并且将在该变量上调用 play() 方法。理论上,这是可以做到的,就像这里https://stackoverflow.com/questions/5613834/convert-string-to-variable-name-in-javascript
但是在您的情况下,最好将音频对象从普通变量转换为某种数据结构,例如
1) 对象数组
像这样收到
2)或成一个对象
像这样收到