OSDN Git Service

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