Created
May 15, 2022 19:47
-
-
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 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
// 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