OSDN Git Service

e33630b09b9975923eaa84b22279dd3295caf197
[pettanr/clientJs.git] / 0.6.x / js / 07_audio / 01_XWebAudio.js
1 var X_Audio_constructor = 3.1 <= X_UA[ 'Safari' ] && X_UA[ 'Safari' ] < 4 ?
2                                                                 function( s, a ){
3                                                                         a = document.createElement( 'audio' );
4                                                                         a.src = s;
5                                                                         a.load();
6                                                                         return a;
7                                                                 } :
8                                                 // Android1.6 + MobileOpera12 HTMLAudio はいるが呼ぶとクラッシュする
9                                                   !( X_UA[ 'Android' ] < 2 ) ?
10                                                                 window[ 'Audio' ] || window.HTMLAudioElement : null,
11         
12         // Blink5 Opera32 Win8 は HTMLAudio が壊れている、WebAudio は mp3 がデコードに失敗、ogg が動作
13         X_Audio_blinkOperaFix = X_UA[ 'BlinkOpera' ] && X_UA[ 'Windows' ],
14
15         X_Audio_codecs;
16
17 if( X_Audio_constructor ){
18         //http://himaxoff.blog111.fc2.com/blog-entry-97.html
19         //引数なしで new Audio() とすると、Operaでエラーになるそうなので注意。
20         X_TEMP.rawAudio = new X_Audio_constructor( '' );
21         
22         // https://html5experts.jp/miyuki-baba/3766/
23         // TODO Chrome for Android31 で HE-AAC が低速再生されるバグ
24         // TODO Android4 標準ブラウザで ogg のシークが正しくない!
25         if( X_TEMP.rawAudio.canPlayType ){
26                 X_Audio_codecs = {
27                   'mp3'  : X_TEMP.rawAudio.canPlayType('audio/mpeg'),
28                   'opus' : X_TEMP.rawAudio.canPlayType('audio/ogg; codecs="opus"'),
29                   'ogg'  : X_TEMP.rawAudio.canPlayType('audio/ogg; codecs="vorbis"'),
30                   'wav'  : X_TEMP.rawAudio.canPlayType('audio/wav; codecs="1"'),
31                   'aac'  : X_TEMP.rawAudio.canPlayType('audio/aac'),
32                   'm4a'  : X_TEMP.rawAudio.canPlayType('audio/x-m4a') + X_TEMP.rawAudio.canPlayType('audio/m4a') + X_TEMP.rawAudio.canPlayType('audio/aac'),
33                   'mp4'  : X_TEMP.rawAudio.canPlayType('audio/x-mp4') + X_TEMP.rawAudio.canPlayType('audio/mp4') + X_TEMP.rawAudio.canPlayType('audio/aac'),
34                   'weba' : X_TEMP.rawAudio.canPlayType('audio/webm; codecs="vorbis"')
35                 };
36                 (function( X_Audio_codecs, k, v ){
37                         for( k in X_Audio_codecs ){
38                                 //if( X_EMPTY_OBJECT[ k ] ) continue;
39                                 v = X_Audio_codecs[ k ];
40                                 v = v && !!( v.split( 'no' ).join( '' ) );
41                                 if( v ){
42                                         console.log( k + ' ' + X_Audio_codecs[ k ] );
43                                         X_Audio_codecs[ k ] = true;
44                                 } else {
45                                         delete X_Audio_codecs[ k ];
46                                 };
47                         };
48                         if( X_Audio_blinkOperaFix ) delete X_Audio_codecs[ 'mp3' ];
49                 })( X_Audio_codecs );
50         } else {
51                 // iOS3.2.3
52                 X_Audio_codecs = {
53                   'mp3'  : X_UA[ 'IE' ] || X_UA[ 'Chrome' ] || ( X_UA[ 'Windows' ] && X_UA[ 'Safari' ]  ),
54                   'ogg'  : 5 <= X_UA[ 'Gecko' ] || X_UA[ 'Chrome' ] || X_UA[ 'Opera' ] ,
55                   'wav'  : X_UA[ 'Gecko' ] || X_UA[ 'Opera' ] || ( X_UA[ 'Windows' ] && X_UA[ 'Safari' ]  ),
56                   'aac'  : X_UA[ 'IE' ] || X_UA[ 'WebKit' ],
57                   'm4a'  : X_UA[ 'IE' ] || X_UA[ 'WebKit' ],
58                   'mp4'  : X_UA[ 'IE' ] || X_UA[ 'WebKit' ],
59                   'weba' : 2 <= X_UA[ 'Gecko' ] || 10.6 <= X_UA[ 'Opera' ] // firefox4+(Gecko2+)
60                 };
61                 (function( X_Audio_codecs, k ){
62                         for( k in X_Audio_codecs ){
63                                 //if( X_EMPTY_OBJECT[ k ] ) continue;
64                                 if( X_Audio_codecs[ k ] ){
65                                         console.log( k + ' ' + X_Audio_codecs[ k ] );
66                                         X_Audio_codecs[ k ] = true;
67                                 } else {
68                                         delete X_Audio_codecs[ k ];
69                                 };
70                         };
71                 })( X_Audio_codecs );
72         };
73         
74         if( X_Audio_blinkOperaFix ){
75                 X_Audio_constructor = null;
76                 delete X_TEMP.rawAudio;
77         };
78 };
79
80
81 var X_WebAudio_context      =   // 4s 以下ではない iPad 2G または iPad mini 1G 以下ではない, iPod touch 4G 以下ではない
82                                                                 !X_UA[ 'iPhone_4s' ]  && !X_UA[ 'iPad_2Mini1' ]  && !X_UA[ 'iPod_4' ]  &&
83                                                                 // Android2 + Gecko で WebAudio が極めて不安定
84                                                                 !( X_UA[ 'Fennec' ] && X_UA[ 'Android' ] < 3 ) &&
85                                                                 // Firefox40.0.5 + Windows8 で音声が途中から鳴らなくなる
86                                                                 // Firefox41.0.1 + Windows8 で音声が途中から鳴らなくなる
87                                                                 !( 40 <= X_UA[ 'Gecko' ] && X_UA[ 'Gecko' ] < 42 && X_UA[ 'Windows' ] ) &&
88                                                                 ( window[ 'AudioContext' ] || window[ 'webkitAudioContext' ] ),
89         X_WebAudio_BUFFER_LIST  = [],
90         X_WebAudio_need1stTouch = X_UA[ 'iOS' ],
91         X_WebAudio_touchState   = X_WebAudio_need1stTouch,
92         X_WebAudio,
93         X_WebAudio_BufferLoader,
94         X_WebAudio_fpsFix;
95
96 /*
97  * iPhone 4s 以下、iPad2以下、iPad mini 1以下, iPod touch 4G 以下は不可
98  */
99 if( X_WebAudio_context ){
100         
101         X_WebAudio_context = new X_WebAudio_context;
102         
103         X_WebAudio_BufferLoader = X_EventDispatcher[ 'inherits' ](
104                 'X.WebAudio.BufferLoader',
105                 X_Class.POOL_OBJECT,
106                 {
107                         audioUrl        : '',
108             xhr             : null,
109             onDecodeSuccess : null,
110             onDecodeError   : null,
111             
112             audioBuffer     : null,
113             errorState      : 0,
114             webAudioList    : null,
115             
116                         'Constructor' : function( webAudio, url ){
117                                 this.webAudioList = [ webAudio ];
118                                 this.audioUrl     = url;
119                                 this.xhr = X[ 'Net' ]( { 'xhr' : url, 'dataType' : 'arraybuffer' } )
120                                                                         [ 'listen' ]( X_EVENT_PROGRESS, this )
121                                                                         [ 'listenOnce' ]( [ X_EVENT_SUCCESS, X_EVENT_COMPLETE ], this );
122                                 X_WebAudio_BUFFER_LIST.push( this );
123                         },
124                         
125                         handleEvent : function( e ){
126                                 var i, l;
127                                 
128                                 switch( e.type ){
129                                         case X_EVENT_PROGRESS :
130                                                 for( i = 0, l = this.webAudioList.length; i < l; ++i ){
131                                                         this.webAudioList[ i ][ 'dispatch' ]( { type : X_EVENT_PROGRESS, 'percent' : e[ 'percent' ] } );
132                                                 };
133                                                 return;
134                                         
135                                         case X_EVENT_SUCCESS :
136                                         // TODO 旧api
137                                         // https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Porting_webkitAudioContext_code_to_standards_based_AudioContext
138                                         
139                                         // http://qiita.com/sou/items/5688d4e7d3a37b4e2ff1
140                                         // iOS 7.1 で decodeAudioData に処理が入った瞬間にスクリーンを長押しする(スクロールを繰り返す)と
141                                         // decoeAudioData の処理がキャンセルされることがある(エラーやコールバックの発火もなく、ただ処理が消滅する)。
142                                         // ただし iOS 8.1.2 では エラーになる
143                                                 if( X_UA[ 'iOS' ] < 8 || !X_WebAudio_context[ 'decodeAudioData' ] ){
144                                                         this._onDecodeSuccess( X_WebAudio_context[ 'createBuffer' ]( e.response, false ) );
145                                                 } else
146                                                 if( X_WebAudio_context[ 'decodeAudioData' ] ){
147                                                         X_WebAudio_context[ 'decodeAudioData' ]( e.response,
148                                                                 this.onDecodeSuccess = X_Closure_create( this, this._onDecodeSuccess ),
149                                                                 this.onDecodeError   = X_Closure_create( this, this._onDecodeError ) );
150                                                 };
151                                                 break;
152
153                                         case X_EVENT_COMPLETE :
154                                                 this.errorState = 1;                            
155                                                 this[ 'asyncDispatch' ]( X_EVENT_COMPLETE );
156                                                 break;
157                                 };
158                                 this.xhr[ 'unlisten' ]( [ X_EVENT_PROGRESS, X_EVENT_SUCCESS, X_EVENT_COMPLETE ], this );
159                                 delete this.xhr;
160                         },
161                         
162                                 _onDecodeSuccess : function( buffer ){
163                                         this.onDecodeSuccess && this._onDecodeComplete();
164                                         
165                         if ( !buffer ) {
166                                 this.errorState = 2;
167                             this[ 'asyncDispatch' ]( X_EVENT_COMPLETE );
168                             return;
169                         };
170                         
171                         console.log( 'WebAudio decode success!' );
172         
173                         this.audioBuffer = buffer;
174
175                                         this[ 'asyncDispatch' ]( X_EVENT_COMPLETE );
176
177                         console.log( 'WebAudio decoded!' );
178                                 },
179                                 
180                                 _onDecodeError : function(){
181                                         console.log( 'WebAudio decode error!' );
182                                         this._onDecodeComplete();
183                                         this.errorState = 2;
184                                         this[ 'asyncDispatch' ]( X_EVENT_COMPLETE );
185                                 },
186                                 
187                                 _onDecodeComplete : function(){
188                                         X_Closure_correct( this.onDecodeSuccess );
189                                         delete this.onDecodeSuccess;
190                                         X_Closure_correct( this.onDecodeError );
191                                         delete this.onDecodeError;
192                                 },
193                         
194                         unregister : function( webAudio ){
195                                 var list = this.webAudioList,
196                                         i    = list.indexOf( webAudio );
197                                 if( 0 < i ){
198                                         list.splice( i, 1 );
199                                         if( list.length ){
200                                                 this.xhr && this.xhr[ 'kill' ]();
201                                                 this[ 'kill' ]();
202                                         };
203                                 };
204                         }
205                         
206                 }
207         );
208         
209         
210         X_WebAudio = X_AudioBase[ 'inherits' ](
211                 'X.WebAudio',
212                 X_Class.POOL_OBJECT,
213                 {
214                         
215                         loader          : null,
216                                                 
217                         _startPos       : 0,
218                         _endPosition    : 0,
219                         _startTime      : 0,
220             _timerID        : 0,
221             _interval       : 0,
222                 audioBuffer     : null,
223                 bufferSource    : null,
224             gainNode        : null,
225             _onended        : null,
226             
227                         'Constructor' : function( disatcher, url, option ){                             
228                                 var i = 0,
229                                         l = X_WebAudio_BUFFER_LIST.length,
230                                         loader;
231
232                                 /*
233                                  * http://qiita.com/sou/items/5688d4e7d3a37b4e2ff1
234                                  * L-01F 等の一部端末で Web Audio API の再生結果に特定条件下でノイズが混ざることがある。
235                                  * 描画レート(描画 FPS)が下がるとノイズが混ざり始め、レートを上げると再生結果が正常になるというもので、オーディオ処理が描画スレッドに巻き込まれているような動作を見せる。
236                                  */
237                                 if( X_UA[ 'Android' ] && X_UA[ 'Chrome' ] && !X_WebAudio_fpsFix ){
238                                         X_Node_systemNode.create( 'div', { id : 'fps-slowdown-make-sound-noisy' } );
239                                         X_WebAudio_fpsFix = true;
240                                 };
241
242                                 for( ; i < l; ++i ){
243                                         loader = X_WebAudio_BUFFER_LIST[ i ];
244                                         if( loader.audioUrl === url ){
245                                                 this.loader = loader;
246                                                 loader.webAudioList.push( this );
247                                                 break;
248                                         };
249                                 };
250                                 
251                                 if( !this.loader ){
252                                         this.loader = loader = X_WebAudio_BufferLoader( this, url );
253                                 };
254                                 
255                                 this.disatcher = disatcher || this;
256                                 this.setState( option );
257                                 
258                                 this[ 'listenOnce' ]( X_EVENT_KILL_INSTANCE, this.onKill );
259                                 
260                                 if( loader.audioBuffer || loader.errorState ){
261                                         this._onLoadBufferComplete();
262                                 } else {
263                                         loader[ 'listenOnce' ]( X_EVENT_COMPLETE, this, this._onLoadBufferComplete );
264                                 };
265                         },
266                         
267                         onKill : function(){
268                                 this.loader[ 'unlisten' ]( X_EVENT_COMPLETE, this, this._onLoadBufferComplete )
269                                         .unregister( this );
270
271                                 delete this.audioBuffer;
272                                 
273                                 this.playing      && this.actualPause();
274                     this.bufferSource && this._sourceDispose();
275         
276                     this._onended     && X_Closure_correct( this._onended );    
277         
278                     this.gainNode     && this.gainNode.disconnect();
279                         },
280                                 _onLoadBufferComplete : function( e ){
281                                         var loader = this.loader,
282                                                 buffer = loader.audioBuffer;
283                                         
284                                         e && loader[ 'unlisten' ]( X_EVENT_COMPLETE, this, this._onLoadBufferComplete );
285                                         
286                         if ( !buffer ) {
287                                 this.error = loader.errorState;
288                                 
289                             this.disatcher[ 'dispatch' ]({
290                                                                 type    : X_EVENT_ERROR,
291                                                                 error   : loader.errorState,
292                                                                 message : loader.errorState === 1 ?
293                                                                                         'load buffer network error' :
294                                                                                         'buffer decode error'
295                                                         });
296                                                 this[ 'kill' ]();
297                             return;
298                         };
299         
300                         this.audioBuffer = buffer;
301                         this.duration    = buffer.duration * 1000;
302
303                                         this.disatcher[ 'asyncDispatch' ]( X_EVENT_READY );
304                         
305                         console.log( 'WebAudio buffer ready' );
306                                 },
307                         
308                         actualPlay : function(){
309                                 var e, begin, end;
310                                 
311                                 console.log( '[WebAudio] play abuf:' + !!this.audioBuffer );
312                                 
313                     if( !this.audioBuffer ){
314                         this._playReserved = true;
315                         return;
316                     };
317                                 
318                                 if( X_WebAudio_touchState ){
319                                         e = X_EventDispatcher_CURRENT_EVENTS[ X_EventDispatcher_CURRENT_EVENTS.length - 1 ];
320                                         if( !e || !e[ 'pointerType' ] ){
321                                                 // alert( 'タッチイベント以外での play! ' + ( e ? e.type : '' ) );
322                                                 return;
323                                         };
324                                 };
325                                 X_WebAudio_touchState = false;
326                                 
327                                 end   = X_Audio_getEndTime( this );
328                                 begin = X_Audio_getStartTime( this, end, true );
329                                 
330                                 console.log( '[WebAudio] play ' + begin + ' -> ' + end );
331                                 
332                                 if( this.bufferSource ) this._sourceDispose();
333                                 if( !this.gainNode ){
334                                         this.gainNode = X_WebAudio_context[ 'createGain' ] ? X_WebAudio_context[ 'createGain' ]() : X_WebAudio_context[ 'createGainNode' ]();
335                         this.gainNode[ 'connect' ]( X_WebAudio_context[ 'destination' ] );
336                                 };
337                     this.bufferSource        = X_WebAudio_context[ 'createBufferSource' ]();
338                     this.bufferSource.buffer = this.audioBuffer;
339                     this.bufferSource[ 'connect' ]( this.gainNode );
340                     
341                     this.gainNode[ 'gain' ].value = this.gain;
342                     
343                     // おかしい、stop 前に外していても呼ばれる、、、@Firefox33.1
344                     // 破棄された X.Callback が呼ばれて、obj.proxy() でエラーになる。Firefox では、onended は使わない
345                     // 多くのブラウザで onended は timer を使ったカウントより遅いので使わない
346                 //if( this.bufferSource.onended !== undefined ){
347                         //console.log( '> use onended' );
348                         //this.bufferSource.onended = this._onended || ( this._onended = X_Closure_create( this, this._onEnded ) );
349                 //} else {
350                         this._timerID && X_Timer_remove( this._timerID );
351                                         this._timerID = X_Timer_once( end - begin, this, this._onEnded );
352                 //};
353         
354                     if( this.bufferSource.start ){
355                         this.bufferSource.start( 0, begin / 1000, end / 1000 );
356                     } else {
357                         this.bufferSource[ 'noteGrainOn' ]( 0, begin / 1000, end / 1000 );
358                     };
359                     
360                     this.playing      = true;
361                     this._startPos    = begin;
362                     this._endPosition = end;
363                     this._startTime   = X_WebAudio_context.currentTime * 1000;
364                     this._interval    = this._interval || X_Timer_add( 1000, 0, this, this._onInterval );
365                         },
366                         
367                                 _sourceDispose : function(){
368                             this.bufferSource.disconnect();
369                             delete this.bufferSource.onended;
370                             delete this.bufferSource;
371                         },
372
373                                 _onInterval : function(){
374                                         if( !this.playing ){
375                                                 delete this._interval;
376                                                 return X_CALLBACK_UN_LISTEN;
377                                         };
378                                         this.disatcher[ 'dispatch' ]( X_EVENT_MEDIA_PLAYING );
379                                 },
380                                                 
381                                 _onEnded : function(){
382                                         var time;
383                                         delete this._timerID;
384                                         
385                             if( this.playing ){
386                                 time = X_WebAudio_context.currentTime * 1000 - this._startTime - this._endPosition + this._startPos | 0;
387                                 //console.log( '> onEnd ' + ( this.playing && ( X_WebAudio_context.currentTime * 1000 - this._startTime ) ) + ' < ' + ( this._endPosition - this._startPos ) );
388                                 if( this._onended ){
389                                         // Firefox 用の対策,,,
390                                         if( time < 0 ) return;
391                                 } else {
392                                         if( time < 0 ){
393                                                 //console.log( '> onEnd crt:' + ( X_WebAudio_context.currentTime * 1000 ) + ' startTime:' + this._startTime +
394                                                 //      ' from:' + this._startPos + ' to:' + this._endPosition );
395                                                 this._timerID = X_Timer_once( -time, this, this._onEnded );
396                                                 return;
397                                         };
398                                 };
399                                 
400                                 if( this.autoLoop ){
401                                         if( !( this.disatcher[ 'dispatch' ]( X_EVENT_MEDIA_BEFORE_LOOP ) & X_CALLBACK_PREVENT_DEFAULT ) ){
402                                                 this.looped = true;
403                                                 this.disatcher[ 'dispatch' ]( X_EVENT_MEDIA_LOOPED );
404                                                 this.actualPlay();
405                                         };
406                                 } else {
407                                         this.actualPause();
408                                         this.disatcher[ 'dispatch' ]( X_EVENT_MEDIA_ENDED );
409                                 };
410                             };
411                                 },
412                         
413                         actualPause : function(){
414                                 console.log( '[WebAudio] pause' );
415                                 
416                     this._timerID && X_Timer_remove( this._timerID );
417                                 delete this._timerID;
418                                 delete this.playing;
419
420                     if( this.bufferSource ){
421                         if( this.bufferSource.onended ) delete this.bufferSource.onended;
422                         
423                         this.bufferSource.stop ? 
424                                 this.bufferSource.stop( 0 ) : this.bufferSource[ 'noteOff' ]( 0 );
425                     };
426                         },
427                         
428                         getActualCurrentTime : function(){
429                                 return X_WebAudio_context.currentTime * 1000 - this._startTime + this._startPos | 0;
430                         },
431                         
432                         afterUpdateState : function( result ){
433                                 if( result & 2 || result & 1 ){ // seek
434                         this.actualPlay();
435                                 } else
436                                 if( result & 4 ){
437                        this.gainNode[ 'gain' ].value = this.gain;
438                                 };
439                         }
440
441                 }
442         );
443
444         X_Audio_BACKENDS.push(
445                 {
446                         backendID   : 1,
447                         
448                         backendName : 'WebAudio',
449
450                         canPlay     : X_Audio_codecs,
451
452                         detect      : function( proxy, source, ext ){
453                                 proxy[ 'asyncDispatch' ]( { type : X_EVENT_COMPLETE, canPlay : X_Audio_codecs[ ext ] } );
454                         },
455                         
456                         klass : X_WebAudio
457                 }
458         );
459 };