我想请求用户许可(例如 google meet 中的麦克风许可)来自动播放 rickroll 的音频文件。我希望在用户接受权限后播放javascript函数。
这是我的html代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Not a rickroll</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body onload="rick();">
<div class="everything">
<h1>Loading....</h1>
<audio id="rick" src="roll.mp3" autoplay preload="auto"></audio>
</div>
<script src="sound.js">
</script>
</body>
</html>
这是 JavaScript 代码:
var popupsound = document.getElementById("rick");
function rick() {
popupsound.play(); //play the audio file
// Change background to dancing rick
document.body.style.backgroundImage = "url('rick.gif')"
// Hide the heading and the button
document.querySelector(".everything").style.display = "none"
}
提前致谢!
这对我有用。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>permission microphone</title>
</head>
<body>
<h1>sound autistar</h1>
<script>
navigator.mediaDevices.getUserMedia({
audio: true,
}).then((stream) => {
// Reproducir audio
const audio = new Audio("alarm.mp3");
audio.play();
});
</script>
<audio autoplay>
<source src="alarm.mp3" type="audio/mpeg">
</audio>
</body>
</html>