2 using System.Collections.Generic;
4 using System.Diagnostics;
5 using System.Runtime.InteropServices;
7 using System.Runtime.CompilerServices;
8 using System.Threading;
10 using SlimDX.DirectSound;
11 using SlimDX.Multimedia;
13 using Un4seen.BassAsio;
14 using Un4seen.BassWasapi;
15 using Un4seen.Bass.AddOn.Mix;
16 using Un4seen.Bass.AddOn.Fx;
21 #region [ DTXMania用拡張 ]
22 public class CSound管理 // : CSound
24 public static ISoundDevice SoundDevice
28 public static ESoundDeviceType SoundDeviceType
32 public static CSoundTimer rc演奏用タイマ = null;
33 public static bool bUseOSTimer = false; // OSのタイマーを使うか、CSoundTimerを使うか。DTXCではfalse, DTXManiaではtrue。
34 // DTXC(DirectSound)でCSoundTimerを使うと、内部で無音のループサウンドを再生するため
35 // サウンドデバイスを占有してしまい、Viewerとして呼び出されるDTXManiaで、ASIOが使えなくなる。
37 // DTXMania単体でこれをtrueにすると、WASAPI/ASIO時に演奏タイマーとしてFDKタイマーではなく
38 // システムのタイマーを使うようになる。こうするとスクロールは滑らかになるが、音ズレが出るかもしれない。
40 public static IntPtr WindowHandle;
42 public static bool bIsTimeStretch = false;
44 private static int _nMasterVolume;
45 public int nMasterVolume
49 return _nMasterVolume;
53 SoundDevice.nMasterVolume = value;
54 _nMasterVolume = value;
59 ///// BASS時、mp3をストリーミング再生せずに、デコードしたraw wavをオンメモリ再生する場合はtrueにする。
60 ///// 特殊なmp3を使用時はシークが乱れるので、必要に応じてtrueにすること。(Config.iniのNoMP3Streamingで設定可能。)
61 ///// ただし、trueにすると、その分再生開始までの時間が長くなる。
63 //public static bool bIsMP3DecodeByWindowsCodec = false;
65 public static int nMixing = 0;
66 public int GetMixingStreams()
70 public static int nStreams = 0;
71 public int GetStreams()
75 #region [ WASAPI/ASIO/DirectSound設定値 ]
77 /// <para>WASAPI 排他モード出力における再生遅延[ms](の希望値)。最終的にはこの数値を基にドライバが決定する)。</para>
78 /// <para>0以下の値を指定すると、この数値はWASAPI初期化時に自動設定する。正数を指定すると、その値を設定しようと試みる。</para>
80 public static int SoundDelayExclusiveWASAPI = 0; // SSTでは、50ms
81 public int GetSoundExclusiveWASAPI()
83 return SoundDelayExclusiveWASAPI;
85 public void SetSoundDelayExclusiveWASAPI( int value )
87 SoundDelayExclusiveWASAPI = value;
90 /// <para>WASAPI 共有モード出力における再生遅延[ms]。ユーザが決定する。</para>
92 public static int SoundDelaySharedWASAPI = 100;
94 /// <para>排他WASAPIバッファの更新間隔。出力間隔ではないので注意。</para>
95 /// <para>→ 自動設定されるのでSoundDelay よりも小さい値であること。(小さすぎる場合はBASSによって自動修正される。)</para>
97 public static int SoundUpdatePeriodExclusiveWASAPI = 6;
99 /// <para>共有WASAPIバッファの更新間隔。出力間隔ではないので注意。</para>
100 /// <para>SoundDelay よりも小さい値であること。(小さすぎる場合はBASSによって自動修正される。)</para>
102 public static int SoundUpdatePeriodSharedWASAPI = 6;
104 ///// <para>ASIO 出力における再生遅延[ms](の希望値)。最終的にはこの数値を基にドライバが決定する)。</para>
106 //public static int SoundDelayASIO = 0; // SSTでは50ms。0にすると、デバイスの設定値をそのまま使う。
108 /// <para>ASIO 出力におけるバッファサイズ。</para>
110 public static int SoundDelayASIO = 0; // 0にすると、デバイスの設定値をそのまま使う。
111 public int GetSoundDelayASIO()
113 return SoundDelayASIO;
115 public void SetSoundDelayASIO(int value)
117 SoundDelayASIO = value;
119 public static int ASIODevice = 0;
120 public int GetASIODevice()
124 public void SetASIODevice(int value)
129 /// <para>DirectSound 出力における再生遅延[ms]。ユーザが決定する。</para>
131 public static int SoundDelayDirectSound = 100;
133 public long GetSoundDelay()
135 if ( SoundDevice != null )
137 return SoundDevice.n実バッファサイズms;
151 /// <param name="handle"></param>
152 public CSound管理( IntPtr handle ) // #30803 従来のコンストラクタ相当のI/Fを追加。(DTXC用)
154 WindowHandle = handle;
157 t初期化( ESoundDeviceType.DirectSound, 0, 0, 0 );
162 /// <param name="handle"></param>
163 /// <param name="soundDeviceType"></param>
164 /// <param name="nSoundDelayExclusiveWASAPI"></param>
165 /// <param name="nSoundDelayASIO"></param>
166 /// <param name="nASIODevice"></param>
167 public CSound管理( IntPtr handle, ESoundDeviceType soundDeviceType, int nSoundDelayExclusiveWASAPI, int nSoundDelayASIO, int nASIODevice, bool _bUseOSTimer )
169 WindowHandle = handle;
171 //bUseOSTimer = false;
172 t初期化( soundDeviceType, nSoundDelayExclusiveWASAPI, nSoundDelayASIO, nASIODevice, _bUseOSTimer );
174 public void Dispose()
179 //public static void t初期化()
181 // t初期化( ESoundDeviceType.DirectSound, 0, 0, 0 );
184 public void t初期化( ESoundDeviceType soundDeviceType, int _nSoundDelayExclusiveWASAPI, int _nSoundDelayASIO, int _nASIODevice, IntPtr handle )
186 //if ( !bInitialized )
188 WindowHandle = handle;
189 t初期化( soundDeviceType, _nSoundDelayExclusiveWASAPI, _nSoundDelayASIO, _nASIODevice );
190 //bInitialized = true;
193 public void t初期化( ESoundDeviceType soundDeviceType, int _nSoundDelayExclusiveWASAPI, int _nSoundDelayASIO, int _nASIODevice )
195 t初期化( soundDeviceType, _nSoundDelayExclusiveWASAPI, _nSoundDelayASIO, _nASIODevice, false );
198 public void t初期化( ESoundDeviceType soundDeviceType, int _nSoundDelayExclusiveWASAPI, int _nSoundDelayASIO, int _nASIODevice, bool _bUseOSTimer )
200 //SoundDevice = null; // 後で再初期化することがあるので、null初期化はコンストラクタに回す
201 rc演奏用タイマ = null; // Global.Bass 依存(つまりユーザ依存)
204 SoundDelayExclusiveWASAPI = _nSoundDelayExclusiveWASAPI;
205 SoundDelayASIO = _nSoundDelayASIO;
206 ASIODevice = _nASIODevice;
207 bUseOSTimer = _bUseOSTimer;
209 ESoundDeviceType[] ESoundDeviceTypes = new ESoundDeviceType[ 4 ]
211 ESoundDeviceType.ExclusiveWASAPI,
212 ESoundDeviceType.ASIO,
213 ESoundDeviceType.DirectSound,
214 ESoundDeviceType.Unknown
218 switch ( soundDeviceType )
220 case ESoundDeviceType.ExclusiveWASAPI:
223 case ESoundDeviceType.ASIO:
226 case ESoundDeviceType.DirectSound:
233 for ( SoundDeviceType = ESoundDeviceTypes[ n初期デバイス ]; ; SoundDeviceType = ESoundDeviceTypes[ ++n初期デバイス ] )
237 t現在のユーザConfigに従ってサウンドデバイスとすべての既存サウンドを再構築する();
240 catch ( Exception e )
242 Trace.TraceInformation( e.Message );
243 if ( ESoundDeviceTypes[ n初期デバイス ] == ESoundDeviceType.Unknown )
245 Trace.TraceError( string.Format( "サウンドデバイスの初期化に失敗しました。" ) );
250 if ( soundDeviceType == ESoundDeviceType.ExclusiveWASAPI || soundDeviceType == ESoundDeviceType.ASIO )
252 //Bass.BASS_SetConfig( BASSConfig.BASS_CONFIG_UPDATETHREADS, 4 );
253 //Bass.BASS_SetConfig( BASSConfig.BASS_CONFIG_UPDATEPERIOD, 0 );
255 Trace.TraceInformation( "BASS_CONFIG_UpdatePeriod=" + Bass.BASS_GetConfig( BASSConfig.BASS_CONFIG_UPDATEPERIOD ) );
256 Trace.TraceInformation( "BASS_CONFIG_UpdateThreads=" + Bass.BASS_GetConfig( BASSConfig.BASS_CONFIG_UPDATETHREADS ) );
260 public void tDisableUpdateBufferAutomatically()
262 //Bass.BASS_SetConfig( BASSConfig.BASS_CONFIG_UPDATETHREADS, 0 );
263 //Bass.BASS_SetConfig( BASSConfig.BASS_CONFIG_UPDATEPERIOD, 0 );
265 //Trace.TraceInformation( "BASS_CONFIG_UpdatePeriod=" + Bass.BASS_GetConfig( BASSConfig.BASS_CONFIG_UPDATEPERIOD ) );
266 //Trace.TraceInformation( "BASS_CONFIG_UpdateThreads=" + Bass.BASS_GetConfig( BASSConfig.BASS_CONFIG_UPDATETHREADS ) );
270 public static void t終了()
272 C共通.tDisposeする( SoundDevice ); SoundDevice = null;
273 C共通.tDisposeする( ref rc演奏用タイマ ); // Global.Bass を解放した後に解放すること。(Global.Bass で参照されているため)
277 public static void t現在のユーザConfigに従ってサウンドデバイスとすべての既存サウンドを再構築する()
279 #region [ すでにサウンドデバイスと演奏タイマが構築されていれば解放する。]
281 if ( SoundDevice != null )
283 // すでに生成済みのサウンドがあれば初期状態に戻す。
285 CSound.tすべてのサウンドを初期状態に戻す(); // リソースは解放するが、CSoundのインスタンスは残す。
288 // サウンドデバイスと演奏タイマを解放する。
290 C共通.tDisposeする( SoundDevice ); SoundDevice = null;
291 C共通.tDisposeする( ref rc演奏用タイマ ); // Global.SoundDevice を解放した後に解放すること。(Global.SoundDevice で参照されているため)
296 #region [ 新しいサウンドデバイスを構築する。]
298 switch ( SoundDeviceType )
300 case ESoundDeviceType.ExclusiveWASAPI:
301 SoundDevice = new CSoundDeviceWASAPI( CSoundDeviceWASAPI.Eデバイスモード.排他, SoundDelayExclusiveWASAPI, SoundUpdatePeriodExclusiveWASAPI );
304 case ESoundDeviceType.SharedWASAPI:
305 SoundDevice = new CSoundDeviceWASAPI( CSoundDeviceWASAPI.Eデバイスモード.共有, SoundDelaySharedWASAPI, SoundUpdatePeriodSharedWASAPI );
308 case ESoundDeviceType.ASIO:
309 SoundDevice = new CSoundDeviceASIO( SoundDelayASIO, ASIODevice );
312 case ESoundDeviceType.DirectSound:
313 SoundDevice = new CSoundDeviceDirectSound( WindowHandle, SoundDelayDirectSound, bUseOSTimer );
317 throw new Exception( string.Format( "未対応の SoundDeviceType です。[{0}]", SoundDeviceType.ToString() ) );
321 #region [ 新しい演奏タイマを構築する。]
323 rc演奏用タイマ = new CSoundTimer( SoundDevice );
327 SoundDevice.nMasterVolume = _nMasterVolume; // サウンドデバイスに対して、マスターボリュームを再設定する
329 CSound.tすべてのサウンドを再構築する( SoundDevice ); // すでに生成済みのサウンドがあれば作り直す。
331 public CSound tサウンドを生成する( string filename )
333 if ( SoundDeviceType == ESoundDeviceType.Unknown )
335 throw new Exception( string.Format( "未対応の SoundDeviceType です。[{0}]", SoundDeviceType.ToString() ) );
337 return SoundDevice.tサウンドを作成する( filename );
340 private static DateTime lastUpdateTime = DateTime.MinValue;
341 public void t再生中の処理をする( object o ) // #26122 2011.9.1 yyagi; delegate経由の呼び出し用
345 public void t再生中の処理をする()
347 //★★★★★★★★★★★★★★★★★★★★★ダミー★★★★★★★★★★★★★★★★★★
348 // Debug.Write( "再生中の処理をする()" );
349 //DateTime now = DateTime.Now;
350 //TimeSpan ts = now - lastUpdateTime;
351 //if ( ts.Milliseconds > 5 )
353 // bool b = Bass.BASS_Update( 100 * 2 );
354 // lastUpdateTime = DateTime.Now;
357 // Trace.TraceInformation( "BASS_UPdate() failed: " + Bass.BASS_ErrorGetCode().ToString() );
362 public void tサウンドを破棄する( CSound csound )
364 csound.t解放する( true ); // インスタンスは存続→破棄にする。
368 public float GetCPUusage()
371 switch ( SoundDeviceType )
373 case ESoundDeviceType.ExclusiveWASAPI:
374 case ESoundDeviceType.SharedWASAPI:
375 f = BassWasapi.BASS_WASAPI_GetCPU();
377 case ESoundDeviceType.ASIO:
378 f = BassAsio.BASS_ASIO_GetCPU();
380 case ESoundDeviceType.DirectSound:
390 public ESoundDeviceType GetCurrentSoundDeviceType()
392 return SoundDeviceType;
395 public void AddMixer( CSound cs, double db再生速度, bool _b演奏終了後も再生が続くチップである )
397 cs.b演奏終了後も再生が続くチップである = _b演奏終了後も再生が続くチップである;
399 cs.tBASSサウンドをミキサーに追加する();
401 public void AddMixer( CSound cs, double db再生速度 )
404 cs.tBASSサウンドをミキサーに追加する();
406 public void AddMixer( CSound cs )
408 cs.tBASSサウンドをミキサーに追加する();
410 public void RemoveMixer( CSound cs )
412 cs.tBASSサウンドをミキサーから削除する();
417 // CSound は、サウンドデバイスが変更されたときも、インスタンスを再作成することなく、新しいデバイスで作り直せる必要がある。
418 // そのため、デバイスごとに別のクラスに分割するのではなく、1つのクラスに集約するものとする。
420 public class CSound : IDisposable, ICloneable
422 #region [ DTXMania用拡張 ]
428 public int nサウンドバッファサイズ // 取りあえず0固定★★★★★★★★★★★★★★★★★★★★
432 public bool bストリーム再生する // 取りあえずfalse固定★★★★★★★★★★★★★★★★★★★★
433 // trueにすると同一チップ音の多重再生で問題が出る(4POLY音源として動かない)
435 get { return false; }
437 public double db周波数倍率
445 if ( _db周波数倍率 != value )
450 Bass.BASS_ChannelSetAttribute( this.hBassStream, BASSAttribute.BASS_ATTRIB_FREQ, ( float ) ( _db周波数倍率 * _db再生速度 * nオリジナルの周波数 ) );
454 // if ( b再生中 ) // #30838 2012.2.24 yyagi (delete b再生中)
456 this.Buffer.Frequency = ( int ) ( _db周波数倍率 * _db再生速度 * nオリジナルの周波数 );
470 if ( _db再生速度 != value )
473 bIs1倍速再生 = ( _db再生速度 == 1.000f );
476 if ( _hTempoStream != 0 && !this.bIs1倍速再生 ) // 再生速度がx1.000のときは、TempoStreamを用いないようにして高速化する
478 this.hBassStream = _hTempoStream;
482 this.hBassStream = _hBassStream;
485 if ( CSound管理.bIsTimeStretch )
487 Bass.BASS_ChannelSetAttribute( this.hBassStream, BASSAttribute.BASS_ATTRIB_TEMPO, (float) ( db再生速度 * 100 - 100 ) );
488 //double seconds = Bass.BASS_ChannelBytes2Seconds( this.hTempoStream, nBytes );
489 //this.n総演奏時間ms = (int) ( seconds * 1000 );
493 Bass.BASS_ChannelSetAttribute( this.hBassStream, BASSAttribute.BASS_ATTRIB_FREQ, ( float ) ( _db周波数倍率 * _db再生速度 * nオリジナルの周波数 ) );
498 // if ( b再生中 ) // #30838 2012.2.24 yyagi (delete b再生中)
500 this.Buffer.Frequency = ( int ) ( _db周波数倍率 * _db再生速度 * nオリジナルの周波数 );
508 public bool b演奏終了後も再生が続くチップである = false; // これがtrueなら、本サウンドの再生終了のコールバック時に自動でミキサーから削除する
510 //private STREAMPROC _cbStreamXA; // make it global, so that the GC can not remove it
511 private SYNCPROC _cbEndofStream; // ストリームの終端まで再生されたときに呼び出されるコールバック
512 // private WaitCallback _cbRemoveMixerChannel;
515 /// <para>0:最小~100:原音</para>
521 if( this.bBASSサウンドである )
524 if ( !Bass.BASS_ChannelGetAttribute( this.hBassStream, BASSAttribute.BASS_ATTRIB_VOL, ref f音量 ) )
525 //if ( BassMix.BASS_Mixer_ChannelGetEnvelopePos( this.hBassStream, BASSMIXEnvelope.BASS_MIXER_ENV_VOL, ref f音量 ) == -1 )
527 return (int) ( f音量 * 100 );
529 else if( this.bDirectSoundである )
537 if( this.bBASSサウンドである )
539 float f音量 = Math.Min( Math.Max( value, 0 ), 100 ) / 100.0f; // 0~100 → 0.0~1.0
540 //var nodes = new BASS_MIXER_NODE[ 1 ] { new BASS_MIXER_NODE( 0, f音量 ) };
541 //BassMix.BASS_Mixer_ChannelSetEnvelope( this.hBassStream, BASSMIXEnvelope.BASS_MIXER_ENV_VOL, nodes );
542 Bass.BASS_ChannelSetAttribute( this.hBassStream, BASSAttribute.BASS_ATTRIB_VOL, f音量 );
545 else if( this.bDirectSoundである )
551 this._n音量db = -10000;
555 this._n音量db = (int) ( ( 20.0 * Math.Log10( ( (double) this._n音量 ) / 100.0 ) ) * 100.0 );
558 this.Buffer.Volume = this._n音量db;
564 /// <para>左:-100~中央:0~100:右。set のみ。</para>
570 if( this.bBASSサウンドである )
573 if ( !Bass.BASS_ChannelGetAttribute( this.hBassStream, BASSAttribute.BASS_ATTRIB_PAN, ref f位置 ) )
574 //if( BassMix.BASS_Mixer_ChannelGetEnvelopePos( this.hBassStream, BASSMIXEnvelope.BASS_MIXER_ENV_PAN, ref f位置 ) == -1 )
576 return (int) ( f位置 * 100 );
578 else if( this.bDirectSoundである )
586 if( this.bBASSサウンドである )
588 float f位置 = Math.Min( Math.Max( value, -100 ), 100 ) / 100.0f; // -100~100 → -1.0~1.0
589 //var nodes = new BASS_MIXER_NODE[ 1 ] { new BASS_MIXER_NODE( 0, f位置 ) };
590 //BassMix.BASS_Mixer_ChannelSetEnvelope( this.hBassStream, BASSMIXEnvelope.BASS_MIXER_ENV_PAN, nodes );
591 Bass.BASS_ChannelSetAttribute( this.hBassStream, BASSAttribute.BASS_ATTRIB_PAN, f位置 );
593 else if( this.bDirectSoundである )
595 this._n位置 = Math.Min( Math.Max( -100, value ), 100 ); // -100~100
601 else if( this._n位置 == -100 )
603 this._n位置db = -10000;
605 else if( this._n位置 == 100 )
609 else if( this._n位置 < 0 )
611 this._n位置db = (int) ( ( 20.0 * Math.Log10( ( (double) ( this._n位置 + 100 ) ) / 100.0 ) ) * 100.0 );
615 this._n位置db = (int) ( ( -20.0 * Math.Log10( ( (double) ( 100 - this._n位置 ) ) / 100.0 ) ) * 100.0 );
618 this.Buffer.Pan = this._n位置db;
624 /// <para>DirectSoundのセカンダリバッファ。</para>
626 //public SecondarySoundBuffer DirectSoundBuffer
627 public SoundBuffer DirectSoundBuffer
629 get { return this.Buffer; }
633 /// <para>DirectSoundのセカンダリバッファ作成時のフラグ。</para>
635 public BufferFlags DirectSoundBufferFlags
642 /// <para>全インスタンスリスト。</para>
643 /// <para>~を作成する() で追加され、t解放する() or Dispose() で解放される。</para>
645 public static List<CSound> listインスタンス = new List<CSound>();
647 public static void ShowAllCSoundFiles()
650 foreach ( CSound cs in listインスタンス )
652 Debug.WriteLine( i++.ToString( "d3" ) + ": " + Path.GetFileName( cs.strファイル名 ) );
662 this.DirectSoundBufferFlags = CSoundDeviceDirectSound.DefaultFlags;
663 // this._cbRemoveMixerChannel = new WaitCallback( RemoveMixerChannelLater );
664 this._hBassStream = -1;
665 this._hTempoStream = 0;
668 public object Clone()
670 if ( !bDirectSoundである )
672 throw new NotImplementedException();
674 CSound clone = (CSound) MemberwiseClone(); // これだけだとCY連打が途切れる&タイトルに戻る際にNullRef例外発生
675 this.DirectSound.DuplicateSoundBuffer( this.Buffer, out clone.Buffer );
677 CSound.listインスタンス.Add( clone ); // インスタンスリストに登録。
681 public void tASIOサウンドを作成する( string strファイル名, int hMixer )
683 this.tBASSサウンドを作成する( strファイル名, hMixer, BASSFlag.BASS_STREAM_DECODE );
684 this.eデバイス種別 = ESoundDeviceType.ASIO; // 作成後に設定する。(作成に失敗してると例外発出されてここは実行されない)
686 public void tASIOサウンドを作成する( byte[] byArrWAVファイルイメージ, int hMixer )
688 this.tBASSサウンドを作成する( byArrWAVファイルイメージ, hMixer, BASSFlag.BASS_STREAM_DECODE );
689 this.eデバイス種別 = ESoundDeviceType.ASIO; // 作成後に設定する。(作成に失敗してると例外発出されてここは実行されない)
691 public void tWASAPIサウンドを作成する( string strファイル名, int hMixer, ESoundDeviceType eデバイス種別 )
693 this.tBASSサウンドを作成する( strファイル名, hMixer, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_FLOAT );
694 this.eデバイス種別 = eデバイス種別; // 作成後に設定する。(作成に失敗してると例外発出されてここは実行されない)
696 public void tWASAPIサウンドを作成する( byte[] byArrWAVファイルイメージ, int hMixer, ESoundDeviceType eデバイス種別 )
698 this.tBASSサウンドを作成する( byArrWAVファイルイメージ, hMixer, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_FLOAT );
699 this.eデバイス種別 = eデバイス種別; // 作成後に設定する。(作成に失敗してると例外発出されてここは実行されない)
701 public void tDirectSoundサウンドを作成する( string strファイル名, DirectSound DirectSound )
703 this.e作成方法 = E作成方法.ファイルから;
704 this.strファイル名 = strファイル名;
706 if ( String.Compare( Path.GetExtension( strファイル名 ), ".xa", true ) == 0 ||
707 String.Compare( Path.GetExtension( strファイル名 ), ".mp3", true ) == 0 ||
708 String.Compare( Path.GetExtension( strファイル名 ), ".ogg", true ) == 0 ) // caselessで文字列比較
710 tDirectSoundサウンドを作成するXaOggMp3( strファイル名, DirectSound );
714 // すべてのファイルを DirectShow でデコードすると時間がかかるので、ファイルが WAV かつ PCM フォーマットでない場合のみ DirectShow でデコードする。
716 byte[] byArrWAVファイルイメージ = null;
717 bool bファイルがWAVかつPCMフォーマットである = true;
720 #region [ ファイルがWAVかつPCMフォーマットか否か調べる。]
724 using ( var ws = new WaveStream( strファイル名 ) )
726 if ( ws.Format.FormatTag != WaveFormatTag.Pcm )
727 bファイルがWAVかつPCMフォーマットである = false;
732 bファイルがWAVかつPCMフォーマットである = false;
737 if ( bファイルがWAVかつPCMフォーマットである )
739 #region [ ファイルを読み込んで byArrWAVファイルイメージへ格納。]
741 var fs = File.Open( strファイル名, FileMode.Open, FileAccess.Read );
742 var br = new BinaryReader( fs );
744 byArrWAVファイルイメージ = new byte[ fs.Length ];
745 br.Read( byArrWAVファイルイメージ, 0, (int) fs.Length );
754 #region [ DirectShow でデコード変換し、 byArrWAVファイルイメージへ格納。]
756 CDStoWAVFileImage.t変換( strファイル名, out byArrWAVファイルイメージ );
764 this.tDirectSoundサウンドを作成する( byArrWAVファイルイメージ, DirectSound );
766 public void tDirectSoundサウンドを作成するXaOggMp3( string strファイル名, DirectSound DirectSound )
768 this.e作成方法 = E作成方法.ファイルから;
769 this.strファイル名 = strファイル名;
772 WaveFormat wfx = new WaveFormat();
773 int nPCMデータの先頭インデックス = 0;
774 // int nPCMサイズbyte = (int) ( xa.xaheader.nSamples * xa.xaheader.nChannels * 2 ); // nBytes = Bass.BASS_ChannelGetLength( this.hBassStream );
777 CWin32.WAVEFORMATEX cw32wfx;
778 tオンメモリ方式でデコードする( strファイル名, out this.byArrWAVファイルイメージ,
779 out nPCMデータの先頭インデックス, out nPCMサイズbyte, out cw32wfx, false );
781 wfx.AverageBytesPerSecond = (int) cw32wfx.nAvgBytesPerSec;
782 wfx.BitsPerSample = (short) cw32wfx.wBitsPerSample;
783 wfx.BlockAlignment = (short) cw32wfx.nBlockAlign;
784 wfx.Channels = (short) cw32wfx.nChannels;
785 wfx.FormatTag = WaveFormatTag.Pcm; // xa.waveformatex.wFormatTag;
786 wfx.SamplesPerSecond = (int) cw32wfx.nSamplesPerSec;
788 // セカンダリバッファを作成し、PCMデータを書き込む。
789 tDirectSoundサウンドを作成する_セカンダリバッファの作成とWAVデータ書き込み
790 ( ref this.byArrWAVファイルイメージ, DirectSound, CSoundDeviceDirectSound.DefaultFlags, wfx,
791 nPCMサイズbyte, nPCMデータの先頭インデックス );
794 public void tDirectSoundサウンドを作成する( byte[] byArrWAVファイルイメージ, DirectSound DirectSound )
796 this.tDirectSoundサウンドを作成する( byArrWAVファイルイメージ, DirectSound, CSoundDeviceDirectSound.DefaultFlags );
798 public void tDirectSoundサウンドを作成する( byte[] byArrWAVファイルイメージ, DirectSound DirectSound, BufferFlags flags )
800 if( this.e作成方法 == E作成方法.Unknown )
801 this.e作成方法 = E作成方法.WAVファイルイメージから;
803 WaveFormat wfx = null;
804 int nPCMデータの先頭インデックス = -1;
805 int nPCMサイズbyte = -1;
807 #region [ byArrWAVファイルイメージ[] から上記3つのデータを取得。]
809 var ms = new MemoryStream( byArrWAVファイルイメージ );
810 var br = new BinaryReader( ms );
816 if( br.ReadUInt32() != 0x46464952 )
817 throw new InvalidDataException( "RIFFファイルではありません。" );
821 if( br.ReadUInt32() != 0x45564157 )
822 throw new InvalidDataException( "WAVEファイルではありません。" );
825 while( ( ms.Position + 8 ) < ms.Length ) // +8 は、チャンク名+チャンクサイズ。残り8バイト未満ならループ終了。
827 uint chunkName = br.ReadUInt32();
830 if( chunkName == 0x20746D66 )
832 long chunkSize = (long) br.ReadUInt32();
834 var tag = (WaveFormatTag) br.ReadUInt16();
836 if( tag == WaveFormatTag.Pcm ) wfx = new WaveFormat();
837 else if( tag == WaveFormatTag.Extensible ) wfx = new SlimDX.Multimedia.WaveFormatExtensible(); // このクラスは WaveFormat を継承している。
839 throw new InvalidDataException( string.Format( "未対応のWAVEフォーマットタグです。(Tag:{0})", tag.ToString() ) );
842 wfx.Channels = br.ReadInt16();
843 wfx.SamplesPerSecond = br.ReadInt32();
844 wfx.AverageBytesPerSecond = br.ReadInt32();
845 wfx.BlockAlignment = br.ReadInt16();
846 wfx.BitsPerSample = br.ReadInt16();
848 long nフォーマットサイズbyte = 16;
850 if( wfx.FormatTag == WaveFormatTag.Extensible )
852 br.ReadUInt16(); // 拡張領域サイズbyte
853 var wfxEx = (SlimDX.Multimedia.WaveFormatExtensible) wfx;
854 wfxEx.ValidBitsPerSample = br.ReadInt16();
855 wfxEx.ChannelMask = (Speakers) br.ReadInt32();
856 wfxEx.SubFormat = new Guid( br.ReadBytes( 16 ) ); // GUID は 16byte (128bit)
858 nフォーマットサイズbyte += 24;
861 ms.Seek( chunkSize - nフォーマットサイズbyte, SeekOrigin.Current );
866 else if( chunkName == 0x61746164 )
868 nPCMサイズbyte = br.ReadInt32();
869 nPCMデータの先頭インデックス = (int) ms.Position;
871 ms.Seek( nPCMサイズbyte, SeekOrigin.Current );
878 long chunkSize = (long) br.ReadUInt32();
879 ms.Seek( chunkSize, SeekOrigin.Current );
885 throw new InvalidDataException( "fmt チャンクが存在しません。不正なサウンドデータです。" );
886 if( nPCMサイズbyte < 0 )
887 throw new InvalidDataException( "data チャンクが存在しません。不正なサウンドデータです。" );
898 // セカンダリバッファを作成し、PCMデータを書き込む。
899 tDirectSoundサウンドを作成する_セカンダリバッファの作成とWAVデータ書き込み(
900 ref byArrWAVファイルイメージ, DirectSound, flags, wfx, nPCMサイズbyte, nPCMデータの先頭インデックス );
903 private void tDirectSoundサウンドを作成する_セカンダリバッファの作成とWAVデータ書き込み
904 ( ref byte[] byArrWAVファイルイメージ, DirectSound DirectSound, BufferFlags flags, WaveFormat wfx,
905 int nPCMサイズbyte, int nPCMデータの先頭インデックス )
907 // セカンダリバッファを作成し、PCMデータを書き込む。
909 this.Buffer = new SecondarySoundBuffer( DirectSound, new SoundBufferDescription()
911 Format = ( wfx.FormatTag == WaveFormatTag.Pcm ) ? wfx : (SlimDX.Multimedia.WaveFormatExtensible) wfx,
913 SizeInBytes = nPCMサイズbyte,
915 this.Buffer.Write( byArrWAVファイルイメージ, nPCMデータの先頭インデックス, nPCMサイズbyte, 0, LockFlags.None );
919 this.eデバイス種別 = ESoundDeviceType.DirectSound;
920 this.DirectSoundBufferFlags = flags;
921 this.byArrWAVファイルイメージ = byArrWAVファイルイメージ;
922 this.DirectSound = DirectSound;
925 this.nオリジナルの周波数 = wfx.SamplesPerSecond;
926 n総演奏時間ms = (int) ( ( (double) nPCMサイズbyte ) / ( this.Buffer.Format.AverageBytesPerSecond * 0.001 ) );
931 CSound.listインスタンス.Add( this );
934 #region [ DTXMania用の変換 ]
936 public void tサウンドを破棄する( CSound cs )
940 public void t再生を開始する()
945 public void t再生を開始する( bool bループする )
951 Bass.BASS_ChannelFlags( this.hBassStream, BASSFlag.BASS_SAMPLE_LOOP, BASSFlag.BASS_SAMPLE_LOOP );
955 Bass.BASS_ChannelFlags( this.hBassStream, BASSFlag.BASS_DEFAULT, BASSFlag.BASS_DEFAULT );
959 tサウンドを再生する( bループする );
961 public void t再生を停止する()
966 public void t再生を一時停止する()
971 public void t再生を再開する( long t ) // ★★★★★★★★★★★★★★★★★★★★★★★★★★★★
973 Debug.WriteLine( "t再生を再開する(long " + t + ")" );
982 if ( this.bBASSサウンドである )
984 bool ret = ( BassMix.BASS_Mixer_ChannelIsActive( this.hBassStream ) == BASSActive.BASS_ACTIVE_PAUSED ) &
985 ( BassMix.BASS_Mixer_ChannelGetPosition( this.hBassStream ) > 0 );
990 return ( this.n一時停止回数 > 0 );
998 if ( this.eデバイス種別 == ESoundDeviceType.DirectSound )
1000 return ( ( this.Buffer.Status & BufferStatus.Playing ) != BufferStatus.None );
1004 // 基本的にはBASS_ACTIVE_PLAYINGなら再生中だが、最後まで再生しきったchannelも
1005 // BASS_ACTIVE_PLAYINGのままになっているので、小細工が必要。
1006 bool ret = ( BassMix.BASS_Mixer_ChannelIsActive( this.hBassStream ) == BASSActive.BASS_ACTIVE_PLAYING );
1007 if ( BassMix.BASS_Mixer_ChannelGetPosition( this.hBassStream ) >= nBytes )
1015 //public lint t時刻から位置を返す( long t )
1017 // double num = ( n時刻 * this.db再生速度 ) * this.db周波数倍率;
1018 // return (int) ( ( num * 0.01 ) * this.nSamplesPerSecond );
1028 public void t解放する( bool _bインスタンス削除 )
1030 if ( this.bBASSサウンドである ) // stream数の削減用
1032 tBASSサウンドをミキサーから削除する();
1033 _cbEndofStream = null;
1034 //_cbStreamXA = null;
1035 CSound管理.nStreams--;
1037 bool bManagedも解放する = true;
1038 bool bインスタンス削除 = _bインスタンス削除; // CSoundの再初期化時は、インスタンスは存続する。
1039 this.Dispose( bManagedも解放する, bインスタンス削除 );
1040 //Debug.WriteLine( "Disposed: " + _bインスタンス削除 + " : " + Path.GetFileName( this.strファイル名 ) );
1042 public void tサウンドを再生する()
1044 tサウンドを再生する( false );
1046 public void tサウンドを再生する( bool bループする )
1048 if ( this.bBASSサウンドである ) // BASSサウンド時のループ処理は、t再生を開始する()側に実装。ここでは「bループする」は未使用。
1050 //Debug.WriteLine( "再生中?: " + System.IO.Path.GetFileName(this.strファイル名) + " status=" + BassMix.BASS_Mixer_ChannelIsActive( this.hBassStream ) + " current=" + BassMix.BASS_Mixer_ChannelGetPosition( this.hBassStream ) + " nBytes=" + nBytes );
1051 bool b = BassMix.BASS_Mixer_ChannelPlay( this.hBassStream );
1054 //Debug.WriteLine( "再生しようとしたが、Mixerに登録されていなかった: " + Path.GetFileName( this.strファイル名 ) + ", stream#=" + this.hBassStream + ", ErrCode=" + Bass.BASS_ErrorGetCode() );
1056 bool bb = tBASSサウンドをミキサーに追加する();
1059 Debug.WriteLine( "Mixerへの登録に失敗: " + Path.GetFileName( this.strファイル名 ) + ", ErrCode=" + Bass.BASS_ErrorGetCode() );
1063 //Debug.WriteLine( "Mixerへの登録に成功: " + Path.GetFileName( this.strファイル名 ) + ": " + Bass.BASS_ErrorGetCode() );
1065 //this.t再生位置を先頭に戻す();
1067 bool bbb = BassMix.BASS_Mixer_ChannelPlay( this.hBassStream );
1070 Debug.WriteLine("更に再生に失敗: " + Path.GetFileName(this.strファイル名) + ", ErrCode=" + Bass.BASS_ErrorGetCode() );
1074 // Debug.WriteLine("再生成功(ミキサー追加後) : " + Path.GetFileName(this.strファイル名));
1079 //Debug.WriteLine( "再生成功: " + Path.GetFileName( this.strファイル名 ) + " (" + hBassStream + ")" );
1082 else if( this.bDirectSoundである )
1084 PlayFlags pf = ( bループする ) ? PlayFlags.Looping : PlayFlags.None;
1085 this.Buffer.Play( 0, pf );
1088 public void tサウンドを先頭から再生する()
1093 public void tサウンドを停止してMixerからも削除する()
1095 tサウンドを停止する( false );
1098 tBASSサウンドをミキサーから削除する();
1101 public void tサウンドを停止する()
1103 tサウンドを停止する( false );
1105 public void tサウンドを停止する( bool pause )
1107 if( this.bBASSサウンドである )
1109 //Debug.WriteLine( "停止: " + System.IO.Path.GetFileName( this.strファイル名 ) + " status=" + BassMix.BASS_Mixer_ChannelIsActive( this.hBassStream ) + " current=" + BassMix.BASS_Mixer_ChannelGetPosition( this.hBassStream ) + " nBytes=" + nBytes );
1110 BassMix.BASS_Mixer_ChannelPause( this.hBassStream );
1113 // tBASSサウンドをミキサーから削除する(); // PAUSEと再生停止を区別できるようにすること!!
1116 else if( this.bDirectSoundである )
1124 // WASAPI/ASIOとDirectSoundを同時使用すると、Bufferがlostしてここで例外発生する。→ catchして無視する。
1125 // DTXCからDTXManiaを呼び出すと、DTXC終了時にこの現象が発生する。
1131 public void t再生位置を先頭に戻す()
1133 if( this.bBASSサウンドである )
1135 BassMix.BASS_Mixer_ChannelSetPosition( this.hBassStream, 0 );
1138 else if( this.bDirectSoundである )
1140 this.Buffer.CurrentPlayPosition = 0;
1143 public void t再生位置を変更する( long n位置ms )
1145 if ( this.bBASSサウンドである )
1150 b = BassMix.BASS_Mixer_ChannelSetPosition( this.hBassStream, Bass.BASS_ChannelSeconds2Bytes( this.hBassStream, n位置ms * this.db周波数倍率 * this.db再生速度 / 1000.0 ), BASSMode.BASS_POS_BYTES );
1152 catch ( Exception e )
1154 Trace.TraceInformation( Path.GetFileName( this.strファイル名 ) + ": Seek error: " + e.ToString() );
1160 BASSError be = Bass.BASS_ErrorGetCode();
1161 Trace.TraceInformation( Path.GetFileName( this.strファイル名 ) + ": Seek error: " + be.ToString() );
1165 else if( this.bDirectSoundである )
1167 int n位置sample = (int) ( this.Buffer.Format.SamplesPerSecond * n位置ms * 0.001 * _db周波数倍率 * _db再生速度 ); // #30839 2013.2.24 yyagi; add _db周波数倍率 and _db再生速度
1170 this.Buffer.CurrentPlayPosition = n位置sample * this.Buffer.Format.BlockAlignment;
1172 catch ( DirectSoundException e )
1174 Trace.TraceError( "{0}: Seek error: {1}", Path.GetFileName( this.strファイル名 ), n位置ms, e.Message );
1179 public static void tすべてのサウンドを初期状態に戻す()
1181 foreach ( var sound in CSound.listインスタンス )
1183 sound.t解放する( false );
1186 public static void tすべてのサウンドを再構築する( ISoundDevice device )
1188 if( CSound.listインスタンス.Count == 0 )
1192 // サウンドを再生する際にインスタンスリストも更新されるので、配列にコピーを取っておき、リストはクリアする。
1194 var sounds = CSound.listインスタンス.ToArray();
1195 CSound.listインスタンス.Clear();
1198 // 配列に基づいて個々のサウンドを作成する。
1200 for( int i = 0; i < sounds.Length; i++ )
1202 switch( sounds[ i ].e作成方法 )
1206 string strファイル名 = sounds[ i ].strファイル名;
1207 sounds[ i ].Dispose( true, false );
1208 device.tサウンドを作成する( strファイル名, ref sounds[ i ] );
1211 #region [ WAVファイルイメージから ]
1212 case E作成方法.WAVファイルイメージから:
1213 if( sounds[ i ].bBASSサウンドである )
1215 byte[] byArrWaveファイルイメージ = sounds[ i ].byArrWAVファイルイメージ;
1216 sounds[ i ].Dispose( true, false );
1217 device.tサウンドを作成する( byArrWaveファイルイメージ, ref sounds[ i ] );
1219 else if( sounds[ i ].bDirectSoundである )
1221 byte[] byArrWaveファイルイメージ = sounds[ i ].byArrWAVファイルイメージ;
1222 var flags = sounds[ i ].DirectSoundBufferFlags;
1223 sounds[ i ].Dispose( true, false );
1224 ( (CSoundDeviceDirectSound) device ).tサウンドを作成する( byArrWaveファイルイメージ, flags, ref sounds[ i ] );
1232 #region [ Dispose-Finalizeパターン実装 ]
1234 public void Dispose()
1236 this.Dispose( true, true );
1237 GC.SuppressFinalize( this );
1239 protected void Dispose( bool bManagedも解放する, bool bインスタンス削除 )
1241 if( this.bBASSサウンドである )
1243 #region [ ASIO, WASAPI の解放 ]
1245 if ( _hTempoStream != 0 )
1247 BassMix.BASS_Mixer_ChannelRemove( this._hTempoStream );
1248 Bass.BASS_StreamFree( this._hTempoStream );
1250 BassMix.BASS_Mixer_ChannelRemove( this._hBassStream );
1251 Bass.BASS_StreamFree( this._hBassStream );
1252 this.hBassStream = -1;
1253 this._hBassStream = -1;
1254 this._hTempoStream = 0;
1261 //int freeIndex = -1;
1263 //if ( CSound.listインスタンス != null )
1265 // freeIndex = CSound.listインスタンス.IndexOf( this );
1266 // if ( freeIndex == -1 )
1268 // Debug.WriteLine( "ERR: freeIndex==-1 : Count=" + CSound.listインスタンス.Count + ", filename=" + Path.GetFileName( this.strファイル名 ) );
1272 if( this.eデバイス種別 == ESoundDeviceType.DirectSound )
1274 #region [ DirectSound の解放 ]
1276 if( this.Buffer != null )
1284 // 演奏終了後、長時間解放しないでいると、たまに AccessViolationException が発生することがある。
1286 C共通.tDisposeする( ref this.Buffer );
1292 if( this.e作成方法 == E作成方法.WAVファイルイメージから &&
1293 this.eデバイス種別 != ESoundDeviceType.DirectSound ) // DirectSound は hGC 未使用。
1295 if ( this.hGC != null && this.hGC.IsAllocated )
1298 this.hGC = default( GCHandle );
1301 if ( this.byArrWAVファイルイメージ != null )
1303 this.byArrWAVファイルイメージ = null;
1310 // CSound.listインスタンス.RemoveAt( freeIndex );
1314 // Debug.WriteLine( "FAILED to remove CSound.listインスタンス: Count=" + CSound.listインスタンス.Count + ", filename=" + Path.GetFileName( this.strファイル名 ) );
1316 bool b = CSound.listインスタンス.Remove( this ); // これだと、Clone()したサウンドのremoveに失敗する
1319 Debug.WriteLine( "FAILED to remove CSound.listインスタンス: Count=" + CSound.listインスタンス.Count + ", filename=" + Path.GetFileName( this.strファイル名 ) );
1327 this.Dispose( false, true );
1332 #region [ protected ]
1334 protected enum E作成方法 { ファイルから, WAVファイルイメージから, Unknown }
1335 protected E作成方法 e作成方法 = E作成方法.Unknown;
1336 protected ESoundDeviceType eデバイス種別 = ESoundDeviceType.Unknown;
1337 public string strファイル名 = null;
1338 protected byte[] byArrWAVファイルイメージ = null; // WAVファイルイメージ、もしくはchunkのDATA部のみ
1339 protected GCHandle hGC;
1340 protected int _hTempoStream = 0;
1341 protected int _hBassStream = -1; // ASIO, WASAPI 用
1342 protected int hBassStream = 0; // #31076 2013.4.1 yyagi; プロパティとして実装すると動作が低速になったため、
1343 // tBASSサウンドを作成する・ストリーム生成後の共通処理()のタイミングと、
1344 // 再生速度を変更したタイミングでのみ、
1345 // hBassStreamを更新するようにした。
1349 // if ( _hTempoStream != 0 && !this.bIs1倍速再生 ) // 再生速度がx1.000のときは、TempoStreamを用いないようにして高速化する
1351 // return _hTempoStream;
1355 // return _hBassStream;
1360 // _hBassStream = value;
1363 protected SoundBuffer Buffer = null; // DirectSound 用
1364 protected DirectSound DirectSound;
1365 protected int hMixer = -1; // 設計壊してゴメン Mixerに後で登録するときに使う
1371 private bool bDirectSoundである
1373 get { return ( this.eデバイス種別 == ESoundDeviceType.DirectSound ); }
1375 private bool bBASSサウンドである
1380 this.eデバイス種別 == ESoundDeviceType.ASIO ||
1381 this.eデバイス種別 == ESoundDeviceType.ExclusiveWASAPI ||
1382 this.eデバイス種別 == ESoundDeviceType.SharedWASAPI );
1385 private int _n位置 = 0;
1387 private int _n音量 = 100;
1389 private long nBytes = 0;
1390 private int n一時停止回数 = 0;
1391 private int nオリジナルの周波数 = 0;
1392 private double _db周波数倍率 = 1.0;
1393 private double _db再生速度 = 1.0;
1394 private bool bIs1倍速再生 = true;
1396 private void tBASSサウンドを作成する( string strファイル名, int hMixer, BASSFlag flags )
1398 #region [ xaとwav(RIFF chunked vorbis)に対しては専用の処理をする ]
1399 switch ( Path.GetExtension( strファイル名 ).ToLower() )
1402 tBASSサウンドを作成するXA( strファイル名, hMixer, flags );
1406 if ( tRIFFchunkedVorbisならDirectShowでDecodeする( strファイル名, ref byArrWAVファイルイメージ ) )
1408 tBASSサウンドを作成する( byArrWAVファイルイメージ, hMixer, flags );
1418 this.e作成方法 = E作成方法.ファイルから;
1419 this.strファイル名 = strファイル名;
1422 // BASSファイルストリームを作成。
1424 this._hBassStream = Bass.BASS_StreamCreateFile( strファイル名, 0, 0, flags );
1425 if( this._hBassStream == 0 )
1426 throw new Exception( string.Format( "サウンドストリームの生成に失敗しました。(BASS_StreamCreateFile)[{0}]", Bass.BASS_ErrorGetCode().ToString() ) );
1428 nBytes = Bass.BASS_ChannelGetLength( this._hBassStream );
1430 tBASSサウンドを作成する_ストリーム生成後の共通処理( hMixer );
1432 private void tBASSサウンドを作成する( byte[] byArrWAVファイルイメージ, int hMixer, BASSFlag flags )
1434 this.e作成方法 = E作成方法.WAVファイルイメージから;
1435 this.byArrWAVファイルイメージ = byArrWAVファイルイメージ;
1436 this.hGC = GCHandle.Alloc( byArrWAVファイルイメージ, GCHandleType.Pinned ); // byte[] をピン留め
1439 // BASSファイルストリームを作成。
1441 this._hBassStream = Bass.BASS_StreamCreateFile( hGC.AddrOfPinnedObject(), 0, byArrWAVファイルイメージ.Length, flags );
1442 if ( this._hBassStream == 0 )
1443 throw new Exception( string.Format( "サウンドストリームの生成に失敗しました。(BASS_StreamCreateFile)[{0}]", Bass.BASS_ErrorGetCode().ToString() ) );
1445 nBytes = Bass.BASS_ChannelGetLength( this._hBassStream );
1447 tBASSサウンドを作成する_ストリーム生成後の共通処理( hMixer );
1450 /// Decode "RIFF chunked Vorbis" to "raw wave"
1451 /// because BASE.DLL has two problems for RIFF chunked Vorbis;
1452 /// 1. time seek is not fine 2. delay occurs (about 10ms)
1454 /// <param name="strファイル名">wave filename</param>
1455 /// <param name="byArrWAVファイルイメージ">wav file image</param>
1456 /// <returns></returns>
1457 private bool tRIFFchunkedVorbisならDirectShowでDecodeする( string strファイル名, ref byte[] byArrWAVファイルイメージ )
1459 bool bファイルにVorbisコンテナが含まれている = false;
1461 #region [ ファイルがWAVかつ、Vorbisコンテナが含まれているかを調べ、それに該当するなら、DirectShowでデコードする。]
1465 using ( var ws = new WaveStream( strファイル名 ) )
1467 if ( ws.Format.FormatTag == ( WaveFormatTag ) 0x6770 || // Ogg Vorbis Mode 2+
1468 ws.Format.FormatTag == ( WaveFormatTag ) 0x6771 ) // Ogg Vorbis Mode 3+
1470 Trace.TraceInformation( Path.GetFileName( strファイル名 ) + ": RIFF chunked Vorbis. Decode to raw Wave first, to avoid BASS.DLL troubles" );
1473 CDStoWAVFileImage.t変換( strファイル名, out byArrWAVファイルイメージ );
1474 bファイルにVorbisコンテナが含まれている = true;
1478 Trace.TraceWarning( "Warning: " + Path.GetFileName( strファイル名 ) + " : RIFF chunked Vorbisのデコードに失敗しました。" );
1483 catch ( InvalidDataException )
1485 // DirectShowのデコードに失敗したら、次はACMでのデコードを試すことになるため、ここではエラーログを出さない。
1486 // Trace.TraceWarning( "Warning: " + Path.GetFileName( strファイル名 ) + " : デコードに失敗しました。" );
1488 catch ( Exception e )
1490 Trace.TraceWarning( "Warning: " + Path.GetFileName( strファイル名 ) + " : 読み込みに失敗しました。" );
1494 return bファイルにVorbisコンテナが含まれている;
1496 private void tBASSサウンドを作成するXA( string strファイル名, int hMixer, BASSFlag flags )
1498 int nPCMデータの先頭インデックス;
1499 CWin32.WAVEFORMATEX wfx;
1502 tオンメモリ方式でデコードする( strファイル名, out this.byArrWAVファイルイメージ,
1503 out nPCMデータの先頭インデックス, out totalPCMSize, out wfx, true );
1505 nBytes = totalPCMSize;
1507 this.e作成方法 = E作成方法.WAVファイルイメージから; //.ファイルから; // 再構築時はデコード後のイメージを流用する&Dispose時にhGCを解放する
1508 this.strファイル名 = strファイル名;
1509 this.hGC = GCHandle.Alloc( this.byArrWAVファイルイメージ, GCHandleType.Pinned ); // byte[] をピン留め
1511 //_cbStreamXA = new STREAMPROC( CallbackPlayingXA );
1513 // BASSファイルストリームを作成。
1515 //this.hBassStream = Bass.BASS_StreamCreate( xa.xaheader.nSamplesPerSec, xa.xaheader.nChannels, BASSFlag.BASS_STREAM_DECODE, _myStreamCreate, IntPtr.Zero );
1516 //this._hBassStream = Bass.BASS_StreamCreate( (int) wfx.nSamplesPerSec, (int) wfx.nChannels, BASSFlag.BASS_STREAM_DECODE, _cbStreamXA, IntPtr.Zero );
1518 // StreamCreate()で作成したstreamはseek不可のため、StreamCreateFile()を使う。
1519 this._hBassStream = Bass.BASS_StreamCreateFile( this.hGC.AddrOfPinnedObject(), 0L, totalPCMSize, flags );
1520 if ( this._hBassStream == 0 )
1523 throw new Exception( string.Format( "サウンドストリームの生成に失敗しました。(BASS_SampleCreate)[{0}]", Bass.BASS_ErrorGetCode().ToString() ) );
1526 nBytes = Bass.BASS_ChannelGetLength( this._hBassStream );
1529 tBASSサウンドを作成する_ストリーム生成後の共通処理( hMixer );
1533 private void tBASSサウンドを作成する_ストリーム生成後の共通処理( int hMixer )
1535 CSound管理.nStreams++;
1537 // 個々のストリームの出力をテンポ変更のストリームに入力する。テンポ変更ストリームの出力を、Mixerに出力する。
1539 // if ( CSound管理.bIsTimeStretch ) // TimeStretchのON/OFFに関わりなく、テンポ変更のストリームを生成する。後からON/OFF切り替え可能とするため。
1541 this._hTempoStream = BassFx.BASS_FX_TempoCreate( this._hBassStream, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_FX_FREESOURCE );
1542 if ( this._hTempoStream == 0 )
1545 throw new Exception( string.Format( "サウンドストリームの生成に失敗しました。(BASS_FX_TempoCreate)[{0}]", Bass.BASS_ErrorGetCode().ToString() ) );
1549 Bass.BASS_ChannelSetAttribute( this._hTempoStream, BASSAttribute.BASS_ATTRIB_TEMPO_OPTION_USE_QUICKALGO, 1f ); // 高速化(音の品質は少し落ちる)
1553 if ( _hTempoStream != 0 && !this.bIs1倍速再生 ) // 再生速度がx1.000のときは、TempoStreamを用いないようにして高速化する
1555 this.hBassStream = _hTempoStream;
1559 this.hBassStream = _hBassStream;
1562 // #32248 再生終了時に発火するcallbackを登録する (演奏終了後に再生終了するチップを非同期的にミキサーから削除するため。)
1563 _cbEndofStream = new SYNCPROC( CallbackEndofStream );
1564 Bass.BASS_ChannelSetSync( hBassStream, BASSSync.BASS_SYNC_END | BASSSync.BASS_SYNC_MIXTIME, 0, _cbEndofStream, IntPtr.Zero );
1568 CSound.listインスタンス.Add( this );
1570 // n総演奏時間の取得; DTXMania用に追加。
1571 double seconds = Bass.BASS_ChannelBytes2Seconds( this._hBassStream, nBytes );
1572 this.n総演奏時間ms = (int) ( seconds * 1000 );
1574 this.hMixer = hMixer;
1576 if ( !Bass.BASS_ChannelGetAttribute( this._hBassStream, BASSAttribute.BASS_ATTRIB_FREQ, ref freq ) )
1579 throw new Exception( string.Format( "サウンドストリームの周波数取得に失敗しました。(BASS_ChannelGetAttribute)[{0}]", Bass.BASS_ErrorGetCode().ToString() ) );
1581 this.nオリジナルの周波数 = (int) freq;
1585 //private int pos = 0;
1586 //private int CallbackPlayingXA( int handle, IntPtr buffer, int length, IntPtr user )
1588 // int bytesread = ( pos + length > Convert.ToInt32( nBytes ) ) ? Convert.ToInt32( nBytes ) - pos : length;
1590 // Marshal.Copy( byArrWAVファイルイメージ, pos, buffer, bytesread );
1591 // pos += bytesread;
1592 // if ( pos >= nBytes )
1594 // // set indicator flag
1595 // bytesread |= (int) BASSStreamProc.BASS_STREAMPROC_END;
1597 // return bytesread;
1600 /// ストリームの終端まで再生したときに呼び出されるコールバック
1602 /// <param name="handle"></param>
1603 /// <param name="channel"></param>
1604 /// <param name="data"></param>
1605 /// <param name="user"></param>
1606 private void CallbackEndofStream( int handle, int channel, int data, IntPtr user ) // #32248 2013.10.14 yyagi
1608 // Trace.TraceInformation( "Callback!(remove): " + Path.GetFileName( this.strファイル名 ) );
1609 if ( b演奏終了後も再生が続くチップである ) // 演奏終了後に再生終了するチップ音のミキサー削除は、再生終了のコールバックに引っ掛けて、自前で行う。
1610 { // そうでないものは、ミキサー削除予定時刻に削除する。
1611 tBASSサウンドをミキサーから削除する( channel );
1617 public bool tBASSサウンドをミキサーから削除する()
1619 return tBASSサウンドをミキサーから削除する( this.hBassStream );
1621 public bool tBASSサウンドをミキサーから削除する( int channel )
1623 bool b = BassMix.BASS_Mixer_ChannelRemove( channel );
1626 Interlocked.Decrement( ref CSound管理.nMixing );
1627 // Debug.WriteLine( "Removed: " + Path.GetFileName( this.strファイル名 ) + " (" + channel + ")" + " MixedStreams=" + CSound管理.nMixing );
1635 public bool tBASSサウンドをミキサーに追加する()
1637 if ( BassMix.BASS_Mixer_ChannelGetMixer( hBassStream ) == 0 )
1639 BASSFlag bf = BASSFlag.BASS_SPEAKER_FRONT | BASSFlag.BASS_MIXER_NORAMPIN | BASSFlag.BASS_MIXER_PAUSE;
1640 Interlocked.Increment( ref CSound管理.nMixing );
1642 // preloadされることを期待して、敢えてflagからはBASS_MIXER_PAUSEを外してAddChannelした上で、すぐにPAUSEする
1643 // -> ChannelUpdateでprebufferできることが分かったため、BASS_MIXER_PAUSEを使用することにした
1645 bool b1 = BassMix.BASS_Mixer_StreamAddChannel( this.hMixer, this.hBassStream, bf );
1646 //bool b2 = BassMix.BASS_Mixer_ChannelPause( this.hBassStream );
1647 t再生位置を先頭に戻す(); // StreamAddChannelの後で再生位置を戻さないとダメ。逆だと再生位置が変わらない。
1648 //Trace.TraceInformation( "Add Mixer: " + Path.GetFileName( this.strファイル名 ) + " (" + hBassStream + ")" + " MixedStreams=" + CSound管理.nMixing );
1649 Bass.BASS_ChannelUpdate( this.hBassStream, 0 ); // pre-buffer
1655 #region [ tオンメモリ方式でデコードする() ]
1656 public void tオンメモリ方式でデコードする( string strファイル名, out byte[] buffer,
1657 out int nPCMデータの先頭インデックス, out int totalPCMSize, out CWin32.WAVEFORMATEX wfx,
1658 bool bIntegrateWaveHeader )
1660 nPCMデータの先頭インデックス = 0;
1661 //int nPCMサイズbyte = (int) ( xa.xaheader.nSamples * xa.xaheader.nChannels * 2 ); // nBytes = Bass.BASS_ChannelGetLength( this.hBassStream );
1663 SoundDecoder sounddecoder;
1665 if ( String.Compare( Path.GetExtension( strファイル名 ), ".xa", true ) == 0 )
1667 sounddecoder = new Cxa();
1669 else if ( String.Compare( Path.GetExtension( strファイル名 ), ".ogg", true ) == 0 )
1671 sounddecoder = new Cogg();
1673 else if ( String.Compare( Path.GetExtension( strファイル名 ), ".mp3", true ) == 0 )
1675 sounddecoder = new Cmp3();
1679 throw new NotImplementedException();
1682 if ( !File.Exists( strファイル名 ) )
1684 throw new Exception( string.Format( "ファイルが見つかりませんでした。({0})", strファイル名 ) );
1686 int nHandle = sounddecoder.Open( strファイル名 );
1689 throw new Exception( string.Format( "Open() に失敗しました。({0})({1})", nHandle, strファイル名 ) );
1691 wfx = new CWin32.WAVEFORMATEX();
1692 if ( sounddecoder.GetFormat( nHandle, ref wfx ) < 0 )
1694 sounddecoder.Close( nHandle );
1695 throw new Exception( string.Format( "GetFormat() に失敗しました。({0})", strファイル名 ) );
1697 //totalPCMSize = (int) sounddecoder.nTotalPCMSize; // tデコード後のサイズを調べる()で既に取得済みの値を流用する。ms単位の高速化だが、チップ音がたくさんあると塵積で結構効果がある
1698 totalPCMSize = (int) sounddecoder.GetTotalPCMSize( nHandle );
1699 if ( totalPCMSize == 0 )
1701 sounddecoder.Close( nHandle );
1702 throw new Exception( string.Format( "GetTotalPCMSize() に失敗しました。({0})", strファイル名 ) );
1704 totalPCMSize += ( ( totalPCMSize % 2 ) != 0 ) ? 1 : 0;
1705 int wavheadersize = ( bIntegrateWaveHeader ) ? 44 : 0;
1706 byte[] buffer_rawdata = new byte[ totalPCMSize ];
1707 buffer = new byte[ wavheadersize + totalPCMSize ];
1708 GCHandle handle = GCHandle.Alloc( buffer_rawdata, GCHandleType.Pinned );
1711 if ( sounddecoder.Decode( nHandle, handle.AddrOfPinnedObject(), (uint) totalPCMSize, 0 ) < 0 )
1714 throw new Exception( string.Format( "デコードに失敗しました。({0})", strファイル名 ) );
1716 if ( bIntegrateWaveHeader )
1720 int wfx拡張領域_Length = 0;
1721 var ms = new MemoryStream();
1722 var bw = new BinaryWriter( ms );
1723 bw.Write( new byte[] { 0x52, 0x49, 0x46, 0x46 } ); // 'RIFF'
1724 bw.Write( (UInt32) totalPCMSize + 44 - 8 ); // ファイルサイズ - 8 [byte];今は不明なので後で上書きする。
1725 bw.Write( new byte[] { 0x57, 0x41, 0x56, 0x45 } ); // 'WAVE'
1726 bw.Write( new byte[] { 0x66, 0x6D, 0x74, 0x20 } ); // 'fmt '
1727 bw.Write( (UInt32) ( 16 + ( ( wfx拡張領域_Length > 0 ) ? ( 2/*sizeof(WAVEFORMATEX.cbSize)*/ + wfx拡張領域_Length ) : 0 ) ) ); // fmtチャンクのサイズ[byte]
1728 bw.Write( (UInt16) wfx.wFormatTag ); // フォーマットID(リニアPCMなら1)
1729 bw.Write( (UInt16) wfx.nChannels ); // チャンネル数
1730 bw.Write( (UInt32) wfx.nSamplesPerSec ); // サンプリングレート
1731 bw.Write( (UInt32) wfx.nAvgBytesPerSec ); // データ速度
1732 bw.Write( (UInt16) wfx.nBlockAlign ); // ブロックサイズ
1733 bw.Write( (UInt16) wfx.wBitsPerSample ); // サンプルあたりのビット数
1734 //if ( wfx拡張領域_Length > 0 )
1736 // bw.Write( (UInt16) wfx拡張領域.Length ); // 拡張領域のサイズ[byte]
1737 // bw.Write( wfx拡張領域 ); // 拡張データ
1739 bw.Write( new byte[] { 0x64, 0x61, 0x74, 0x61 } ); // 'data'
1740 //int nDATAチャンクサイズ位置 = (int) ms.Position;
1741 bw.Write( (UInt32) totalPCMSize ); // dataチャンクのサイズ[byte]
1743 byte[] bs = ms.ToArray();
1748 for ( int i = 0; i < bs.Length; i++ )
1750 buffer[ i ] = bs[ i ];
1753 int s = ( bIntegrateWaveHeader ) ? 44 : 0;
1754 for ( int i = 0; i < totalPCMSize; i++ )
1756 buffer[ i + s ] = buffer_rawdata[ i ];
1758 totalPCMSize += wavheadersize;
1759 nPCMデータの先頭インデックス = wavheadersize;
1764 sounddecoder.Close( nHandle );
1765 sounddecoder = null;