英文:
HTML audio playing issues when specific key is pressed
问题
I'm trying to make this audio play when a specific key is pressed and will continue to loop. Any ideas on how to make this work?
document.addEventListener("keypress", function(event) {
if (event.keyCode == 13) {
<audio controls loop>
<source src="Chiptronical.ogg" type="audio/ogg">
</audio>
}
});
I wanted it to play the audio when the key is pressed, but it just doesn't work.
英文:
Im trying to make this audio play when a specific key is pressed and will continue to loop. Any ideas on how to make this work?
document.addEventListener("keypress", function(event) {
if (event.keyCode == 13) {
<audio controls loop>
<source src="Chiptronical.ogg" type="audio/ogg">
</audio>
}
});
i wanted it to play the audio when the key is pressed but it just doesnt work
答案1
得分: 0
以下是您提供的HTML代码的翻译部分:
尝试在浏览器上运行这个代码,并按回车键。
确保目录与音频文件相同。
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
$(document).ready(function(){
document.addEventListener("keypress", function(event) {
if (event.keyCode == 13) {
$('body').append( '<audio controls autoplay>' +
'<source src="Chiptronical.ogg" type="audio/ogg">' +
'<source src="Chiptronical.mp3" type="audio/mpeg">' +
'Your browser does not support the audio element.' +
'</audio>' );
}
});
});
</script>
</head>
<body>
<h1>音频自动播放属性</h1>
<p>按回车键播放声音:</p>
</body>
</html>
请注意,这是您提供的HTML代码的翻译部分,其中包含HTML标记和JavaScript代码。
英文:
try this and run on browser. and press enter.
make sure directory is same with audio file
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
$(document).ready(function(){
document.addEventListener("keypress", function(event) {
if (event.keyCode == 13) {
$('body').append( `<audio controls autoplay>
<source src="Chiptronical.ogg" type="audio/ogg">
<source src="Chiptronical.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>` );
}
});
});
</script>
</head>
<body>
<h1>The audio autoplay attribute</h1>
<p>Press Enter to play a sound:</p>
</body>
</html>
答案2
得分: 0
以下是翻译好的部分:
你可以像这样实现所需的结果:-
这是HTML代码:-
<audio id="audioElement" controls loop>
<source src="Chiptronical.ogg" type="audio/ogg">
</audio>
这是JavaScript代码:-
const audioElement = document.querySelector('#audioElement');
document.addEventListener("keypress", function(event) {
if (event.keyCode == 13) {
// 播放
audioElement.play();
// 暂停
audioElement.pause();
}
});
英文:
You can achieve the desired results like this:-
Here is the html:-
<audio id="audioElement" controls loop>
<source src="Chiptronical.ogg" type="audio/ogg">
</audio>
Here is the JavaScript:-
const audioElement = document.querySelector('#audioElement');
document.addEventListener("keypress", function(event) {
if (event.keyCode == 13) {
// For Play
audioElement.play();
// For Pause
audioElement.pause();
}
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论