OSDN Git Service

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