Skip to content

Instantly share code, notes, and snippets.

@tomaadland
Created March 28, 2019 08:05
Show Gist options
  • Save tomaadland/227216c8db89440bd778dc83f7b25538 to your computer and use it in GitHub Desktop.
Save tomaadland/227216c8db89440bd778dc83f7b25538 to your computer and use it in GitHub Desktop.
Get Web Audio to work with ios safari
<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