如何在JavaScript图片测验中为每个问题添加可播放音频
解决图片测验中音频播放按钮的问题
当前代码中直接将audio字段的文本值(如audio1)插入页面,只会显示纯文本,无法实现播放功能。需要通过动态生成HTML音频元素/播放按钮,结合sounds对象中的音频路径来实现可点击播放的功能。
核心修改步骤
- 替换音频显示逻辑:在
populate函数中,不再直接赋值音频key,而是根据key从sounds对象获取音频路径,生成可交互的播放控件。 - 处理音频播放状态:切换问题时重置音频容器,避免重复生成控件或多音频同时播放。
修改后的关键代码(JavaScript部分)
function populate() { if (quiz.isEnded()) { showScores(); } else { // show question var element = document.getElementById("question"); element.innerHTML = quiz.getQuestionIndex().text; // --- 修改这里的音频显示逻辑 --- var audioContainer = document.getElementById("audio"); audioContainer.innerHTML = ''; // 清空容器,避免重复控件 var audioKey = quiz.getQuestionIndex().audio; var audioPath = sounds[audioKey]; // 方案1:使用浏览器原生音频控件(自带播放/暂停按钮) audioContainer.innerHTML = `<audio src="${audioPath}" controls style="margin-top:10px; padding:5px;"></audio>`; // 方案2:自定义播放按钮(更灵活的样式控制) /* var playBtn = document.createElement('button'); playBtn.textContent = '🔊 播放音频'; playBtn.style.cssText = 'padding:8px 16px; background:#ffc107; color:white; border:none; border-radius:4px; cursor:pointer; margin-top:10px;'; var audio = new Audio(audioPath); playBtn.onclick = function() { // 暂停所有正在播放的音频 document.querySelectorAll('audio').forEach(a => a.pause()); audio.play(); }; audioContainer.appendChild(playBtn); */ // show options var choices = quiz.getQuestionIndex().choices; for (var i = 0; i < choices.length; i++) { var element = document.getElementById("choice" + i); element.innerHTML = images[choices[i]]? '<img src="'+images[choices[i]]+'"/>':choices[i]; guess("btn" + i, choices[i]); } showProgress(); } };
为什么之前的方法无效?
- 直接将
audio1这类字符串插入页面,只是纯文本,不是有效的HTML媒体元素。 - 若尝试在
questions数组中直接嵌入HTML字符串,会导致音频路径硬编码,无法利用sounds对象统一管理资源,维护性差。
完整修改后的JavaScript代码
var images = { "dog": "dog.jpg", "cow": "cow.jpg", "cat": "cat.jpg", "goat": "goat.jpg", "deer": "deer.jpg", "hen": "hen.jpg", "lion": "lion.jpg", "parrot": "parrot.jpg", "tiger": "tiger.jpg" } var sounds = { "audio1" : "grizz.mp3", "audio2" : "immortal.mp3", "audio3" : "genshoshi.mp3", "audio4" : "genshoshi.mp3", "audio5" : "immortal.mp3" } function populate() { if (quiz.isEnded()) { showScores(); } else { // show question var element = document.getElementById("question"); element.innerHTML = quiz.getQuestionIndex().text; // 修改后的音频处理逻辑 var audioContainer = document.getElementById("audio"); audioContainer.innerHTML = ''; var audioKey = quiz.getQuestionIndex().audio; var audioPath = sounds[audioKey]; // 使用原生控件 audioContainer.innerHTML = `<audio src="${audioPath}" controls style="margin-top:10px;"></audio>`; // show options var choices = quiz.getQuestionIndex().choices; for (var i = 0; i < choices.length; i++) { var element = document.getElementById("choice" + i); element.innerHTML = images[choices[i]]? '<img src="'+images[choices[i]]+'"/>':choices[i]; guess("btn" + i, choices[i]); } showProgress(); } }; function guess(id, guess) { var button = document.getElementById(id); button.onclick = function() { quiz.guess(guess); populate(); } }; function showProgress() { var currentQuestionNumber = quiz.questionIndex + 1; var element = document.getElementById("progress"); element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length; }; function showScores() { var gameOverHTML = "<h1>Result</h1>"; gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>"; var element = document.getElementById("quiz"); element.innerHTML = gameOverHTML; }; // create questions var questions = [ new Question(["Which one is dog?"],"audio1",["cow", "goat", "cat", "dog"], "dog"), new Question(["select tiger below"],"audio2",["parrot", "deer", "tiger", "lion"], "tiger"), new Question(["choose parrot pls?"],"audio3",["hen", "parrot", "goat", "dog"], "parrot"), new Question(["Find cat below?"],"audio4",["parrot", "goat", "cat", "tiger"], "cat"), new Question(["choose lion pls?"],"audio5",["lion", "goat", "tiger", "dog"], "lion") ]; questions.sort(function(){ return 0.5 - Math.random(); }); function Question(text, audio , choices, answer) { this.text = text; this.audio = audio; this.choices = choices; this.answer = answer; } Question.prototype.isCorrectAnswer = function(choice) { return this.answer === choice; } function Quiz(questions) { this.score = 0; this.questions = questions; this.questionIndex = 0; } Quiz.prototype.getQuestionIndex = function() { return this.questions[this.questionIndex]; } Quiz.prototype.guess = function(answer) { if (this.getQuestionIndex().isCorrectAnswer(answer)) { this.score++; } this.questionIndex++; } Quiz.prototype.isEnded = function() { return this.questionIndex === this.questions.length; } // create quiz var quiz = new Quiz(questions); // display quiz populate();
内容的提问来源于stack exchange,提问作者Amongus
相关产品推荐
相关产品推荐

