Last active
April 6, 2020 01:43
-
-
Save aarongeorge/5249e062ad4bac1204c009185e4793bf to your computer and use it in GitHub Desktop.
A function that will create an audio context that bypasses the iOS sample rate mismatch bug
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
/** | |
* A function that will create an audio context that fixes | |
* the iOS sample rate mismatch bug | |
* | |
* Author: Aaron George https://github.com/aarongeorge | |
*/ | |
// Create Audio Context | |
const createAudioContext = (desiredSampleRate = 44100) => { | |
// Deal with browser prefixes | |
const AudioContext = window.AudioContext || window.webkitAudioContext | |
// Create new audio context | |
let audioContext = new AudioContext() | |
// Regular expression that matches iOS devices | |
const iOSRegex = new RegExp('iPhone|iPad|iPod', 'i') | |
// Warm a `context` | |
const warmContext = (context, sampleRate) => { | |
// Create buffer and warmer source | |
const buffer = context.createBuffer(1, 1, sampleRate) | |
const warmer = context.createBufferSource() | |
// Set `warmer.buffer` to `buffer` | |
warmer.buffer = buffer | |
// Connect `warmer` | |
warmer.connect(context.destination) | |
// Play `warmer` | |
if (warmer.start) warmer.start(0) | |
else if (warmer.noteOn) warmer.noteOn(0) | |
// Disconnect `warmer` | |
warmer.disconnect() | |
} | |
/** | |
* There is a bug with iOS 6+ where you will get an incorrect sample rate | |
* which causes distortion. The below checks for that and fixes it for you | |
* by creating an audio context, destroying it, then creating a new one | |
*/ | |
// Check if iOS | |
if (iOSRegex.test(navigator.userAgent) && !window.MSStream) { | |
// Warm the context | |
warmContext(audioContext, desiredSampleRate) | |
// `sampleRate` does not match `desiredSampleRate` | |
if (audioContext.sampleRate !== desiredSampleRate) { | |
// Close `audioContext` | |
audioContext.close() | |
// Create new `AudioContext` | |
audioContext = new AudioContext() | |
// Warm the new context | |
warmContext(audioContext, desiredSampleRate) | |
} | |
} | |
// Return `audioContext` | |
return audioContext | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment