Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
1 contributor

Users who have contributed to this file

75 lines (61 sloc) 1.84 KB
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Basic Web Audio example</title>
<style>
input {
height: 1.5em;
}
</style>
</head>
<body>
<audio src="outfoxing.mp3"></audio>
<button class="paused">Play</button>
<br>
<input type="range" min="0" max="1" step="0.01" value="1" class="volume">
<script>
// Create an AudioContext (cross browser)
const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioCtx = new AudioContext();
// store references to our HTML elements
const audioElement = document.querySelector('audio');
const playBtn = document.querySelector('button');
const volumeSlider = document.querySelector('.volume');
// load the audio source into our audio graph
const audioSource = audioCtx.createMediaElementSource(audioElement);
// play/pause audio
playBtn.addEventListener('click', function() {
// check if context is in suspended state (autoplay policy)
if (audioCtx.state === 'suspended') {
audioCtx.resume();
}
// if track is stopped, play it
if (this.getAttribute('class') === 'paused') {
audioElement.play();
this.setAttribute('class', 'playing');
this.textContent = 'Pause'
// if track is playing, stop it
} else if (this.getAttribute('class') === 'playing') {
audioElement.pause();
this.setAttribute('class', 'paused');
this.textContent = 'Play';
}
});
// if track ends
audioElement.addEventListener('ended', function() {
playBtn.setAttribute('class', 'paused');
this.textContent = 'Play'
});
// volume
const gainNode = audioCtx.createGain();
volumeSlider.addEventListener('input', function() {
gainNode.gain.value = this.value;
});
// connect our graph
audioSource.connect(gainNode).connect(audioCtx.destination);
// Track credit: Outfoxing the Fox by Kevin MacLeod under Creative Commons
</script>
</body>
</html>
You can’t perform that action at this time.