Skip to content

Instantly share code, notes, and snippets.

@idlebit1
Created May 15, 2022 19:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save idlebit1/c5828bb7ec0006c7aeb92fdc93c7bb0b to your computer and use it in GitHub Desktop.
Save idlebit1/c5828bb7ec0006c7aeb92fdc93c7bb0b to your computer and use it in GitHub Desktop.
How to make web audio / tone.js play while iphone is muted.
// This gist copyright IdleBit 2022, MIT License
var isIOS = /iPad|iPhone|iPod/.test(navigator.platform) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)
var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || isIOS
var isFirefox = /Firefox/i.test(navigator.userAgent)
// call this from first click action
function startSound() {
if (isIOS) {
try{
// Adapted from https://github.com/swevans/unmute (MIT 2020)
const silentAudioFile = createSilentAudioFile(44100)
createHtmlAudio(silentAudioFile);
}catch(e){
console.log(e)
}
}
// start your web audio or tone.js sounds here.
...
}
function createSilentAudioFile (sampleRate) {
const arrayBuffer = new ArrayBuffer(10)
const dataView = new DataView(arrayBuffer)
dataView.setUint32(0, sampleRate, true)
dataView.setUint32(4, sampleRate, true)
dataView.setUint16(8, 1, true)
const missingCharacters =
window.btoa(String.fromCharCode(...new Uint8Array(arrayBuffer)))
.slice(0, 13)
return `data:audio/wav;base64,UklGRisAAABXQVZFZm10IBAAAAABAAEA${missingCharacters}AgAZGF0YQcAAACAgICAgICAAAA=`
}
function createHtmlAudio(silentAudioFile) {
audio = document.createElement('audio')
audio.setAttribute('x-webkit-airplay', 'deny')
audio.preload = 'auto'
audio.loop = true
audio.src = silentAudioFile
audio.load()
audio.play().then(
() => {
audio.pause()
audio.removeAttribute('src')
audio.load()
audio = null
},
() => {
audio.pause()
audio.removeAttribute('src')
audio.load()
audio = null
}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment