OSDN Git Service

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