Created
March 28, 2019 08:05
-
-
Save tomaadland/227216c8db89440bd778dc83f7b25538 to your computer and use it in GitHub Desktop.
Get Web Audio to work with ios safari
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
<script> | |
$(document).ready(function(){ | |
console.log("Lang: <%= I18n.locale %>"); | |
<% if I18n.locale.to_s == 'en' %> | |
let url = "https:<%= @sight.sound_guide_en.url %>;" | |
<% else %> | |
let url = "https:<%= @sight.sound_guide.url %>;" | |
<% end %> | |
let source; | |
window.AudioContext = window.AudioContext || window.webkitAudioContext; | |
let context; | |
$('.play-sound').on('click', function(e) { | |
e.preventDefault(); | |
$(this).find('.play').toggleClass('pause'); | |
if (context && context.state === 'running') { | |
stopTunes(); | |
//console.log("Stopping.."); | |
//console.log("Context ", context.state); | |
} else if(context && context.state === 'suspended') { | |
//console.log("Resume play"); | |
resumeTunes(); | |
} else { | |
//console.log("Start new"); | |
context = new AudioContext(); | |
var request = new XMLHttpRequest(); | |
request.open("GET", url, true); | |
request.responseType = "arraybuffer"; | |
request.onload = function() { | |
var Data = request.response; | |
process(Data, context); | |
}; | |
request.send(); | |
} | |
if (context) { | |
//console.log("STATE: ", context.state); | |
} | |
}) | |
function process(Data, context) { | |
source = context.createBufferSource(); // Create Sound Source | |
context.decodeAudioData(Data, function(buffer) { | |
source.buffer = buffer; | |
source.connect(context.destination); | |
source.start(context.currentTime); | |
}); | |
} | |
function stopTunes() { | |
context.suspend(); | |
} | |
function resumeTunes() { | |
context.resume(); | |
} | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment