Created
September 9, 2017 17:25
-
-
Save castaneai/269077142224ad9a57ca0c837e9553c4 to your computer and use it in GitHub Desktop.
Audio crossfade example with Web Audio API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Crossfade Demo</title> | |
<style> | |
html, body { | |
margin: 0; | |
padding: 0; | |
width: 100%; | |
height: 100%; | |
} | |
.background { | |
width: 100%; | |
height: 100%; | |
position: relative; | |
} | |
.background > .artwork { | |
width: 100%; | |
height: 100%; | |
position: absolute; | |
top: 0; | |
left: 0; | |
background-repeat: no-repeat; | |
background-size: cover; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="background"> | |
<div class="artwork" id="artwork-1" style="background-image: url(1.jpg)"></div> | |
<div class="artwork" id="artwork-2" style="background-image: url(2.jpg)"></div> | |
<audio id="audio-1" src="1.m4a" preload="metadata"></audio> | |
<audio id="audio-2" src="2.m4a" preload="metadata"></audio> | |
</div> | |
<script> | |
window.onload = () => { | |
const audioCtx = new AudioContext(); | |
const art1Elem = document.getElementById("artwork-1"); | |
const art2Elem = document.getElementById("artwork-2"); | |
const audio1Elem = document.getElementById("audio-1"); | |
const audio2Elem = document.getElementById("audio-2"); | |
const src1= audioCtx.createMediaElementSource(audio1Elem); | |
const src2 = audioCtx.createMediaElementSource(audio2Elem); | |
const gain1 = audioCtx.createGain(); | |
const gain2 = audioCtx.createGain(); | |
src1.connect(gain1); | |
gain1.connect(audioCtx.destination); | |
src2.connect(gain2); | |
gain2.connect(audioCtx.destination); | |
document.onmousemove = (e) => { | |
var x = e.clientX / document.body.clientWidth; | |
var gainL = Math.cos(x * 0.5 * Math.PI); | |
var gainR = Math.cos((1.0 - x) * 0.5 * Math.PI); | |
gain1.gain.value = gainL; | |
gain2.gain.value = gainR; | |
art1Elem.style.opacity = gainL; | |
art2Elem.style.opacity = gainR; | |
console.log("[GAIN]L: %.2f R: %.2f", gainL, gainR); | |
} | |
// play!! | |
audio1Elem.play(); | |
audio2Elem.play(); | |
} | |
</script> | |
</body> | |
</html> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment