Skip to content

Instantly share code, notes, and snippets.

@anthumchris
Created November 14, 2020 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthumchris/ee5355fcdecb9fd93e3d07227a2880a0 to your computer and use it in GitHub Desktop.
Save anthumchris/ee5355fcdecb9fd93e3d07227a2880a0 to your computer and use it in GitHub Desktop.
toggle oscillator playback
<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>
@anthumchris
Copy link
Author

@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

@rodolfocangiotti
Copy link

rodolfocangiotti commented Nov 16, 2020

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