OSDN Git Service

Version 0.6.185, fix X.AudioSprite & X_Node_onKill.
[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                                                                 // AOSP でも WebAudio を不完全に実装するものがある
86                                                                 !X_UA[ 'AOSP' ] && !( X_UA[ 'ChromeWV' ] < 5 ) &&
87                                                                 !X_UA[ 'Blink' ] &&
88                                                                 // Firefox40.0.5 + Windows8 で音声が途中から鳴らなくなる
89                                                                 // Firefox41.0.1 + Windows8 で音声が途中から鳴らなくなる
90                                                                 !( 40 <= X_UA[ 'Gecko' ] && X_UA[ 'Gecko' ] < 42 && X_UA[ 'Windows' ] ) &&
91                                                                 ( window[ 'AudioContext' ] || window[ 'webkitAudioContext' ] ),
92         X_WebAudio_BUFFER_LIST  = [],
93         X_WebAudio_need1stTouch = X_UA[ 'iOS' ],
94         X_WebAudio_touchState   = X_WebAudio_need1stTouch,
95         X_WebAudio,
96         X_WebAudio_BufferLoader,
97         X_WebAudio_fpsFix;
98
99 /*
100  * iPhone 4s 以下、iPad2以下、iPad mini 1以下, iPod touch 4G 以下は不可
101  */
102 if( X_WebAudio_context ){
103         
104         X_WebAudio_context = new X_WebAudio_context;
105         
106         X_WebAudio_BufferLoader = X_EventDispatcher[ 'inherits' ](
107                 'X.WebAudio.BufferLoader',
108                 X_Class.POOL_OBJECT,
109                 {
110                         audioUrl        : '',
111             xhr             : null,
112             onDecodeSuccess : null,
113             onDecodeError   : null,
114             
115             audioBuffer     : null,
116             errorState      : 0,
117             webAudioList    : null,
118             
119                         'Constructor' : function( webAudio, url ){
120                                 this.webAudioList = [ webAudio ];
121                                 this.audioUrl     = url;
122                                 this.xhr = X[ 'Net' ]( { 'xhr' : url, 'dataType' : 'arraybuffer' } )
123                                                                         [ 'listen' ]( X_EVENT_PROGRESS, this )
124                                                                         [ 'listenOnce' ]( [ X_EVENT_SUCCESS, X_EVENT_COMPLETE ], this );
125                                 X_WebAudio_BUFFER_LIST.push( this );
126                         },
127                         
128                         handleEvent : function( e ){
129                                 var i, l;
130                                 
131                                 switch( e.type ){
132                                         case X_EVENT_PROGRESS :
133                                                 for( i = 0, l = this.webAudioList.length; i < l; ++i ){
134                                                         this.webAudioList[ i ][ 'dispatch' ]( { type : X_EVENT_PROGRESS, 'percent' : e[ 'percent' ] } );
135                                                 };
136                                                 return;
137                                         
138                                         case X_EVENT_SUCCESS :
139                                         // TODO 旧api
140                                         // https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Porting_webkitAudioContext_code_to_standards_based_AudioContext
141                                         
142                                         // http://qiita.com/sou/items/5688d4e7d3a37b4e2ff1
143                                         // iOS 7.1 で decodeAudioData に処理が入った瞬間にスクリーンを長押しする(スクロールを繰り返す)と
144                                         // decoeAudioData の処理がキャンセルされることがある(エラーやコールバックの発火もなく、ただ処理が消滅する)。
145                                         // ただし iOS 8.1.2 では エラーになる
146                                                 if( X_UA[ 'iOS' ] < 8 || !X_WebAudio_context[ 'decodeAudioData' ] ){
147                                                         this._onDecodeSuccess( X_WebAudio_context[ 'createBuffer' ]( e.response, false ) );
148                                                 } else
149                                                 if( X_WebAudio_context[ 'decodeAudioData' ] ){
150                                                         X_WebAudio_context[ 'decodeAudioData' ]( e.response,
151                                                                 this.onDecodeSuccess = X_Closure_create( this, this._onDecodeSuccess ),
152                                                                 this.onDecodeError   = X_Closure_create( this, this._onDecodeError ) );
153                                                 };
154                                                 break;
155
156                                         case X_EVENT_COMPLETE :
157                                                 this.errorState = 1;                            
158                                                 this[ 'asyncDispatch' ]( X_EVENT_COMPLETE );
159                                                 break;
160                                 };
161                                 this.xhr[ 'unlisten' ]( [ X_EVENT_PROGRESS, X_EVENT_SUCCESS, X_EVENT_COMPLETE ], this );
162                                 delete this.xhr;
163                         },
164                         
165                                 _onDecodeSuccess : function( buffer ){
166                                         this.onDecodeSuccess && this._onDecodeComplete();
167                                         
168                         if ( !buffer ) {
169                                 this.errorState = 2;
170                             this[ 'asyncDispatch' ]( X_EVENT_COMPLETE );
171                             return;
172                         };
173                         
174                         console.log( 'WebAudio decode success!' );
175         
176                         this.audioBuffer = buffer;
177
178                                         this[ 'asyncDispatch' ]( X_EVENT_COMPLETE );
179
180                         console.log( 'WebAudio decoded!' );
181                                 },
182                                 
183                                 _onDecodeError : function(){
184                                         console.log( 'WebAudio decode error!' );
185                                         this._onDecodeComplete();
186                                         this.errorState = 2;
187                                         this[ 'asyncDispatch' ]( X_EVENT_COMPLETE );
188                                 },
189                                 
190                                 _onDecodeComplete : function(){
191                                         X_Closure_correct( this.onDecodeSuccess );
192                                         delete this.onDecodeSuccess;
193                                         X_Closure_correct( this.onDecodeError );
194                                         delete this.onDecodeError;
195                                 },
196                         
197                         unregister : function( webAudio ){
198                                 var list = this.webAudioList,
199                                         i    = list.indexOf( webAudio );
200                                 if( 0 < i ){
201                                         list.splice( i, 1 );
202                                         if( !list.length ){
203                                                 this.xhr && this.xhr[ 'kill' ]();
204                                                 this[ 'kill' ]();
205                                         };
206                                 };
207                         }
208                         
209                 }
210         );
211         
212         
213         X_WebAudio = X_AudioBase[ 'inherits' ](
214                 'X.WebAudio',
215                 X_Class.POOL_OBJECT,
216                 {
217                         
218                         loader          : null,
219                                                 
220                         _startPos       : 0,
221                         _endPosition    : 0,
222                         _startTime      : 0,
223             _timerID        : 0,
224             _interval       : 0,
225                 audioBuffer     : null,
226                 bufferSource    : null,
227             gainNode        : null,
228             _onended        : null,
229             
230                         'Constructor' : function( disatcher, url, option ){                             
231                                 var i = 0,
232                                         l = X_WebAudio_BUFFER_LIST.length,
233                                         loader;
234
235                                 /*
236                                  * http://qiita.com/sou/items/5688d4e7d3a37b4e2ff1
237                                  * L-01F 等の一部端末で Web Audio API の再生結果に特定条件下でノイズが混ざることがある。
238                                  * 描画レート(描画 FPS)が下がるとノイズが混ざり始め、レートを上げると再生結果が正常になるというもので、オーディオ処理が描画スレッドに巻き込まれているような動作を見せる。
239                                  */
240                                 if( X_UA[ 'Android' ] && X_UA[ 'Chrome' ] && !X_WebAudio_fpsFix ){
241                                         X_Node_systemNode.create( 'div', { id : 'fps-slowdown-make-sound-noisy' } );
242                                         X_WebAudio_fpsFix = true;
243                                 };
244
245                                 for( ; i < l; ++i ){
246                                         loader = X_WebAudio_BUFFER_LIST[ i ];
247                                         if( loader.audioUrl === url ){
248                                                 this.loader = loader;
249                                                 loader.webAudioList.push( this );
250                                                 break;
251                                         };
252                                 };
253                                 
254                                 if( !this.loader ){
255                                         this.loader = loader = X_WebAudio_BufferLoader( this, url );
256                                 };
257                                 
258                                 this.disatcher = disatcher || this;
259                                 this.setState( option );
260                                 
261                                 this[ 'listenOnce' ]( X_EVENT_KILL_INSTANCE, this.onKill );
262                                 
263                                 if( loader.audioBuffer || loader.errorState ){
264                                         this._onLoadBufferComplete();
265                                 } else {
266                                         loader[ 'listenOnce' ]( X_EVENT_COMPLETE, this, this._onLoadBufferComplete );
267                                 };
268                         },
269                         
270                         onKill : function(){
271                                 this.loader[ 'unlisten' ]( X_EVENT_COMPLETE, this, this._onLoadBufferComplete )
272                                         .unregister( this );
273
274                                 delete this.audioBuffer;
275                                 
276                                 this.playing      && this.actualPause();
277                     this.bufferSource && this._sourceDispose();
278         
279                     this._onended     && X_Closure_correct( this._onended );    
280         
281                     this.gainNode     && this.gainNode.disconnect();
282                         },
283                                 _onLoadBufferComplete : function( e ){
284                                         var loader = this.loader,
285                                                 buffer = loader.audioBuffer;
286                                         
287                                         e && loader[ 'unlisten' ]( X_EVENT_COMPLETE, this, this._onLoadBufferComplete );
288                                         
289                         if ( !buffer ) {
290                                 this.error = loader.errorState;
291                                 
292                             this.disatcher[ 'dispatch' ]({
293                                                                 type    : X_EVENT_ERROR,
294                                                                 error   : loader.errorState,
295                                                                 message : loader.errorState === 1 ?
296                                                                                         'load buffer network error' :
297                                                                                         'buffer decode error'
298                                                         });
299                                                 this[ 'kill' ]();
300                             return;
301                         };
302         
303                         this.audioBuffer = buffer;
304                         this.duration    = buffer.duration * 1000;
305
306                                         this.disatcher[ 'asyncDispatch' ]( X_WebAudio_touchState ? X_EVENT_MEDIA_TOUCH_FOR_LOAD : X_EVENT_READY );
307                                 },
308                         
309                         actualPlay : function(){
310                                 var e, begin, end;
311                                 
312                                 console.log( '[WebAudio] play abuf:' + !!this.audioBuffer );
313                                 
314                     if( !this.audioBuffer ){
315                         this._playReserved = true;
316                         return;
317                     };
318                                 
319                                 if( X_WebAudio_touchState ){
320                                         e = X_EventDispatcher_CURRENT_EVENTS[ X_EventDispatcher_CURRENT_EVENTS.length - 1 ];
321                                         if( !e || !e[ 'pointerType' ] ){
322                                                 // alert( 'タッチイベント以外での play! ' + ( e ? e.type : '' ) );
323                                                 return;
324                                         };
325                                         this.disatcher[ 'asyncDispatch' ]( X_EVENT_READY );
326                                 };
327                                 X_WebAudio_touchState = false;
328                                 
329                                 end   = X_Audio_getEndTime( this );
330                                 begin = X_Audio_getStartTime( this, end, true );
331                                 
332                                 console.log( '[WebAudio] play ' + begin + ' -> ' + end );
333                                 
334                                 if( this.bufferSource ) this._sourceDispose();
335                                 if( !this.gainNode ){
336                                         this.gainNode = X_WebAudio_context[ 'createGain' ] ? X_WebAudio_context[ 'createGain' ]() : X_WebAudio_context[ 'createGainNode' ]();
337                         this.gainNode[ 'connect' ]( X_WebAudio_context[ 'destination' ] );
338                                 };
339                     this.bufferSource        = X_WebAudio_context[ 'createBufferSource' ]();
340                     this.bufferSource.buffer = this.audioBuffer;
341                     this.bufferSource[ 'connect' ]( this.gainNode );
342                     
343                     this.gainNode[ 'gain' ].value = this.gain;
344                     
345                     // おかしい、stop 前に外していても呼ばれる、、、@Firefox33.1
346                     // 破棄された X.Callback が呼ばれて、obj.proxy() でエラーになる。Firefox では、onended は使わない
347                     // 多くのブラウザで onended は timer を使ったカウントより遅いので使わない
348                 //if( this.bufferSource.onended !== undefined ){
349                         //console.log( '> use onended' );
350                         //this.bufferSource.onended = this._onended || ( this._onended = X_Closure_create( this, this._onEnded ) );
351                 //} else {
352                         this._timerID && X_Timer_remove( this._timerID );
353                                         this._timerID = X_Timer_once( end - begin, this, this._onEnded );
354                 //};
355         
356                     if( this.bufferSource.start ){
357                         this.bufferSource.start( 0, begin / 1000, end / 1000 );
358                     } else {
359                         this.bufferSource[ 'noteGrainOn' ]( 0, begin / 1000, end / 1000 );
360                     };
361                     
362                     this.playing      = true;
363                     this._startPos    = begin;
364                     this._endPosition = end;
365                     this._startTime   = X_WebAudio_context.currentTime * 1000;
366                     this._interval    = this._interval || X_Timer_add( 1000, 0, this, this._onInterval );
367                         },
368                         
369                                 _sourceDispose : function(){
370                             this.bufferSource.disconnect();
371                             delete this.bufferSource.onended;
372                             delete this.bufferSource;
373                         },
374
375                                 _onInterval : function(){
376                                         if( !this.playing ){
377                                                 delete this._interval;
378                                                 return X_CALLBACK_UN_LISTEN;
379                                         };
380                                         this.disatcher[ 'dispatch' ]( X_EVENT_MEDIA_PLAYING );
381                                 },
382                                                 
383                                 _onEnded : function(){
384                                         var time;
385                                         delete this._timerID;
386                                         
387                             if( this.playing ){
388                                 time = X_WebAudio_context.currentTime * 1000 - this._startTime - this._endPosition + this._startPos | 0;
389                                 //console.log( '> onEnd ' + ( this.playing && ( X_WebAudio_context.currentTime * 1000 - this._startTime ) ) + ' < ' + ( this._endPosition - this._startPos ) );
390                                 if( this._onended ){
391                                         // Firefox 用の対策,,,
392                                         if( time < 0 ) return;
393                                 } else {
394                                         if( time < 0 ){
395                                                 //console.log( '> onEnd crt:' + ( X_WebAudio_context.currentTime * 1000 ) + ' startTime:' + this._startTime +
396                                                 //      ' from:' + this._startPos + ' to:' + this._endPosition );
397                                                 this._timerID = X_Timer_once( -time, this, this._onEnded );
398                                                 return;
399                                         };
400                                 };
401                                 
402                                 if( this.autoLoop ){
403                                         if( !( this.disatcher[ 'dispatch' ]( X_EVENT_MEDIA_BEFORE_LOOP ) & X_CALLBACK_PREVENT_DEFAULT ) ){
404                                                 this.looped = true;
405                                                 this.disatcher[ 'dispatch' ]( X_EVENT_MEDIA_LOOPED );
406                                                 this.actualPlay();
407                                         };
408                                 } else {
409                                         this.actualPause();
410                                         this.disatcher[ 'dispatch' ]( X_EVENT_MEDIA_ENDED );
411                                 };
412                             };
413                                 },
414                         
415                         actualPause : function(){
416                                 console.log( '[WebAudio] pause' );
417                                 
418                     this._timerID && X_Timer_remove( this._timerID );
419                                 delete this._timerID;
420                                 delete this.playing;
421
422                     if( this.bufferSource ){
423                         if( this.bufferSource.onended ) delete this.bufferSource.onended;
424                         
425                         this.bufferSource.stop ? 
426                                 this.bufferSource.stop( 0 ) : this.bufferSource[ 'noteOff' ]( 0 );
427                     };
428                         },
429                         
430                         getActualCurrentTime : function(){
431                                 return X_WebAudio_context.currentTime * 1000 - this._startTime + this._startPos | 0;
432                         },
433                         
434                         afterUpdateState : function( result ){
435                                 if( result & 2 || result & 1 ){ // seek
436                         this.actualPlay();
437                                 } else
438                                 if( result & 4 ){
439                        this.gainNode[ 'gain' ].value = this.gain;
440                                 };
441                         }
442
443                 }
444         );
445
446         X_Audio_BACKENDS.push(
447                 {
448                         backendID   : 1,
449                         
450                         backendName : 'WebAudio',
451
452                         canPlay     : X_Audio_codecs,
453
454                         detect      : function( proxy, source, ext ){
455                                 proxy[ 'asyncDispatch' ]( { type : X_EVENT_COMPLETE, canPlay : X_Audio_codecs[ ext ] } );
456                         },
457                         
458                         klass : X_WebAudio
459                 }
460         );
461 };