|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +define(function () { |
| 4 | + // Create the Audio Context |
| 5 | + var audiocontext = new window.AudioContext(); |
| 6 | + |
| 7 | + /** |
| 8 | + * <p>Returns the Audio Context for this sketch. Useful for users |
| 9 | + * who would like to dig deeper into the <a target='_blank' href= |
| 10 | + * 'http://webaudio.github.io/web-audio-api/'>Web Audio API |
| 11 | + * </a>.</p> |
| 12 | + * |
| 13 | + * <p>Some browsers require users to startAudioContext |
| 14 | + * with a user gesture, such as touchStarted in the example below.</p> |
| 15 | + * |
| 16 | + * @method getAudioContext |
| 17 | + * @return {Object} AudioContext for this sketch |
| 18 | + * @example |
| 19 | + * <div><code> |
| 20 | + * function draw() { |
| 21 | + * background(255); |
| 22 | + * textAlign(CENTER); |
| 23 | + * |
| 24 | + * if (getAudioContext().state !== 'running') { |
| 25 | + * text('click to start audio', width/2, height/2); |
| 26 | + * } else { |
| 27 | + * text('audio is enabled', width/2, height/2); |
| 28 | + * } |
| 29 | + * } |
| 30 | + * |
| 31 | + * function touchStarted() { |
| 32 | + * if (getAudioContext().state !== 'running') { |
| 33 | + * getAudioContext().resume(); |
| 34 | + * } |
| 35 | + * var synth = new p5.MonoSynth(); |
| 36 | + * synth.play('A4', 0.5, 0, 0.2); |
| 37 | + * } |
| 38 | + * |
| 39 | + * </div></code> |
| 40 | + */ |
| 41 | + p5.prototype.getAudioContext = function() { |
| 42 | + return audiocontext; |
| 43 | + }; |
| 44 | + |
| 45 | + // if it is iOS, we have to have a user interaction to start Web Audio |
| 46 | + // http://paulbakaus.com/tutorials/html5/web-audio-on-ios/ |
| 47 | + var iOS = navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false ; |
| 48 | + if (iOS) { |
| 49 | + var iosStarted = false; |
| 50 | + var startIOS = function() { |
| 51 | + if (iosStarted) return; |
| 52 | + |
| 53 | + // create empty buffer |
| 54 | + var buffer = audiocontext.createBuffer(1, 1, 22050); |
| 55 | + var source = audiocontext.createBufferSource(); |
| 56 | + source.buffer = buffer; |
| 57 | + |
| 58 | + // connect to output (your speakers) |
| 59 | + source.connect(audiocontext.destination); |
| 60 | + // play the file |
| 61 | + source.start(0); |
| 62 | + console.log('start ios!'); |
| 63 | + |
| 64 | + if (audiocontext.state === 'running') { |
| 65 | + iosStarted = true; |
| 66 | + } |
| 67 | + }; |
| 68 | + document.addEventListener('touchend', startIOS, false); |
| 69 | + document.addEventListener('touchstart', startIOS, false); |
| 70 | + |
| 71 | + // TO DO: fake touch event so that audio will just start |
| 72 | + } |
| 73 | + |
| 74 | + return audiocontext; |
| 75 | +}); |
0 commit comments