Herzlich willkommen zum SELF-Treffen 2026
vom 24.04. – 26.04.2026
in Halle (Saale)
Beispiel:Web-Audio-06.html
Aus SELFHTML-Wiki
<!DOCTYPE html> <html lang="de"> <head>
<meta charset="UTF-8"> <title>Web Audio API – Beispiel</title>
</head> <body>
<button id="playBtn">Abspielen</button>
<script>
document.addEventListener('DOMContentLoaded', function () {
let audioContext = null;
let audioBuffer = null;
// AudioContext nur einmalig erzeugen – Browser erlauben ihn erst
// nach einer Nutzerinteraktion (z. B. einem Klick)
function getAudioContext() {
if (!audioContext) {
audioContext = new AudioContext();
}
return audioContext;
}
async function loadAudio() {
if (audioBuffer) return audioBuffer; // bereits geladen, nichts tun
const audioCtx = getAudioContext();
const response = await fetch("/images/3/36/Hi.mp3"); // Datei-URL im Wiki verwenden
const arrayBuffer = await response.arrayBuffer();
audioBuffer = await audioCtx.decodeAudioData(arrayBuffer);
return audioBuffer;
}
async function playHi() {
try {
const audioCtx = getAudioContext();
if (!audioBuffer) await loadAudio();
if (audioCtx.state === "suspended") await audioCtx.resume();
// Für jede Wiedergabe muss eine neue BufferSourceNode erzeugt werden –
// eine Node kann nur einmal abgespielt werden.
const source = audioCtx.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioCtx.destination);
source.start();
} catch (err) {
console.error("Fehler beim Abspielen:", err);
}
}
document.getElementById("playBtn").addEventListener("click", playHi);
}); // DOMContentLoaded
</script>
</body> </html>