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 SharpDX.DirectSound;
11 using SharpDX.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 // if ( SoundDeviceType == ESoundDeviceType.ExclusiveWASAPI || SoundDeviceType == ESoundDeviceType.ASIO )
55 // return Bass.BASS_GetConfig(BASSConfig.BASS_CONFIG_GVOL_STREAM ) / 100;
64 // if ( SoundDeviceType == ESoundDeviceType.ExclusiveWASAPI )
66 // // LINEARでなくWINDOWS(2)を使う必要があるが、exclusive時は使用不可、またデバイス側が対応してないと使用不可
67 // bool b = BassWasapi.BASS_WASAPI_SetVolume( BASSWASAPIVolume.BASS_WASAPI_CURVE_LINEAR, value / 100.0f );
70 // BASSError be = Bass.BASS_ErrorGetCode();
71 // Trace.TraceInformation( "WASAPI Master Volume Set Error: " + be.ToString() );
77 // if ( SoundDeviceType == ESoundDeviceType.ExclusiveWASAPI || SoundDeviceType == ESoundDeviceType.ASIO )
79 // bool b = Bass.BASS_SetConfig(BASSConfig.BASS_CONFIG_GVOL_STREAM, value * 100 );
82 // BASSError be = Bass.BASS_ErrorGetCode();
83 // Trace.TraceInformation( "Master Volume Set Error: " + be.ToString() );
89 // if ( SoundDeviceType == ESoundDeviceType.ExclusiveWASAPI || SoundDeviceType == ESoundDeviceType.ASIO )
91 // var nodes = new BASS_MIXER_NODE[ 1 ] { new BASS_MIXER_NODE( 0, (float) value ) };
92 // BassMix.BASS_Mixer_ChannelSetEnvelope( SoundDevice.hMixer, BASSMIXEnvelope.BASS_MIXER_ENV_VOL, nodes );
97 SoundDevice.nMasterVolume = value;
98 _nMasterVolume = value;
103 ///// BASS時、mp3をストリーミング再生せずに、デコードしたraw wavをオンメモリ再生する場合はtrueにする。
104 ///// 特殊なmp3を使用時はシークが乱れるので、必要に応じてtrueにすること。(Config.iniのNoMP3Streamingで設定可能。)
105 ///// ただし、trueにすると、その分再生開始までの時間が長くなる。
107 //public static bool bIsMP3DecodeByWindowsCodec = false;
109 public static int nMixing = 0;
110 public int GetMixingStreams()
114 public static int nStreams = 0;
115 public int GetStreams()
119 #region [ WASAPI/ASIO/DirectSound設定値 ]
121 /// <para>WASAPI 排他モード出力における再生遅延[ms](の希望値)。最終的にはこの数値を基にドライバが決定する)。</para>
122 /// <para>0以下の値を指定すると、この数値はWASAPI初期化時に自動設定する。正数を指定すると、その値を設定しようと試みる。</para>
124 public static int SoundDelayExclusiveWASAPI = 0; // SSTでは、50ms
125 public int GetSoundExclusiveWASAPI()
127 return SoundDelayExclusiveWASAPI;
129 public void SetSoundDelayExclusiveWASAPI( int value )
131 SoundDelayExclusiveWASAPI = value;
134 /// <para>WASAPI 共有モード出力における再生遅延[ms]。ユーザが決定する。</para>
136 public static int SoundDelaySharedWASAPI = 10;
138 /// <para>排他WASAPIバッファの更新間隔。出力間隔ではないので注意。</para>
139 /// <para>→ 自動設定されるのでSoundDelay よりも小さい値であること。(小さすぎる場合はBASSによって自動修正される。)</para>
141 public static int SoundUpdatePeriodExclusiveWASAPI = 6;
143 /// <para>共有WASAPIバッファの更新間隔。出力間隔ではないので注意。</para>
144 /// <para>SoundDelay よりも小さい値であること。(小さすぎる場合はBASSによって自動修正される。)</para>
146 public static int SoundUpdatePeriodSharedWASAPI = 3;
148 /// WASAPI利用時に、サウンドバッファの更新をevent drivenにするか、pollingにするかの設定。
149 /// デフォルト設定はpolling。event drivenにすることで、よりラグを小さくできるが、CPU負荷は若干上昇する。
151 /// なおこれをtrueにすると、SoundUpdatePeriodExclusiveWASAPIの設定は無視される。
153 public static bool bSoundUpdateByEventWASAPI = false;
156 ///// <para>ASIO 出力における再生遅延[ms](の希望値)。最終的にはこの数値を基にドライバが決定する)。</para>
158 //public static int SoundDelayASIO = 0; // SSTでは50ms。0にすると、デバイスの設定値をそのまま使う。
160 /// <para>ASIO 出力におけるバッファサイズ。</para>
162 public static int SoundDelayASIO = 0; // 0にすると、デバイスの設定値をそのまま使う。
163 public int GetSoundDelayASIO()
165 return SoundDelayASIO;
167 public void SetSoundDelayASIO(int value)
169 SoundDelayASIO = value;
171 public static int ASIODevice = 0;
172 public int GetASIODevice()
176 public void SetASIODevice(int value)
181 /// <para>DirectSound 出力における再生遅延[ms]。ユーザが決定する。</para>
183 public static int SoundDelayDirectSound = 100;
185 public long GetSoundDelay()
187 if ( SoundDevice != null )
189 return SoundDevice.n実バッファサイズms;
203 /// <param name="handle"></param>
204 public CSound管理( IntPtr handle ) // #30803 従来のコンストラクタ相当のI/Fを追加。(DTXC用)
206 WindowHandle = handle;
209 t初期化( ESoundDeviceType.DirectSound, 0, 0, 0 );
214 /// <param name="handle"></param>
215 /// <param name="soundDeviceType"></param>
216 /// <param name="nSoundDelayExclusiveWASAPI"></param>
217 /// <param name="nSoundDelayASIO"></param>
218 /// <param name="nASIODevice"></param>
219 public CSound管理( IntPtr handle, ESoundDeviceType soundDeviceType,
220 int nSoundDelayExclusiveWASAPI, bool _bSoundUpdateByEventWASAPI,
221 int nSoundDelayASIO, int nASIODevice,
224 WindowHandle = handle;
226 //bUseOSTimer = false;
227 t初期化( soundDeviceType, nSoundDelayExclusiveWASAPI, _bSoundUpdateByEventWASAPI, nSoundDelayASIO, nASIODevice, _bUseOSTimer );
229 public void Dispose()
234 //public static void t初期化()
236 // t初期化( ESoundDeviceType.DirectSound, 0, 0, 0 );
239 public void t初期化( ESoundDeviceType soundDeviceType, int _nSoundDelayExclusiveWASAPI, int _nSoundDelayASIO, int _nASIODevice, IntPtr handle )
241 //if ( !bInitialized )
243 WindowHandle = handle;
244 t初期化( soundDeviceType, _nSoundDelayExclusiveWASAPI, _nSoundDelayASIO, _nASIODevice );
245 //bInitialized = true;
248 public void t初期化( ESoundDeviceType soundDeviceType, int _nSoundDelayExclusiveWASAPI, int _nSoundDelayASIO, int _nASIODevice )
250 t初期化( soundDeviceType, _nSoundDelayExclusiveWASAPI, false, _nSoundDelayASIO, _nASIODevice, false );
253 public void t初期化( ESoundDeviceType soundDeviceType,
254 int _nSoundDelayExclusiveWASAPI, bool _bSoundUpdateByEventWASAPI,
255 int _nSoundDelayASIO, int _nASIODevice,
258 //SoundDevice = null; // 後で再初期化することがあるので、null初期化はコンストラクタに回す
259 rc演奏用タイマ = null; // Global.Bass 依存(つまりユーザ依存)
262 SoundDelayExclusiveWASAPI = _nSoundDelayExclusiveWASAPI;
263 SoundDelayASIO = _nSoundDelayASIO;
264 ASIODevice = _nASIODevice;
265 bUseOSTimer = _bUseOSTimer;
266 bSoundUpdateByEventWASAPI = _bSoundUpdateByEventWASAPI;
268 ESoundDeviceType[] ESoundDeviceTypes = new ESoundDeviceType[ 5 ]
270 ESoundDeviceType.ExclusiveWASAPI,
271 ESoundDeviceType.ASIO,
272 ESoundDeviceType.SharedWASAPI,
273 ESoundDeviceType.DirectSound,
274 ESoundDeviceType.Unknown
278 switch ( soundDeviceType )
280 case ESoundDeviceType.ExclusiveWASAPI:
283 case ESoundDeviceType.ASIO:
286 case ESoundDeviceType.SharedWASAPI:
289 case ESoundDeviceType.DirectSound:
296 for ( SoundDeviceType = ESoundDeviceTypes[ n初期デバイス ]; ; SoundDeviceType = ESoundDeviceTypes[ ++n初期デバイス ] )
300 t現在のユーザConfigに従ってサウンドデバイスとすべての既存サウンドを再構築する();
303 catch ( Exception e )
305 Trace.TraceInformation( e.Message );
306 if ( ESoundDeviceTypes[ n初期デバイス ] == ESoundDeviceType.Unknown )
308 Trace.TraceError( string.Format( "サウンドデバイスの初期化に失敗しました。" ) );
313 if ( soundDeviceType == ESoundDeviceType.ExclusiveWASAPI || soundDeviceType == ESoundDeviceType.ASIO || soundDeviceType == ESoundDeviceType.SharedWASAPI )
315 //Bass.BASS_SetConfig( BASSConfig.BASS_CONFIG_UPDATETHREADS, 4 );
316 //Bass.BASS_SetConfig( BASSConfig.BASS_CONFIG_UPDATEPERIOD, 0 );
318 Trace.TraceInformation( "BASS_CONFIG_UpdatePeriod=" + Bass.BASS_GetConfig( BASSConfig.BASS_CONFIG_UPDATEPERIOD ) );
319 Trace.TraceInformation( "BASS_CONFIG_UpdateThreads=" + Bass.BASS_GetConfig( BASSConfig.BASS_CONFIG_UPDATETHREADS ) );
323 public void tDisableUpdateBufferAutomatically()
325 //Bass.BASS_SetConfig( BASSConfig.BASS_CONFIG_UPDATETHREADS, 0 );
326 //Bass.BASS_SetConfig( BASSConfig.BASS_CONFIG_UPDATEPERIOD, 0 );
328 //Trace.TraceInformation( "BASS_CONFIG_UpdatePeriod=" + Bass.BASS_GetConfig( BASSConfig.BASS_CONFIG_UPDATEPERIOD ) );
329 //Trace.TraceInformation( "BASS_CONFIG_UpdateThreads=" + Bass.BASS_GetConfig( BASSConfig.BASS_CONFIG_UPDATETHREADS ) );
333 public static void t終了()
335 C共通.tDisposeする( SoundDevice ); SoundDevice = null;
336 C共通.tDisposeする( ref rc演奏用タイマ ); // Global.Bass を解放した後に解放すること。(Global.Bass で参照されているため)
340 public static void t現在のユーザConfigに従ってサウンドデバイスとすべての既存サウンドを再構築する()
342 #region [ すでにサウンドデバイスと演奏タイマが構築されていれば解放する。]
344 if ( SoundDevice != null )
346 // すでに生成済みのサウンドがあれば初期状態に戻す。
348 CSound.tすべてのサウンドを初期状態に戻す(); // リソースは解放するが、CSoundのインスタンスは残す。
351 // サウンドデバイスと演奏タイマを解放する。
353 C共通.tDisposeする( SoundDevice ); SoundDevice = null;
354 C共通.tDisposeする( ref rc演奏用タイマ ); // Global.SoundDevice を解放した後に解放すること。(Global.SoundDevice で参照されているため)
359 #region [ 新しいサウンドデバイスを構築する。]
361 switch ( SoundDeviceType )
363 case ESoundDeviceType.ExclusiveWASAPI:
364 SoundDevice = new CSoundDeviceWASAPI( CSoundDeviceWASAPI.Eデバイスモード.排他, SoundDelayExclusiveWASAPI, SoundUpdatePeriodExclusiveWASAPI );
367 case ESoundDeviceType.SharedWASAPI:
368 SoundDevice = new CSoundDeviceWASAPI( CSoundDeviceWASAPI.Eデバイスモード.共有, SoundDelaySharedWASAPI, SoundUpdatePeriodSharedWASAPI );
371 case ESoundDeviceType.ASIO:
372 SoundDevice = new CSoundDeviceASIO( SoundDelayASIO, ASIODevice );
375 case ESoundDeviceType.DirectSound:
376 SoundDevice = new CSoundDeviceDirectSound( WindowHandle, SoundDelayDirectSound, bUseOSTimer );
380 throw new Exception( string.Format( "未対応の SoundDeviceType です。[{0}]", SoundDeviceType.ToString() ) );
384 #region [ 新しい演奏タイマを構築する。]
386 rc演奏用タイマ = new CSoundTimer( SoundDevice );
390 SoundDevice.nMasterVolume = _nMasterVolume; // サウンドデバイスに対して、マスターボリュームを再設定する
392 CSound.tすべてのサウンドを再構築する( SoundDevice ); // すでに生成済みのサウンドがあれば作り直す。
394 public CSound tサウンドを生成する( string filename )
396 if ( SoundDeviceType == ESoundDeviceType.Unknown )
398 throw new Exception( string.Format( "未対応の SoundDeviceType です。[{0}]", SoundDeviceType.ToString() ) );
400 return SoundDevice.tサウンドを作成する( filename );
403 private static DateTime lastUpdateTime = DateTime.MinValue;
404 public void t再生中の処理をする( object o ) // #26122 2011.9.1 yyagi; delegate経由の呼び出し用
408 public void t再生中の処理をする()
410 //★★★★★★★★★★★★★★★★★★★★★ダミー★★★★★★★★★★★★★★★★★★
411 // Debug.Write( "再生中の処理をする()" );
412 //DateTime now = DateTime.Now;
413 //TimeSpan ts = now - lastUpdateTime;
414 //if ( ts.Milliseconds > 5 )
416 // bool b = Bass.BASS_Update( 100 * 2 );
417 // lastUpdateTime = DateTime.Now;
420 // Trace.TraceInformation( "BASS_UPdate() failed: " + Bass.BASS_ErrorGetCode().ToString() );
425 public void tサウンドを破棄する( CSound csound )
427 csound.t解放する( true ); // インスタンスは存続→破棄にする。
431 public float GetCPUusage()
434 switch ( SoundDeviceType )
436 case ESoundDeviceType.ExclusiveWASAPI:
437 case ESoundDeviceType.SharedWASAPI:
438 f = BassWasapi.BASS_WASAPI_GetCPU();
440 case ESoundDeviceType.ASIO:
441 f = BassAsio.BASS_ASIO_GetCPU();
443 case ESoundDeviceType.DirectSound:
453 public string GetCurrentSoundDeviceType()
455 switch ( SoundDeviceType )
457 case ESoundDeviceType.ExclusiveWASAPI:
458 return "WASAPI(Exclusive)";
459 case ESoundDeviceType.SharedWASAPI:
460 return "WASAPI(Shared)";
461 case ESoundDeviceType.ASIO:
463 case ESoundDeviceType.DirectSound:
464 return "DirectSound";
470 public void AddMixer( CSound cs, double db再生速度, bool _b演奏終了後も再生が続くチップである )
472 cs.b演奏終了後も再生が続くチップである = _b演奏終了後も再生が続くチップである;
474 cs.tBASSサウンドをミキサーに追加する();
476 public void AddMixer( CSound cs, double db再生速度 )
479 cs.tBASSサウンドをミキサーに追加する();
481 public void AddMixer( CSound cs )
483 cs.tBASSサウンドをミキサーに追加する();
485 public void RemoveMixer( CSound cs )
487 cs.tBASSサウンドをミキサーから削除する();
492 // CSound は、サウンドデバイスが変更されたときも、インスタンスを再作成することなく、新しいデバイスで作り直せる必要がある。
493 // そのため、デバイスごとに別のクラスに分割するのではなく、1つのクラスに集約するものとする。
495 public class CSound : IDisposable, ICloneable
497 #region [ DTXMania用拡張 ]
503 public int nサウンドバッファサイズ // 取りあえず0固定★★★★★★★★★★★★★★★★★★★★
507 public bool bストリーム再生する // 取りあえずfalse固定★★★★★★★★★★★★★★★★★★★★
508 // trueにすると同一チップ音の多重再生で問題が出る(4POLY音源として動かない)
510 get { return false; }
512 public double db周波数倍率
520 if ( _db周波数倍率 != value )
525 Bass.BASS_ChannelSetAttribute( this.hBassStream, BASSAttribute.BASS_ATTRIB_FREQ, ( float ) ( _db周波数倍率 * _db再生速度 * nオリジナルの周波数 ) );
529 // if ( b再生中 ) // #30838 2012.2.24 yyagi (delete b再生中)
531 this.Buffer.Frequency = ( int ) ( _db周波数倍率 * _db再生速度 * nオリジナルの周波数 );
545 if ( _db再生速度 != value )
548 bIs1倍速再生 = ( _db再生速度 == 1.000f );
551 if ( _hTempoStream != 0 && !this.bIs1倍速再生 ) // 再生速度がx1.000のときは、TempoStreamを用いないようにして高速化する
553 this.hBassStream = _hTempoStream;
557 this.hBassStream = _hBassStream;
560 if ( CSound管理.bIsTimeStretch )
562 Bass.BASS_ChannelSetAttribute( this.hBassStream, BASSAttribute.BASS_ATTRIB_TEMPO, (float) ( db再生速度 * 100 - 100 ) );
563 //double seconds = Bass.BASS_ChannelBytes2Seconds( this.hTempoStream, nBytes );
564 //this.n総演奏時間ms = (int) ( seconds * 1000 );
568 Bass.BASS_ChannelSetAttribute( this.hBassStream, BASSAttribute.BASS_ATTRIB_FREQ, ( float ) ( _db周波数倍率 * _db再生速度 * nオリジナルの周波数 ) );
573 // if ( b再生中 ) // #30838 2012.2.24 yyagi (delete b再生中)
575 this.Buffer.Frequency = ( int ) ( _db周波数倍率 * _db再生速度 * nオリジナルの周波数 );
583 public bool b演奏終了後も再生が続くチップである = false; // これがtrueなら、本サウンドの再生終了のコールバック時に自動でミキサーから削除する
585 //private STREAMPROC _cbStreamXA; // make it global, so that the GC can not remove it
586 private SYNCPROC _cbEndofStream; // ストリームの終端まで再生されたときに呼び出されるコールバック
587 // private WaitCallback _cbRemoveMixerChannel;
590 /// <para>0:最小~100:原音</para>
596 if( this.bBASSサウンドである )
599 if ( !Bass.BASS_ChannelGetAttribute( this.hBassStream, BASSAttribute.BASS_ATTRIB_VOL, ref f音量 ) )
600 //if ( BassMix.BASS_Mixer_ChannelGetEnvelopePos( this.hBassStream, BASSMIXEnvelope.BASS_MIXER_ENV_VOL, ref f音量 ) == -1 )
602 return (int) ( f音量 * 100 );
604 else if( this.bDirectSoundである )
612 if( this.bBASSサウンドである )
614 float f音量 = Math.Min( Math.Max( value, 0 ), 100 ) / 100.0f; // 0~100 → 0.0~1.0
615 //var nodes = new BASS_MIXER_NODE[ 1 ] { new BASS_MIXER_NODE( 0, f音量 ) };
616 //BassMix.BASS_Mixer_ChannelSetEnvelope( this.hBassStream, BASSMIXEnvelope.BASS_MIXER_ENV_VOL, nodes );
617 Bass.BASS_ChannelSetAttribute( this.hBassStream, BASSAttribute.BASS_ATTRIB_VOL, f音量 );
620 else if( this.bDirectSoundである )
626 this._n音量db = -10000;
630 this._n音量db = (int) ( ( 20.0 * Math.Log10( ( (double) this._n音量 ) / 100.0 ) ) * 100.0 );
633 this.Buffer.Volume = this._n音量db;
639 /// <para>左:-100~中央:0~100:右。set のみ。</para>
645 if( this.bBASSサウンドである )
648 if ( !Bass.BASS_ChannelGetAttribute( this.hBassStream, BASSAttribute.BASS_ATTRIB_PAN, ref f位置 ) )
649 //if( BassMix.BASS_Mixer_ChannelGetEnvelopePos( this.hBassStream, BASSMIXEnvelope.BASS_MIXER_ENV_PAN, ref f位置 ) == -1 )
651 return (int) ( f位置 * 100 );
653 else if( this.bDirectSoundである )
661 if( this.bBASSサウンドである )
663 float f位置 = Math.Min( Math.Max( value, -100 ), 100 ) / 100.0f; // -100~100 → -1.0~1.0
664 //var nodes = new BASS_MIXER_NODE[ 1 ] { new BASS_MIXER_NODE( 0, f位置 ) };
665 //BassMix.BASS_Mixer_ChannelSetEnvelope( this.hBassStream, BASSMIXEnvelope.BASS_MIXER_ENV_PAN, nodes );
666 Bass.BASS_ChannelSetAttribute( this.hBassStream, BASSAttribute.BASS_ATTRIB_PAN, f位置 );
668 else if( this.bDirectSoundである )
670 this._n位置 = Math.Min( Math.Max( -100, value ), 100 ); // -100~100
676 else if( this._n位置 == -100 )
678 this._n位置db = -10000;
680 else if( this._n位置 == 100 )
684 else if( this._n位置 < 0 )
686 this._n位置db = (int) ( ( 20.0 * Math.Log10( ( (double) ( this._n位置 + 100 ) ) / 100.0 ) ) * 100.0 );
690 this._n位置db = (int) ( ( -20.0 * Math.Log10( ( (double) ( 100 - this._n位置 ) ) / 100.0 ) ) * 100.0 );
693 this.Buffer.Pan = this._n位置db;
699 /// <para>DirectSoundのセカンダリバッファ。</para>
701 //public SecondarySoundBuffer DirectSoundBuffer
702 public SoundBuffer DirectSoundBuffer
704 get { return this.Buffer; }
708 /// <para>DirectSoundのセカンダリバッファ作成時のフラグ。</para>
710 public BufferFlags DirectSoundBufferFlags
717 /// <para>全インスタンスリスト。</para>
718 /// <para>~を作成する() で追加され、t解放する() or Dispose() で解放される。</para>
720 public static List<CSound> listインスタンス = new List<CSound>();
722 public static void ShowAllCSoundFiles()
725 foreach ( CSound cs in listインスタンス )
727 Debug.WriteLine( i++.ToString( "d3" ) + ": " + Path.GetFileName( cs.strファイル名 ) );
737 this.DirectSoundBufferFlags = CSoundDeviceDirectSound.DefaultFlags;
738 // this._cbRemoveMixerChannel = new WaitCallback( RemoveMixerChannelLater );
739 this._hBassStream = -1;
740 this._hTempoStream = 0;
743 public object Clone()
745 if ( !bDirectSoundである )
747 throw new NotImplementedException();
749 CSound clone = (CSound) MemberwiseClone(); // これだけだとCY連打が途切れる&タイトルに戻る際にNullRef例外発生
750 clone.Buffer = this.DirectSound.DuplicateSoundBuffer( this.Buffer );
752 // CSound.listインスタンス.Add( this ); // インスタンスリストに登録。
753 // 本来これを加えるべきだが、Add後Removeできなくなっている。Clone()の仕方の問題であろう。
757 public void tASIOサウンドを作成する( string strファイル名, int hMixer )
759 this.tBASSサウンドを作成する( strファイル名, hMixer, BASSFlag.BASS_STREAM_DECODE );
760 this.eデバイス種別 = ESoundDeviceType.ASIO; // 作成後に設定する。(作成に失敗してると例外発出されてここは実行されない)
762 public void tASIOサウンドを作成する( byte[] byArrWAVファイルイメージ, int hMixer )
764 this.tBASSサウンドを作成する( byArrWAVファイルイメージ, hMixer, BASSFlag.BASS_STREAM_DECODE );
765 this.eデバイス種別 = ESoundDeviceType.ASIO; // 作成後に設定する。(作成に失敗してると例外発出されてここは実行されない)
767 public void tWASAPIサウンドを作成する( string strファイル名, int hMixer, ESoundDeviceType eデバイス種別 )
769 this.tBASSサウンドを作成する( strファイル名, hMixer, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_FLOAT );
770 this.eデバイス種別 = eデバイス種別; // 作成後に設定する。(作成に失敗してると例外発出されてここは実行されない)
772 public void tWASAPIサウンドを作成する( byte[] byArrWAVファイルイメージ, int hMixer, ESoundDeviceType eデバイス種別 )
774 this.tBASSサウンドを作成する( byArrWAVファイルイメージ, hMixer, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_FLOAT );
775 this.eデバイス種別 = eデバイス種別; // 作成後に設定する。(作成に失敗してると例外発出されてここは実行されない)
777 public void tDirectSoundサウンドを作成する( string strファイル名, DirectSound DirectSound )
779 this.e作成方法 = E作成方法.ファイルから;
780 this.strファイル名 = strファイル名;
781 if ( String.Compare( Path.GetExtension( strファイル名 ), ".xa", true ) == 0 ||
782 String.Compare( Path.GetExtension( strファイル名 ), ".mp3", true ) == 0 ||
783 String.Compare( Path.GetExtension( strファイル名 ), ".ogg", true ) == 0 ) // caselessで文字列比較
785 tDirectSoundサウンドを作成するXaOggMp3( strファイル名, DirectSound );
789 // すべてのファイルを DirectShow でデコードすると時間がかかるので、ファイルが WAV かつ PCM フォーマットでない場合のみ DirectShow でデコードする。
791 byte[] byArrWAVファイルイメージ = null;
792 bool bファイルがWAVかつPCMフォーマットである = true;
795 #region [ ファイルがWAVかつPCMフォーマットか否か調べる。]
799 using( var ws = new SoundStream( new FileStream( strファイル名, FileMode.Open ) ) )
801 if( ws.Format.Encoding != WaveFormatEncoding.Pcm )
802 bファイルがWAVかつPCMフォーマットである = false;
807 bファイルがWAVかつPCMフォーマットである = false;
812 if ( bファイルがWAVかつPCMフォーマットである )
814 #region [ ファイルを読み込んで byArrWAVファイルイメージへ格納。]
816 var fs = File.Open( strファイル名, FileMode.Open, FileAccess.Read );
817 var br = new BinaryReader( fs );
819 byArrWAVファイルイメージ = new byte[ fs.Length ];
820 br.Read( byArrWAVファイルイメージ, 0, (int) fs.Length );
829 #region [ DirectShow でデコード変換し、 byArrWAVファイルイメージへ格納。]
831 CDStoWAVFileImage.t変換( strファイル名, out byArrWAVファイルイメージ );
839 this.tDirectSoundサウンドを作成する( byArrWAVファイルイメージ, DirectSound );
841 public void tDirectSoundサウンドを作成するXaOggMp3( string strファイル名, DirectSound DirectSound )
843 this.e作成方法 = E作成方法.ファイルから;
844 this.strファイル名 = strファイル名;
847 int nPCMデータの先頭インデックス = 0;
848 // int nPCMサイズbyte = (int) ( xa.xaheader.nSamples * xa.xaheader.nChannels * 2 ); // nBytes = Bass.BASS_ChannelGetLength( this.hBassStream );
851 CWin32.WAVEFORMATEX cw32wfx;
852 tオンメモリ方式でデコードする( strファイル名, out this.byArrWAVファイルイメージ,
853 out nPCMデータの先頭インデックス, out nPCMサイズbyte, out cw32wfx, false );
854 WaveFormat wfx = WaveFormat.CreateCustomFormat( WaveFormatEncoding.Pcm, (int) cw32wfx.nSamplesPerSec, (int) cw32wfx.nChannels, (int) cw32wfx.nAvgBytesPerSec, (int) cw32wfx.nBlockAlign, (int) cw32wfx.wBitsPerSample );
856 // セカンダリバッファを作成し、PCMデータを書き込む。
857 tDirectSoundサウンドを作成する_セカンダリバッファの作成とWAVデータ書き込み
858 ( ref this.byArrWAVファイルイメージ, DirectSound, CSoundDeviceDirectSound.DefaultFlags, wfx,
859 nPCMサイズbyte, nPCMデータの先頭インデックス );
862 public void tDirectSoundサウンドを作成する( byte[] byArrWAVファイルイメージ, DirectSound DirectSound )
864 this.tDirectSoundサウンドを作成する( byArrWAVファイルイメージ, DirectSound, CSoundDeviceDirectSound.DefaultFlags );
866 public void tDirectSoundサウンドを作成する( byte[] byArrWAVファイルイメージ, DirectSound DirectSound, BufferFlags flags )
868 if( this.e作成方法 == E作成方法.Unknown )
869 this.e作成方法 = E作成方法.WAVファイルイメージから;
871 WaveFormat wfx = null;
872 int nPCMデータの先頭インデックス = -1;
873 int nPCMサイズbyte = -1;
875 #region [ byArrWAVファイルイメージ[] から上記3つのデータを取得。]
877 var ms = new MemoryStream( byArrWAVファイルイメージ );
878 var br = new BinaryReader( ms );
884 if( br.ReadUInt32() != 0x46464952 )
885 throw new InvalidDataException( "RIFFファイルではありません。" );
889 if( br.ReadUInt32() != 0x45564157 )
890 throw new InvalidDataException( "WAVEファイルではありません。" );
893 while( ( ms.Position + 8 ) < ms.Length ) // +8 は、チャンク名+チャンクサイズ。残り8バイト未満ならループ終了。
895 uint chunkName = br.ReadUInt32();
898 if( chunkName == 0x20746D66 )
900 long chunkSize = (long) br.ReadUInt32();
902 var tag = (WaveFormatEncoding) br.ReadUInt16();
903 var channels = br.ReadInt16();
904 var samplesPerSecond = br.ReadInt32();
905 var averageBytesPerSecond = br.ReadInt32();
906 var blockAlignment = br.ReadInt16();
907 var bitsPerSample = br.ReadInt16();
909 if( tag == WaveFormatEncoding.Pcm )
911 wfx = WaveFormat.CreateCustomFormat( tag, samplesPerSecond, channels, averageBytesPerSecond, blockAlignment, bitsPerSample );
913 else if( tag == WaveFormatEncoding.Extensible )
915 wfx = SharpDX.Multimedia.WaveFormatExtensible.CreateCustomFormat( // このクラスは WaveFormat を継承している。
916 tag, samplesPerSecond, channels, averageBytesPerSecond, blockAlignment, bitsPerSample );
919 throw new InvalidDataException( string.Format( "未対応のWAVEフォーマットタグです。(Tag:{0})", tag.ToString() ) );
921 long nフォーマットサイズbyte = 16;
923 if( wfx.Encoding == WaveFormatEncoding.Extensible )
925 br.ReadUInt16(); // 拡張領域サイズbyte
926 var wfxEx = (SharpDX.Multimedia.WaveFormatExtensible) wfx;
927 /*wfxEx.ValidBitsPerSample = */br.ReadInt16(); // 対応するメンバがない?
928 wfxEx.ChannelMask = (Speakers) br.ReadInt32();
929 wfxEx.GuidSubFormat = new Guid( br.ReadBytes( 16 ) ); // GUID は 16byte (128bit)
931 nフォーマットサイズbyte += 24;
934 ms.Seek( chunkSize - nフォーマットサイズbyte, SeekOrigin.Current );
939 else if( chunkName == 0x61746164 )
941 nPCMサイズbyte = br.ReadInt32();
942 nPCMデータの先頭インデックス = (int) ms.Position;
944 ms.Seek( nPCMサイズbyte, SeekOrigin.Current );
951 long chunkSize = (long) br.ReadUInt32();
952 ms.Seek( chunkSize, SeekOrigin.Current );
958 throw new InvalidDataException( "fmt チャンクが存在しません。不正なサウンドデータです。" );
959 if( nPCMサイズbyte < 0 )
960 throw new InvalidDataException( "data チャンクが存在しません。不正なサウンドデータです。" );
971 // セカンダリバッファを作成し、PCMデータを書き込む。
972 tDirectSoundサウンドを作成する_セカンダリバッファの作成とWAVデータ書き込み(
973 ref byArrWAVファイルイメージ, DirectSound, flags, wfx, nPCMサイズbyte, nPCMデータの先頭インデックス );
976 private void tDirectSoundサウンドを作成する_セカンダリバッファの作成とWAVデータ書き込み
977 ( ref byte[] byArrWAVファイルイメージ, DirectSound DirectSound, BufferFlags flags, WaveFormat wfx,
978 int nPCMサイズbyte, int nPCMデータの先頭インデックス )
980 // セカンダリバッファを作成し、PCMデータを書き込む。
984 this.Buffer = new SecondarySoundBuffer( DirectSound, new SoundBufferDescription()
986 Format = this._Format,
988 BufferBytes = nPCMサイズbyte,
990 this.Buffer.Write( byArrWAVファイルイメージ, nPCMデータの先頭インデックス, nPCMサイズbyte, 0, LockFlags.None );
994 this.eデバイス種別 = ESoundDeviceType.DirectSound;
995 this.DirectSoundBufferFlags = flags;
996 this.byArrWAVファイルイメージ = byArrWAVファイルイメージ;
997 this.DirectSound = DirectSound;
1000 this.nオリジナルの周波数 = wfx.SampleRate;
1001 n総演奏時間ms = (int) ( ( (double) nPCMサイズbyte ) / ( this._Format.AverageBytesPerSecond * 0.001 ) );
1004 CSound.listインスタンス.Add( this );
1007 #region [ DTXMania用の変換 ]
1009 public void tサウンドを破棄する( CSound cs )
1013 public void t再生を開始する()
1018 public void t再生を開始する( bool bループする )
1024 Bass.BASS_ChannelFlags( this.hBassStream, BASSFlag.BASS_SAMPLE_LOOP, BASSFlag.BASS_SAMPLE_LOOP );
1028 Bass.BASS_ChannelFlags( this.hBassStream, BASSFlag.BASS_DEFAULT, BASSFlag.BASS_DEFAULT );
1032 tサウンドを再生する( bループする );
1034 public void t再生を停止する()
1039 public void t再生を一時停止する()
1044 public void t再生を再開する( long t ) // ★★★★★★★★★★★★★★★★★★★★★★★★★★★★
1046 Debug.WriteLine( "t再生を再開する(long " + t + ")" );
1055 if ( this.bBASSサウンドである )
1057 bool ret = ( BassMix.BASS_Mixer_ChannelIsActive( this.hBassStream ) == BASSActive.BASS_ACTIVE_PAUSED ) &
1058 ( BassMix.BASS_Mixer_ChannelGetPosition( this.hBassStream ) > 0 );
1063 return ( this.n一時停止回数 > 0 );
1071 if ( this.eデバイス種別 == ESoundDeviceType.DirectSound )
1073 return ( ( this.Buffer.Status & (int) BufferStatus.Playing ) != (int) BufferStatus.None );
1077 // 基本的にはBASS_ACTIVE_PLAYINGなら再生中だが、最後まで再生しきったchannelも
1078 // BASS_ACTIVE_PLAYINGのままになっているので、小細工が必要。
1079 bool ret = ( BassMix.BASS_Mixer_ChannelIsActive( this.hBassStream ) == BASSActive.BASS_ACTIVE_PLAYING );
1080 if ( BassMix.BASS_Mixer_ChannelGetPosition( this.hBassStream ) >= nBytes )
1088 //public lint t時刻から位置を返す( long t )
1090 // double num = ( n時刻 * this.db再生速度 ) * this.db周波数倍率;
1091 // return (int) ( ( num * 0.01 ) * this.nSamplesPerSecond );
1101 public void t解放する( bool _bインスタンス削除 )
1103 if ( this.bBASSサウンドである ) // stream数の削減用
1105 tBASSサウンドをミキサーから削除する();
1106 _cbEndofStream = null;
1107 //_cbStreamXA = null;
1108 CSound管理.nStreams--;
1110 bool bManagedも解放する = true;
1111 bool bインスタンス削除 = _bインスタンス削除; // CSoundの再初期化時は、インスタンスは存続する。
1112 this.Dispose( bManagedも解放する, bインスタンス削除 );
1113 //Debug.WriteLine( "Disposed: " + _bインスタンス削除 + " : " + Path.GetFileName( this.strファイル名 ) );
1115 public void tサウンドを再生する()
1117 tサウンドを再生する( false );
1119 public void tサウンドを再生する( bool bループする )
1121 if ( this.bBASSサウンドである ) // BASSサウンド時のループ処理は、t再生を開始する()側に実装。ここでは「bループする」は未使用。
1123 //Debug.WriteLine( "再生中?: " + System.IO.Path.GetFileName(this.strファイル名) + " status=" + BassMix.BASS_Mixer_ChannelIsActive( this.hBassStream ) + " current=" + BassMix.BASS_Mixer_ChannelGetPosition( this.hBassStream ) + " nBytes=" + nBytes );
1124 bool b = BassMix.BASS_Mixer_ChannelPlay( this.hBassStream );
1127 //Debug.WriteLine( "再生しようとしたが、Mixerに登録されていなかった: " + Path.GetFileName( this.strファイル名 ) + ", stream#=" + this.hBassStream + ", ErrCode=" + Bass.BASS_ErrorGetCode() );
1129 bool bb = tBASSサウンドをミキサーに追加する();
1132 Debug.WriteLine( "Mixerへの登録に失敗: " + Path.GetFileName( this.strファイル名 ) + ", ErrCode=" + Bass.BASS_ErrorGetCode() );
1136 //Debug.WriteLine( "Mixerへの登録に成功: " + Path.GetFileName( this.strファイル名 ) + ": " + Bass.BASS_ErrorGetCode() );
1138 //this.t再生位置を先頭に戻す();
1140 bool bbb = BassMix.BASS_Mixer_ChannelPlay( this.hBassStream );
1143 Debug.WriteLine("更に再生に失敗: " + Path.GetFileName(this.strファイル名) + ", ErrCode=" + Bass.BASS_ErrorGetCode() );
1147 // Debug.WriteLine("再生成功(ミキサー追加後) : " + Path.GetFileName(this.strファイル名));
1152 //Debug.WriteLine( "再生成功: " + Path.GetFileName( this.strファイル名 ) + " (" + hBassStream + ")" );
1155 else if( this.bDirectSoundである )
1157 PlayFlags pf = ( bループする ) ? PlayFlags.Looping : PlayFlags.None;
1158 this.Buffer.Play( 0, pf );
1161 public void tサウンドを先頭から再生する()
1166 public void tサウンドを停止してMixerからも削除する()
1168 tサウンドを停止する( false );
1171 tBASSサウンドをミキサーから削除する();
1174 public void tサウンドを停止する()
1176 tサウンドを停止する( false );
1178 public void tサウンドを停止する( bool pause )
1180 if( this.bBASSサウンドである )
1182 //Debug.WriteLine( "停止: " + System.IO.Path.GetFileName( this.strファイル名 ) + " status=" + BassMix.BASS_Mixer_ChannelIsActive( this.hBassStream ) + " current=" + BassMix.BASS_Mixer_ChannelGetPosition( this.hBassStream ) + " nBytes=" + nBytes );
1183 BassMix.BASS_Mixer_ChannelPause( this.hBassStream );
1186 // tBASSサウンドをミキサーから削除する(); // PAUSEと再生停止を区別できるようにすること!!
1189 else if( this.bDirectSoundである )
1197 // WASAPI/ASIOとDirectSoundを同時使用すると、Bufferがlostしてここで例外発生する。→ catchして無視する。
1198 // DTXCからDTXManiaを呼び出すと、DTXC終了時にこの現象が発生する。
1204 public void t再生位置を先頭に戻す()
1206 if( this.bBASSサウンドである )
1208 BassMix.BASS_Mixer_ChannelSetPosition( this.hBassStream, 0 );
1211 else if( this.bDirectSoundである )
1213 this.Buffer.CurrentPosition = 0;
1216 public void t再生位置を変更する( long n位置ms )
1218 if( this.bBASSサウンドである )
1223 b = BassMix.BASS_Mixer_ChannelSetPosition( this.hBassStream, Bass.BASS_ChannelSeconds2Bytes( this.hBassStream, n位置ms * this.db周波数倍率 * this.db再生速度 / 1000.0 ), BASSMode.BASS_POS_BYTES );
1225 catch( Exception e )
1227 Trace.TraceInformation( Path.GetFileName( this.strファイル名 ) + ": Seek error: " + e.ToString() + ": " + n位置ms + "ms" );
1233 BASSError be = Bass.BASS_ErrorGetCode();
1234 Trace.TraceInformation( Path.GetFileName( this.strファイル名 ) + ": Seek error: " + be.ToString() + ": " + n位置ms + "MS" );
1237 //if ( this.n総演奏時間ms > 5000 )
1239 // Trace.TraceInformation( Path.GetFileName( this.strファイル名 ) + ": Seeked to " + n位置ms + "ms = " + Bass.BASS_ChannelSeconds2Bytes( this.hBassStream, n位置ms * this.db周波数倍率 * this.db再生速度 / 1000.0 ) );
1242 else if( this.bDirectSoundである )
1244 int n位置sample = (int) ( this._Format.SampleRate * n位置ms * 0.001 * _db周波数倍率 * _db再生速度 ); // #30839 2013.2.24 yyagi; add _db周波数倍率 and _db再生速度
1247 this.Buffer.CurrentPosition = n位置sample * this._Format.BlockAlign;
1249 catch ( Exception e )
1251 Trace.TraceError( "{0}: Seek error: {1}", Path.GetFileName( this.strファイル名 ), n位置ms, e.Message );
1253 //if ( this.n総演奏時間ms > 5000 )
1255 // Trace.TraceInformation( Path.GetFileName( this.strファイル名 ) + ": Seeked to " + n位置ms + "ms = " + n位置sample );
1262 /// <param name="n位置byte"></param>
1263 /// <param name="db位置ms"></param>
1264 public void t再生位置を取得する( out long n位置byte, out double db位置ms )
1266 if ( this.bBASSサウンドである )
1268 n位置byte = BassMix.BASS_Mixer_ChannelGetPosition( this.hBassStream );
1269 db位置ms = Bass.BASS_ChannelBytes2Seconds( this.hBassStream, n位置byte );
1271 else if ( this.bDirectSoundである )
1273 this.Buffer.GetCurrentPosition( out int pos, out _ );
1274 n位置byte = (long) pos;
1275 db位置ms = n位置byte / this._Format.SampleRate / 0.001 / _db周波数倍率 / _db再生速度;
1285 public static void tすべてのサウンドを初期状態に戻す()
1287 foreach ( var sound in CSound.listインスタンス )
1289 sound.t解放する( false );
1292 public static void tすべてのサウンドを再構築する( ISoundDevice device )
1294 if( CSound.listインスタンス.Count == 0 )
1298 // サウンドを再生する際にインスタンスリストも更新されるので、配列にコピーを取っておき、リストはクリアする。
1300 var sounds = CSound.listインスタンス.ToArray();
1301 CSound.listインスタンス.Clear();
1304 // 配列に基づいて個々のサウンドを作成する。
1306 for( int i = 0; i < sounds.Length; i++ )
1308 switch( sounds[ i ].e作成方法 )
1312 string strファイル名 = sounds[ i ].strファイル名;
1313 sounds[ i ].Dispose( true, false );
1314 device.tサウンドを作成する( strファイル名, ref sounds[ i ] );
1317 #region [ WAVファイルイメージから ]
1318 case E作成方法.WAVファイルイメージから:
1319 if( sounds[ i ].bBASSサウンドである )
1321 byte[] byArrWaveファイルイメージ = sounds[ i ].byArrWAVファイルイメージ;
1322 sounds[ i ].Dispose( true, false );
1323 device.tサウンドを作成する( byArrWaveファイルイメージ, ref sounds[ i ] );
1325 else if( sounds[ i ].bDirectSoundである )
1327 byte[] byArrWaveファイルイメージ = sounds[ i ].byArrWAVファイルイメージ;
1328 var flags = sounds[ i ].DirectSoundBufferFlags;
1329 sounds[ i ].Dispose( true, false );
1330 ( (CSoundDeviceDirectSound) device ).tサウンドを作成する( byArrWaveファイルイメージ, flags, ref sounds[ i ] );
1338 #region [ Dispose-Finalizeパターン実装 ]
1340 public void Dispose()
1342 this.Dispose( true, true );
1343 GC.SuppressFinalize( this );
1345 protected void Dispose( bool bManagedも解放する, bool bインスタンス削除 )
1347 if( this.bBASSサウンドである )
1349 #region [ ASIO, WASAPI の解放 ]
1351 if ( _hTempoStream != 0 )
1353 BassMix.BASS_Mixer_ChannelRemove( this._hTempoStream );
1354 Bass.BASS_StreamFree( this._hTempoStream );
1356 BassMix.BASS_Mixer_ChannelRemove( this._hBassStream );
1357 Bass.BASS_StreamFree( this._hBassStream );
1358 this.hBassStream = -1;
1359 this._hBassStream = -1;
1360 this._hTempoStream = 0;
1367 //int freeIndex = -1;
1369 //if ( CSound.listインスタンス != null )
1371 // freeIndex = CSound.listインスタンス.IndexOf( this );
1372 // if ( freeIndex == -1 )
1374 // Debug.WriteLine( "ERR: freeIndex==-1 : Count=" + CSound.listインスタンス.Count + ", filename=" + Path.GetFileName( this.strファイル名 ) );
1378 if( this.eデバイス種別 == ESoundDeviceType.DirectSound )
1380 #region [ DirectSound の解放 ]
1382 if( this.Buffer != null )
1390 // 演奏終了後、長時間解放しないでいると、たまに AccessViolationException が発生することがある。
1392 C共通.tDisposeする( ref this.Buffer );
1398 if( this.e作成方法 == E作成方法.WAVファイルイメージから &&
1399 this.eデバイス種別 != ESoundDeviceType.DirectSound ) // DirectSound は hGC 未使用。
1401 if ( this.hGC != null && this.hGC.IsAllocated )
1404 this.hGC = default( GCHandle );
1407 if ( this.byArrWAVファイルイメージ != null )
1409 this.byArrWAVファイルイメージ = null;
1416 // CSound.listインスタンス.RemoveAt( freeIndex );
1420 // Debug.WriteLine( "FAILED to remove CSound.listインスタンス: Count=" + CSound.listインスタンス.Count + ", filename=" + Path.GetFileName( this.strファイル名 ) );
1422 bool b = CSound.listインスタンス.Remove( this ); // これだと、Clone()したサウンドのremoveに失敗する
1425 Debug.WriteLine( "FAILED to remove CSound.listインスタンス: Count=" + CSound.listインスタンス.Count + ", filename=" + Path.GetFileName( this.strファイル名 ) );
1433 this.Dispose( false, true );
1438 #region [ protected ]
1440 protected enum E作成方法 { ファイルから, WAVファイルイメージから, Unknown }
1441 protected E作成方法 e作成方法 = E作成方法.Unknown;
1442 protected ESoundDeviceType eデバイス種別 = ESoundDeviceType.Unknown;
1443 public string strファイル名 = null;
1444 protected byte[] byArrWAVファイルイメージ = null; // WAVファイルイメージ、もしくはchunkのDATA部のみ
1445 protected GCHandle hGC;
1446 protected int _hTempoStream = 0;
1447 protected int _hBassStream = -1; // ASIO, WASAPI 用
1448 protected int hBassStream = 0; // #31076 2013.4.1 yyagi; プロパティとして実装すると動作が低速になったため、
1449 // tBASSサウンドを作成する・ストリーム生成後の共通処理()のタイミングと、
1450 // 再生速度を変更したタイミングでのみ、
1451 // hBassStreamを更新するようにした。
1455 // if ( _hTempoStream != 0 && !this.bIs1倍速再生 ) // 再生速度がx1.000のときは、TempoStreamを用いないようにして高速化する
1457 // return _hTempoStream;
1461 // return _hBassStream;
1466 // _hBassStream = value;
1469 protected SoundBuffer Buffer = null; // DirectSound 用
1470 protected DirectSound DirectSound;
1471 protected int hMixer = -1; // 設計壊してゴメン Mixerに後で登録するときに使う
1477 private bool bDirectSoundである
1479 get { return ( this.eデバイス種別 == ESoundDeviceType.DirectSound ); }
1481 private bool bBASSサウンドである
1486 this.eデバイス種別 == ESoundDeviceType.ASIO ||
1487 this.eデバイス種別 == ESoundDeviceType.ExclusiveWASAPI ||
1488 this.eデバイス種別 == ESoundDeviceType.SharedWASAPI );
1491 private int _n位置 = 0;
1493 private int _n音量 = 100;
1495 private long nBytes = 0;
1496 private int n一時停止回数 = 0;
1497 private int nオリジナルの周波数 = 0;
1498 private double _db周波数倍率 = 1.0;
1499 private double _db再生速度 = 1.0;
1500 private bool bIs1倍速再生 = true;
1501 private WaveFormat _Format;
1503 private void tBASSサウンドを作成する( string strファイル名, int hMixer, BASSFlag flags )
1505 #region [ xaとwav(RIFF chunked vorbis)に対しては専用の処理をする ]
1506 switch ( Path.GetExtension( strファイル名 ).ToLower() )
1509 tBASSサウンドを作成するXA( strファイル名, hMixer, flags );
1513 if ( tRIFFchunkedVorbisならDirectShowでDecodeする( strファイル名, ref byArrWAVファイルイメージ ) )
1515 tBASSサウンドを作成する( byArrWAVファイルイメージ, hMixer, flags );
1525 this.e作成方法 = E作成方法.ファイルから;
1526 this.strファイル名 = strファイル名;
1529 // BASSファイルストリームを作成。
1531 this._hBassStream = Bass.BASS_StreamCreateFile( strファイル名, 0, 0, flags );
1532 if( this._hBassStream == 0 )
1533 throw new Exception( string.Format( "サウンドストリームの生成に失敗しました。(BASS_StreamCreateFile)[{0}]", Bass.BASS_ErrorGetCode().ToString() ) );
1535 nBytes = Bass.BASS_ChannelGetLength( this._hBassStream );
1537 tBASSサウンドを作成する_ストリーム生成後の共通処理( hMixer );
1539 private void tBASSサウンドを作成する( byte[] byArrWAVファイルイメージ, int hMixer, BASSFlag flags )
1541 this.e作成方法 = E作成方法.WAVファイルイメージから;
1542 this.byArrWAVファイルイメージ = byArrWAVファイルイメージ;
1543 this.hGC = GCHandle.Alloc( byArrWAVファイルイメージ, GCHandleType.Pinned ); // byte[] をピン留め
1546 // BASSファイルストリームを作成。
1548 this._hBassStream = Bass.BASS_StreamCreateFile( hGC.AddrOfPinnedObject(), 0, byArrWAVファイルイメージ.Length, flags );
1549 if ( this._hBassStream == 0 )
1550 throw new Exception( string.Format( "サウンドストリームの生成に失敗しました。(BASS_StreamCreateFile)[{0}]", Bass.BASS_ErrorGetCode().ToString() ) );
1552 nBytes = Bass.BASS_ChannelGetLength( this._hBassStream );
1554 tBASSサウンドを作成する_ストリーム生成後の共通処理( hMixer );
1558 /// Decode "RIFF chunked Vorbis" to "raw wave"
1559 /// because BASE.DLL has two problems for RIFF chunked Vorbis;
1560 /// 1. time seek is not fine 2. delay occurs (about 10ms)
1562 /// <param name="strファイル名">wave filename</param>
1563 /// <param name="byArrWAVファイルイメージ">wav file image</param>
1564 /// <returns></returns>
1565 private bool tRIFFchunkedVorbisならDirectShowでDecodeする( string strファイル名, ref byte[] byArrWAVファイルイメージ )
1567 bool bファイルにVorbisコンテナが含まれている = false;
1569 #region [ ファイルがWAVかつ、Vorbisコンテナが含まれているかを調べ、それに該当するなら、DirectShowでデコードする。]
1573 using( var ws = new SoundStream( new FileStream( strファイル名, FileMode.Open ) ) )
1575 if( ws.Format.Encoding == WaveFormatEncoding.OggVorbisMode2Plus ||
1576 ws.Format.Encoding == WaveFormatEncoding.OggVorbisMode3Plus )
1578 Trace.TraceInformation( Path.GetFileName( strファイル名 ) + ": RIFF chunked Vorbis. Decode to raw Wave first, to avoid BASS.DLL troubles" );
1581 CDStoWAVFileImage.t変換( strファイル名, out byArrWAVファイルイメージ );
1582 bファイルにVorbisコンテナが含まれている = true;
1586 Trace.TraceWarning( "Warning: " + Path.GetFileName( strファイル名 ) + " : RIFF chunked Vorbisのデコードに失敗しました。" );
1591 catch ( InvalidDataException )
1593 // DirectShowのデコードに失敗したら、次はACMでのデコードを試すことになるため、ここではエラーログを出さない。
1594 // Trace.TraceWarning( "Warning: " + Path.GetFileName( strファイル名 ) + " : デコードに失敗しました。" );
1598 Trace.TraceWarning( "Warning: " + Path.GetFileName( strファイル名 ) + " : 読み込みに失敗しました。" );
1602 return bファイルにVorbisコンテナが含まれている;
1605 private void tBASSサウンドを作成するXA( string strファイル名, int hMixer, BASSFlag flags )
1607 int nPCMデータの先頭インデックス;
1608 CWin32.WAVEFORMATEX wfx;
1611 tオンメモリ方式でデコードする( strファイル名, out this.byArrWAVファイルイメージ,
1612 out nPCMデータの先頭インデックス, out totalPCMSize, out wfx, true );
1614 nBytes = totalPCMSize;
1616 this.e作成方法 = E作成方法.WAVファイルイメージから; //.ファイルから; // 再構築時はデコード後のイメージを流用する&Dispose時にhGCを解放する
1617 this.strファイル名 = strファイル名;
1618 this.hGC = GCHandle.Alloc( this.byArrWAVファイルイメージ, GCHandleType.Pinned ); // byte[] をピン留め
1620 //_cbStreamXA = new STREAMPROC( CallbackPlayingXA );
1622 // BASSファイルストリームを作成。
1624 //this.hBassStream = Bass.BASS_StreamCreate( xa.xaheader.nSamplesPerSec, xa.xaheader.nChannels, BASSFlag.BASS_STREAM_DECODE, _myStreamCreate, IntPtr.Zero );
1625 //this._hBassStream = Bass.BASS_StreamCreate( (int) wfx.nSamplesPerSec, (int) wfx.nChannels, BASSFlag.BASS_STREAM_DECODE, _cbStreamXA, IntPtr.Zero );
1627 // StreamCreate()で作成したstreamはseek不可のため、StreamCreateFile()を使う。
1628 this._hBassStream = Bass.BASS_StreamCreateFile( this.hGC.AddrOfPinnedObject(), 0L, totalPCMSize, flags );
1629 if ( this._hBassStream == 0 )
1632 throw new Exception( string.Format( "サウンドストリームの生成に失敗しました。(BASS_SampleCreate)[{0}]", Bass.BASS_ErrorGetCode().ToString() ) );
1635 nBytes = Bass.BASS_ChannelGetLength( this._hBassStream );
1638 tBASSサウンドを作成する_ストリーム生成後の共通処理( hMixer );
1642 private void tBASSサウンドを作成する_ストリーム生成後の共通処理( int hMixer )
1644 CSound管理.nStreams++;
1646 // 個々のストリームの出力をテンポ変更のストリームに入力する。テンポ変更ストリームの出力を、Mixerに出力する。
1648 // if ( CSound管理.bIsTimeStretch ) // TimeStretchのON/OFFに関わりなく、テンポ変更のストリームを生成する。後からON/OFF切り替え可能とするため。
1650 this._hTempoStream = BassFx.BASS_FX_TempoCreate( this._hBassStream, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_FX_FREESOURCE );
1651 if ( this._hTempoStream == 0 )
1654 throw new Exception( string.Format( "サウンドストリームの生成に失敗しました。(BASS_FX_TempoCreate)[{0}]", Bass.BASS_ErrorGetCode().ToString() ) );
1658 Bass.BASS_ChannelSetAttribute( this._hTempoStream, BASSAttribute.BASS_ATTRIB_TEMPO_OPTION_USE_QUICKALGO, 1f ); // 高速化(音の品質は少し落ちる)
1662 if ( _hTempoStream != 0 && !this.bIs1倍速再生 ) // 再生速度がx1.000のときは、TempoStreamを用いないようにして高速化する
1664 this.hBassStream = _hTempoStream;
1668 this.hBassStream = _hBassStream;
1671 // #32248 再生終了時に発火するcallbackを登録する (演奏終了後に再生終了するチップを非同期的にミキサーから削除するため。)
1672 _cbEndofStream = new SYNCPROC( CallbackEndofStream );
1673 Bass.BASS_ChannelSetSync( hBassStream, BASSSync.BASS_SYNC_END | BASSSync.BASS_SYNC_MIXTIME, 0, _cbEndofStream, IntPtr.Zero );
1677 CSound.listインスタンス.Add( this );
1679 // n総演奏時間の取得; DTXMania用に追加。
1680 double seconds = Bass.BASS_ChannelBytes2Seconds( this._hBassStream, nBytes );
1681 this.n総演奏時間ms = (int) ( seconds * 1000 );
1683 this.hMixer = hMixer;
1685 if ( !Bass.BASS_ChannelGetAttribute( this._hBassStream, BASSAttribute.BASS_ATTRIB_FREQ, ref freq ) )
1688 throw new Exception( string.Format( "サウンドストリームの周波数取得に失敗しました。(BASS_ChannelGetAttribute)[{0}]", Bass.BASS_ErrorGetCode().ToString() ) );
1690 this.nオリジナルの周波数 = (int) freq;
1694 //private int pos = 0;
1695 //private int CallbackPlayingXA( int handle, IntPtr buffer, int length, IntPtr user )
1697 // int bytesread = ( pos + length > Convert.ToInt32( nBytes ) ) ? Convert.ToInt32( nBytes ) - pos : length;
1699 // Marshal.Copy( byArrWAVファイルイメージ, pos, buffer, bytesread );
1700 // pos += bytesread;
1701 // if ( pos >= nBytes )
1703 // // set indicator flag
1704 // bytesread |= (int) BASSStreamProc.BASS_STREAMPROC_END;
1706 // return bytesread;
1709 /// ストリームの終端まで再生したときに呼び出されるコールバック
1711 /// <param name="handle"></param>
1712 /// <param name="channel"></param>
1713 /// <param name="data"></param>
1714 /// <param name="user"></param>
1715 private void CallbackEndofStream( int handle, int channel, int data, IntPtr user ) // #32248 2013.10.14 yyagi
1717 // Trace.TraceInformation( "Callback!(remove): " + Path.GetFileName( this.strファイル名 ) );
1718 if ( b演奏終了後も再生が続くチップである ) // 演奏終了後に再生終了するチップ音のミキサー削除は、再生終了のコールバックに引っ掛けて、自前で行う。
1719 { // そうでないものは、ミキサー削除予定時刻に削除する。
1720 tBASSサウンドをミキサーから削除する( channel );
1726 public bool tBASSサウンドをミキサーから削除する()
1728 return tBASSサウンドをミキサーから削除する( this.hBassStream );
1730 public bool tBASSサウンドをミキサーから削除する( int channel )
1732 bool b = BassMix.BASS_Mixer_ChannelRemove( channel );
1735 Interlocked.Decrement( ref CSound管理.nMixing );
1736 // Debug.WriteLine( "Removed: " + Path.GetFileName( this.strファイル名 ) + " (" + channel + ")" + " MixedStreams=" + CSound管理.nMixing );
1744 public bool tBASSサウンドをミキサーに追加する()
1746 if ( BassMix.BASS_Mixer_ChannelGetMixer( hBassStream ) == 0 )
1748 BASSFlag bf = BASSFlag.BASS_SPEAKER_FRONT | BASSFlag.BASS_MIXER_NORAMPIN | BASSFlag.BASS_MIXER_PAUSE;
1749 Interlocked.Increment( ref CSound管理.nMixing );
1751 // preloadされることを期待して、敢えてflagからはBASS_MIXER_PAUSEを外してAddChannelした上で、すぐにPAUSEする
1752 // -> ChannelUpdateでprebufferできることが分かったため、BASS_MIXER_PAUSEを使用することにした
1754 bool b1 = BassMix.BASS_Mixer_StreamAddChannel( this.hMixer, this.hBassStream, bf );
1755 //bool b2 = BassMix.BASS_Mixer_ChannelPause( this.hBassStream );
1756 t再生位置を先頭に戻す(); // StreamAddChannelの後で再生位置を戻さないとダメ。逆だと再生位置が変わらない。
1757 //Trace.TraceInformation( "Add Mixer: " + Path.GetFileName( this.strファイル名 ) + " (" + hBassStream + ")" + " MixedStreams=" + CSound管理.nMixing );
1758 Bass.BASS_ChannelUpdate( this.hBassStream, 0 ); // pre-buffer
1764 #region [ tオンメモリ方式でデコードする() ]
1765 public void tオンメモリ方式でデコードする( string strファイル名, out byte[] buffer,
1766 out int nPCMデータの先頭インデックス, out int totalPCMSize, out CWin32.WAVEFORMATEX wfx,
1767 bool bIntegrateWaveHeader )
1769 nPCMデータの先頭インデックス = 0;
1770 //int nPCMサイズbyte = (int) ( xa.xaheader.nSamples * xa.xaheader.nChannels * 2 ); // nBytes = Bass.BASS_ChannelGetLength( this.hBassStream );
1772 SoundDecoder sounddecoder;
1774 if ( String.Compare( Path.GetExtension( strファイル名 ), ".xa", true ) == 0 )
1776 sounddecoder = new Cxa();
1778 else if ( String.Compare( Path.GetExtension( strファイル名 ), ".ogg", true ) == 0 )
1780 sounddecoder = new Cogg();
1782 else if ( String.Compare( Path.GetExtension( strファイル名 ), ".mp3", true ) == 0 )
1784 sounddecoder = new Cmp3();
1788 throw new NotImplementedException();
1791 if ( !File.Exists( strファイル名 ) )
1793 throw new Exception( string.Format( "ファイルが見つかりませんでした。({0})", strファイル名 ) );
1795 int nHandle = sounddecoder.Open( strファイル名 );
1798 throw new Exception( string.Format( "Open() に失敗しました。({0})({1})", nHandle, strファイル名 ) );
1800 wfx = new CWin32.WAVEFORMATEX();
1801 if ( sounddecoder.GetFormat( nHandle, ref wfx ) < 0 )
1803 sounddecoder.Close( nHandle );
1804 throw new Exception( string.Format( "GetFormat() に失敗しました。({0})", strファイル名 ) );
1806 //totalPCMSize = (int) sounddecoder.nTotalPCMSize; // tデコード後のサイズを調べる()で既に取得済みの値を流用する。ms単位の高速化だが、チップ音がたくさんあると塵積で結構効果がある
1807 totalPCMSize = (int) sounddecoder.GetTotalPCMSize( nHandle );
1808 if ( totalPCMSize == 0 )
1810 sounddecoder.Close( nHandle );
1811 throw new Exception( string.Format( "GetTotalPCMSize() に失敗しました。({0})", strファイル名 ) );
1813 totalPCMSize += ( ( totalPCMSize % 2 ) != 0 ) ? 1 : 0;
1814 int wavheadersize = ( bIntegrateWaveHeader ) ? 44 : 0;
1815 byte[] buffer_rawdata = new byte[ totalPCMSize ];
1816 buffer = new byte[ wavheadersize + totalPCMSize ];
1817 GCHandle handle = GCHandle.Alloc( buffer_rawdata, GCHandleType.Pinned );
1820 if ( sounddecoder.Decode( nHandle, handle.AddrOfPinnedObject(), (uint) totalPCMSize, 0 ) < 0 )
1823 throw new Exception( string.Format( "デコードに失敗しました。({0})", strファイル名 ) );
1825 if ( bIntegrateWaveHeader )
1829 int wfx拡張領域_Length = 0;
1830 var ms = new MemoryStream();
1831 var bw = new BinaryWriter( ms );
1832 bw.Write( new byte[] { 0x52, 0x49, 0x46, 0x46 } ); // 'RIFF'
1833 bw.Write( (UInt32) totalPCMSize + 44 - 8 ); // ファイルサイズ - 8 [byte];今は不明なので後で上書きする。
1834 bw.Write( new byte[] { 0x57, 0x41, 0x56, 0x45 } ); // 'WAVE'
1835 bw.Write( new byte[] { 0x66, 0x6D, 0x74, 0x20 } ); // 'fmt '
1836 bw.Write( (UInt32) ( 16 + ( ( wfx拡張領域_Length > 0 ) ? ( 2/*sizeof(WAVEFORMATEX.cbSize)*/ + wfx拡張領域_Length ) : 0 ) ) ); // fmtチャンクのサイズ[byte]
1837 bw.Write( (UInt16) wfx.wFormatTag ); // フォーマットID(リニアPCMなら1)
1838 bw.Write( (UInt16) wfx.nChannels ); // チャンネル数
1839 bw.Write( (UInt32) wfx.nSamplesPerSec ); // サンプリングレート
1840 bw.Write( (UInt32) wfx.nAvgBytesPerSec ); // データ速度
1841 bw.Write( (UInt16) wfx.nBlockAlign ); // ブロックサイズ
1842 bw.Write( (UInt16) wfx.wBitsPerSample ); // サンプルあたりのビット数
1843 //if ( wfx拡張領域_Length > 0 )
1845 // bw.Write( (UInt16) wfx拡張領域.Length ); // 拡張領域のサイズ[byte]
1846 // bw.Write( wfx拡張領域 ); // 拡張データ
1848 bw.Write( new byte[] { 0x64, 0x61, 0x74, 0x61 } ); // 'data'
1849 //int nDATAチャンクサイズ位置 = (int) ms.Position;
1850 bw.Write( (UInt32) totalPCMSize ); // dataチャンクのサイズ[byte]
1852 byte[] bs = ms.ToArray();
1857 for ( int i = 0; i < bs.Length; i++ )
1859 buffer[ i ] = bs[ i ];
1862 int s = ( bIntegrateWaveHeader ) ? 44 : 0;
1863 for ( int i = 0; i < totalPCMSize; i++ )
1865 buffer[ i + s ] = buffer_rawdata[ i ];
1867 totalPCMSize += wavheadersize;
1868 nPCMデータの先頭インデックス = wavheadersize;
1873 sounddecoder.Close( nHandle );
1874 sounddecoder = null;