Created
November 14, 2020 16:43
-
-
Save anthumchris/ee5355fcdecb9fd93e3d07227a2880a0 to your computer and use it in GitHub Desktop.
toggle oscillator playback
This file contains 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
<html> | |
<head> | |
<style>body { padding: 4rem; text-align: center; }</style> | |
<script> | |
/* Parentheses may be needed to instantiate: `audioCtx = new (OBJECT)()`<br /> | |
* Oscillator waveform may need explicit definition: `osc.type = 'sine'` | |
*/ | |
var audioCtx = null | |
var isPlaying = false | |
document.addEventListener('click', togglePlay) | |
function togglePlay() { | |
if (!audioCtx) | |
initAudio() | |
if (isPlaying) { | |
audioCtx.suspend() | |
} else { | |
audioCtx.resume() | |
} | |
isPlaying = !isPlaying | |
} | |
function initAudio() { | |
audioCtx = new (window.AudioContext || window.webkitAudioContext)() | |
audioCtx.suspend() | |
const osc = audioCtx.createOscillator() | |
osc.connect(audioCtx.destination) | |
osc.type = 'sine' | |
osc.frequency.value = 500 | |
osc.start() | |
} | |
</script> | |
</head> | |
<body>tap/click anywhere to toggle playback</body> | |
</html> |
Hey @anthumchris, thank you for your suggestion. Actually, I removed the question on StackOverflow because I realised that the issue was simply due to the active silent mode (some applications like YouTube, etc. output audio audio also in silent mode but it seems that browsers do not).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@rodolfocangiotti I was about to answer your StackOverflow question but you deleted it before I could click "submit". Hope this helps!
https://jsbin.com/guyocel/edit?html,output