Last active
October 22, 2015 06:28
-
-
Save sang4lv/32e0fbd817410db5dea1 to your computer and use it in GitHub Desktop.
Play Audio on 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
<!DOCTYPE html> | |
<html> | |
<head></head> | |
<body> | |
<button id="btn" style="transform: scale(3); margin: 100px;">touch to play</button> | |
</body> | |
<script> | |
$el = document.querySelector('#btn'); | |
var myContext = new (window.AudioContext || window.webkitAudioContext)(); | |
var path = 'ended.mp3'; | |
var source, buffer; | |
//someone suggested the async property might be the problem, so I brought it out from the play function | |
var request = new XMLHttpRequest(); | |
request.open('GET', path, true); | |
request.responseType = 'arraybuffer'; | |
request.onload = function() { | |
myContext.decodeAudioData(request.response, function(buf) { | |
buffer = buf; | |
console.log(buffer); | |
}); | |
}; | |
request.send(); | |
function play(e) { | |
e.preventDefault(); | |
source = myContext.createBufferSource(); | |
gain = myContext.createGain(); //one question mentioned creating a gain might help, but it doesn't | |
source.buffer = buffer; | |
source.connect(gain); | |
gain.connect(myContext.destination); | |
if(source.noteOn) { | |
source.noteOn(0.01); //another answer suggested playing from 0.01 might help, but it doesn't | |
} else if(source.start) { | |
source.start(0.01); //another answer suggested playing from 0.01 might help, but it doesn't | |
} else if(source.play) { | |
source.play(); | |
} else { | |
console.error('no methods to start'); | |
} | |
} | |
$el.ontouchend = play; | |
$el.onclick = play; | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment