private void InitialiseDirectSound(IntPtr windowHandle, int sampleRate) { var waveFormat = new WaveFormat(sampleRate, 16, 2); _directSound = new DirectSound(); _directSound.SetCooperativeLevel(windowHandle, CooperativeLevel.Priority); var primaryBufferDescription = new SoundBufferDescription() { Flags = BufferFlags.PrimaryBuffer, AlgorithmFor3D = Guid.Empty, }; _primarySoundBuffer = new PrimarySoundBuffer(_directSound, primaryBufferDescription) { Format = waveFormat }; _soundBufferLength = waveFormat.ConvertLatencyToByteSize(500); var secondaryBufferDescription = new SoundBufferDescription() { Format = waveFormat, Flags = BufferFlags.GetCurrentPosition2 | BufferFlags.GlobalFocus, BufferBytes = _soundBufferLength, AlgorithmFor3D = Guid.Empty, }; _soundBuffer = new SecondarySoundBuffer(_directSound, secondaryBufferDescription); }
void InitDirectSound(Control parent) { //Create the device MyNesDEBUGGER.WriteLine(this, "Initializing direct sound for APU", DebugStatus.None); _SoundDevice = new DirectSound(); _SoundDevice.SetCooperativeLevel(parent.Parent.Handle, CooperativeLevel.Normal); //Create the wav format WaveFormat wav = new WaveFormat(); wav.FormatTag = WaveFormatTag.Pcm; wav.SamplesPerSecond = 44100; wav.Channels = (short)(STEREO ? 2 : 1); AD = (STEREO ? 4 : 2);//Stereo / Mono wav.BitsPerSample = 16; wav.AverageBytesPerSecond = wav.SamplesPerSecond * wav.Channels * (wav.BitsPerSample / 8); wav.BlockAlignment = (short)(wav.Channels * wav.BitsPerSample / 8); BufferSize = wav.AverageBytesPerSecond; //Description SoundBufferDescription des = new SoundBufferDescription(); des.Format = wav; des.SizeInBytes = BufferSize; //des.Flags = BufferFlags.GlobalFocus | BufferFlags.Software; des.Flags = BufferFlags.ControlVolume | BufferFlags.ControlFrequency | BufferFlags.ControlPan | BufferFlags.ControlEffects; //buffer DATA = new byte[BufferSize]; buffer = new SecondarySoundBuffer(_SoundDevice, des); buffer.Play(0, PlayFlags.Looping); //channels InitChannels(); MyNesDEBUGGER.WriteLine(this, "APU OK !!", DebugStatus.Cool); }
public Sound(IntPtr handle, DirectSound device) { if (device != null) { device.SetCooperativeLevel(handle, CooperativeLevel.Priority); var format = new WaveFormat { SamplesPerSecond = 44100, BitsPerSample = 16, Channels = 2, FormatTag = WaveFormatTag.Pcm, BlockAlignment = 4 }; format.AverageBytesPerSecond = format.SamplesPerSecond * format.Channels * (format.BitsPerSample / 8); var desc = new SoundBufferDescription { Format = format, Flags = BufferFlags.GlobalFocus | BufferFlags.Software | BufferFlags.GetCurrentPosition2 | BufferFlags.ControlVolume, SizeInBytes = BufferSize }; DSoundBuffer = new SecondarySoundBuffer(device, desc); ChangeVolume(Global.Config.SoundVolume); } SoundBuffer = new byte[BufferSize]; disposed = false; }
public void ChangeAudioDevice(string deviceName = null) { if (CurrentDeviceName == deviceName && ApplicationDevice != null) { return; } var playbackDevices = DirectSound.GetDevices(); // Use default device. Guid driverGuid = Guid.Empty; foreach (var device in playbackDevices) { // Pick specific device for the plaback. if (string.Compare(device.Description, deviceName, true) == 0) { driverGuid = device.DriverGuid; } } if (ApplicationDevice != null) { ApplicationDevice.Dispose(); ApplicationDevice = null; } // Create and set the sound device. ApplicationDevice = new DirectSound(driverGuid); SpeakerConfiguration speakerSet; SpeakerGeometry geometry; ApplicationDevice.GetSpeakerConfiguration(out speakerSet, out geometry); ApplicationDevice.SetCooperativeLevel(_Handle, CooperativeLevel.Normal); CurrentDeviceName = deviceName; }
void InitDirectSound(IntPtr handle) { //Create the device _SoundDevice = new DirectSound(); _SoundDevice.SetCooperativeLevel(handle, CooperativeLevel.Priority); //Creat the wav format, it will be mono-44100-pcm-16bit //TODO: support more wave formats WaveFormat wav = new WaveFormat(); wav.FormatTag = WaveFormatTag.Pcm; wav.SamplesPerSecond = 44100; wav.Channels = 1;//mono wav.BitsPerSample = 16; wav.AverageBytesPerSecond = 88200;//wav.SamplesPerSecond * wav.Channels * (wav.BitsPerSample / 8); wav.BlockAlignment = 2;//(wfx.Channels * wfx.BitsPerSample / 8); BufferSize = 88200 * 5; //Description SoundBufferDescription des = new SoundBufferDescription(); des.Format = wav; des.SizeInBytes = BufferSize; des.Flags = BufferFlags.GlobalFocus | BufferFlags.Software; //buffer buffer = new SecondarySoundBuffer(_SoundDevice, des); DATA = new byte[BufferSize]; buffer.Play(0, PlayFlags.Looping); //channels InitChannels(); }
private void PlaySound(Stream sound) { DirectSound ds = new DirectSound(); ds.SetCooperativeLevel(this.Handle, CooperativeLevel.Priority); WaveFormat format = WaveFormat.CreateCustomFormat( WaveFormatEncoding.Pcm, 44100, 2, 4 * 44100, 4, 16 ); SoundBufferDescription primaryDesc = new SoundBufferDescription(); primaryDesc.Format = format; primaryDesc.Flags = BufferFlags.GlobalFocus; primaryDesc.BufferBytes = 8 * 4 * 44100; PrimarySoundBuffer pBuffer = new PrimarySoundBuffer(ds, primaryDesc); SoundBufferDescription secondDesc = new SoundBufferDescription(); secondDesc.Format = format; secondDesc.Flags = BufferFlags.GlobalFocus | BufferFlags.ControlPositionNotify | BufferFlags.GetCurrentPosition2; secondDesc.BufferBytes = 8 * 4 * 44100; SecondarySoundBuffer secondBuffer = new SecondarySoundBuffer(ds, secondDesc); secondBuffer.Write(sound.ReadAll(), 0, LockFlags.None); secondBuffer.Play(0, PlayFlags.None); }
private static void Initialise() { try { if (directSound == null) { //Initialize the DirectSound Device directSound = new DirectSound(); waveFormat = new WaveFormat(); waveFormat.BitsPerSample = 16; waveFormat.Channels = 1; waveFormat.BlockAlignment = (short)(waveFormat.BitsPerSample / 8); waveFormat.FormatTag = WaveFormatTag.Pcm; waveFormat.SamplesPerSecond = 192000; waveFormat.AverageBytesPerSecond = waveFormat.SamplesPerSecond * waveFormat.BlockAlignment; } // Set the priority of the device with the rest of the operating system directSound.SetCooperativeLevel(User32.GetForegroundWindow(), CooperativeLevel.Priority); } catch (Exception ex) { Utilities.OnError(Utilities.GetCurrentMethod(), ex); } }
public Sound(IntPtr formHandle) { directSound = new DirectSound(); directSound.SetCooperativeLevel(formHandle, CooperativeLevel.Normal); // WAVEFORMATEX Structure (from Microsoft Documentation on DirectSound) // https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ee419019(v%3dvs.85) var wFormatTag = WaveFormatEncoding.Pcm; var nSamplesPerSec = 44100; var nChannels = 1; var wBitsPerSample = 16; // (short) var nBlockAlign = (nChannels * wBitsPerSample) / 8; // nBlockAlign must be equal to the product of nChannels and wBitsPerSample divided by 8 (bits per byte) var nAvgBytesPerSec = nSamplesPerSec * nBlockAlign; // nAvgBytesPerSec should be equal to the product of nSamplesPerSec and nBlockAlign waveFormat = WaveFormat.CreateCustomFormat( tag: wFormatTag, sampleRate: nSamplesPerSec, channels: nChannels, averageBytesPerSecond: nAvgBytesPerSec, blockAlign: nBlockAlign, bitsPerSample: wBitsPerSample ); var bufferDesc = new SoundBufferDescription(); bufferDesc.Format = waveFormat; bufferDesc.BufferBytes = Convert.ToInt32( bufferDuration.TotalSeconds * waveFormat.AverageBytesPerSecond / waveFormat.Channels); buffer = new SecondarySoundBuffer(directSound, bufferDesc); int numSamples = buffer.Capabilities.BufferBytes / waveFormat.BlockAlign; samples = new short[numSamples]; }
bool InitializeDirectSound(IntPtr windowHandler) { try { // Initialize the direct sound interface pointer for the default sound device. _DirectSound = new DirectSound(); // Set the cooperative level to priority so the format of the primary sound buffer can be modified. if (_DirectSound.SetCooperativeLevel(windowHandler, CooperativeLevel.Priority) != Result.Ok) { return(false); } // Setup the primary buffer description. var buffer = new SoundBufferDescription(); buffer.Flags = BufferFlags.PrimaryBuffer | BufferFlags.ControlVolume; buffer.AlgorithmFor3D = Guid.Empty; // Get control of the primary sound buffer on the default sound device. _PrimaryBuffer = new PrimarySoundBuffer(_DirectSound, buffer); // Setup the format of the primary sound buffer. // In this case it is a . _PrimaryBuffer.Format = new WaveFormat(44100, 16, 2); } catch (Exception) { return(false); } return(true); }
private SoundPlayer() { dSound = new DirectSound(); dSound.SetCooperativeLevel(System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle, CooperativeLevel.Normal); dSound.IsDefaultPool = false; cache = new Dictionary <string, SecondarySoundBuffer>(); }
public DirectSoundSoundOutput(Sound sound, IntPtr mainWindowHandle) { _sound = sound; var deviceInfo = DirectSound.GetDevices().FirstOrDefault(d => d.Description == Global.Config.SoundDevice); _device = deviceInfo != null ? new DirectSound(deviceInfo.DriverGuid) : new DirectSound(); _device.SetCooperativeLevel(mainWindowHandle, CooperativeLevel.Priority); }
static void Main(string[] args) { DirectSound directSound = new DirectSound(); var form = new Form(); form.Text = "SharpDX - DirectSound Demo"; // Set Cooperative Level to PRIORITY (priority level can call the SetFormat and Compact methods) // directSound.SetCooperativeLevel(form.Handle, CooperativeLevel.Priority); // Create PrimarySoundBuffer var primaryBufferDesc = new SoundBufferDescription(); primaryBufferDesc.Flags = BufferFlags.PrimaryBuffer; primaryBufferDesc.AlgorithmFor3D = Guid.Empty; var primarySoundBuffer = new PrimarySoundBuffer(directSound, primaryBufferDesc); // Play the PrimarySound Buffer primarySoundBuffer.Play(0, PlayFlags.Looping); // Default WaveFormat Stereo 44100 16 bit WaveFormat waveFormat = new WaveFormat(); // Create SecondarySoundBuffer var secondaryBufferDesc = new SoundBufferDescription(); secondaryBufferDesc.BufferBytes = waveFormat.ConvertLatencyToByteSize(60000); secondaryBufferDesc.Format = waveFormat; secondaryBufferDesc.Flags = BufferFlags.GetCurrentPosition2 | BufferFlags.ControlPositionNotify | BufferFlags.GlobalFocus | BufferFlags.ControlVolume | BufferFlags.StickyFocus; secondaryBufferDesc.AlgorithmFor3D = Guid.Empty; var secondarySoundBuffer = new SecondarySoundBuffer(directSound, secondaryBufferDesc); // Get Capabilties from secondary sound buffer var capabilities = secondarySoundBuffer.Capabilities; // Lock the buffer DataStream dataPart2; var dataPart1 =secondarySoundBuffer.Lock(0, capabilities.BufferBytes, LockFlags.EntireBuffer, out dataPart2); // Fill the buffer with some sound int numberOfSamples = capabilities.BufferBytes/waveFormat.BlockAlign; for (int i = 0; i < numberOfSamples; i++) { double vibrato = Math.Cos(2 * Math.PI * 10.0 * i /waveFormat.SampleRate); short value = (short) (Math.Cos(2*Math.PI*(220.0 + 4.0 * vibrato)*i/waveFormat.SampleRate)*16384); // Not too loud dataPart1.Write(value); dataPart1.Write(value); } // Unlock the buffer secondarySoundBuffer.Unlock(dataPart1, dataPart2); // Play the song secondarySoundBuffer.Play(0, PlayFlags.Looping); Application.Run(form); }
public void Create() { device = new DirectSound(); device.SetCooperativeLevel(handle, CooperativeLevel.Priority); pBufferDescription.Flags = BufferFlags.PrimaryBuffer; pBuffer = new PrimarySoundBuffer(device, pBufferDescription); pBuffer.Format = audioFormat; Reset(); }
public void run() { directSound = new DirectSound(); IntPtr hwnd = GetDesktopWindow(); // Set Cooperative Level to PRIORITY (priority level can call the SetFormat and Compact methods) directSound.SetCooperativeLevel(hwnd, CooperativeLevel.Priority); // Create PrimarySoundBuffer var primaryBufferDesc = new SoundBufferDescription(); primaryBufferDesc.Flags = BufferFlags.PrimaryBuffer; primaryBufferDesc.AlgorithmFor3D = Guid.Empty; primarySoundBuffer = new PrimarySoundBuffer(directSound, primaryBufferDesc); // Create SecondarySoundBuffer int soundLatencyInMilliseconds = 100; var secondaryBufferDesc = new SoundBufferDescription(); secondaryBufferDesc.BufferBytes = soundStreamer.waveFormat.ConvertLatencyToByteSize(soundLatencyInMilliseconds); secondaryBufferDesc.Format = soundStreamer.waveFormat; secondaryBufferDesc.Flags = BufferFlags.GetCurrentPosition2 | BufferFlags.ControlPositionNotify | BufferFlags.GlobalFocus | BufferFlags.ControlVolume | BufferFlags.StickyFocus | BufferFlags.Trueplayposition; secondaryBufferDesc.AlgorithmFor3D = Guid.Empty; secondarySoundBuffer = new SecondarySoundBuffer(directSound, secondaryBufferDesc); NotificationPosition n = new NotificationPosition(); n.Offset = (secondaryBufferDesc.BufferBytes / 4) * 1; n.WaitHandle = soundStreamer.wait; NotificationPosition n2 = new NotificationPosition(); n2.Offset = (secondaryBufferDesc.BufferBytes / 4) * 3; n2.WaitHandle = soundStreamer.wait; secondarySoundBuffer.SetNotificationPositions(new NotificationPosition[] { n, n2 }); soundStreamerThread = new Thread(soundStreamer.loop); soundStreamer.secondarySoundBuffer = secondarySoundBuffer; soundStreamerThread.Start(); // play the sound secondarySoundBuffer.Play(0, PlayFlags.Looping); }
public DXWavePlayer(int device, int BufferByteSize, DataRequestDelegate fillProc) { if (BufferByteSize < 1000) { throw new ArgumentOutOfRangeException("BufferByteSize", "minimal size of buffer is 1000 bytes"); } _buffersize = BufferByteSize; _requestproc = fillProc; var devices = DirectSound.GetDevices(); if (device <= 0 || device >= devices.Count) { device = 0; } _outputDevice = new DirectSound(devices[device].DriverGuid); System.Windows.Interop.WindowInteropHelper wh = new System.Windows.Interop.WindowInteropHelper(Application.Current.MainWindow); _outputDevice.SetCooperativeLevel(wh.Handle, CooperativeLevel.Priority); _buffDescription = new SoundBufferDescription(); _buffDescription.Flags = BufferFlags.ControlPositionNotify | BufferFlags.ControlFrequency | BufferFlags.ControlEffects | BufferFlags.GlobalFocus | BufferFlags.GetCurrentPosition2; _buffDescription.BufferBytes = BufferByteSize * InternalBufferSizeMultiplier; WaveFormat format = new WaveFormat(16000, 16, 1); _buffDescription.Format = format; _soundBuffer = new SecondarySoundBuffer(_outputDevice, _buffDescription); _synchronizer = new AutoResetEvent(false); NotificationPosition[] nots = new NotificationPosition[InternalBufferSizeMultiplier]; NotificationPosition not; int bytepos = 800; for (int i = 0; i < InternalBufferSizeMultiplier; i++) { not = new NotificationPosition(); not.Offset = bytepos; not.WaitHandle = _synchronizer; nots[i] = not; bytepos += BufferByteSize; } _soundBuffer.SetNotificationPositions(nots); _waitThread = new Thread(new ThreadStart(DataRequestThread)) { Name = "MyWavePlayer.DataRequestThread" }; _waitThread.Start(); }
public DirectSoundSoundOutput(IHostAudioManager sound, IntPtr mainWindowHandle, string soundDevice) { _sound = sound; _retryCounter = 5; var deviceInfo = DirectSound.GetDevices().FirstOrDefault(d => d.Description == soundDevice); _device = deviceInfo != null ? new DirectSound(deviceInfo.DriverGuid) : new DirectSound(); _device.SetCooperativeLevel(mainWindowHandle, CooperativeLevel.Priority); }
public void Initialize() { soundDevice = new DirectSound(); soundDevice.SetCooperativeLevel(window.Handle, CooperativeLevel.Priority); FMODEX.RESULT result; result = FMODEX.Factory.System_Create(ref system); CheckError(result); result = system.init(1, FMODEX.INITFLAGS.NORMAL, (IntPtr)null); CheckError(result); }
//--------------------// #region Setup /// <summary> /// Helper called by the constructor to setup the audio-subsystem. /// </summary> /// <exception cref="SlimDX.DirectSound.DirectSoundException">internal errors occurred while intiliazing the sound card.</exception> private void SetupAudio() { AudioDevice = new DirectSound(); AudioDevice.SetCooperativeLevel(Target.Handle, CooperativeLevel.Priority); // ToDo //var buffer = new PrimarySoundBuffer(SoundDevice, new SoundBufferDescription {Flags = BufferFlags.Control3D | BufferFlags.PrimaryBuffer}); //_listener = new SoundListener3D(buffer) { RolloffFactor = 0.005f }; Music = new MusicManager(this); }
public void initialize(int samplesPerSecond, int bytesPerSample, int nrChannels, int bufferSizeBytes) { try { if (directSound == null) { directSound = new DirectSound(); directSound.SetCooperativeLevel(owner.Handle, CooperativeLevel.Priority); } releaseResources(); this.bufferSizeBytes = bufferSizeBytes; this.bytesPerSample = bytesPerSample; this.samplesPerSecond = samplesPerSecond; this.nrChannels = nrChannels; SoundBufferDescription desc = new SoundBufferDescription(); desc.BufferBytes = bufferSizeBytes; desc.Flags = BufferFlags.Defer | BufferFlags.GlobalFocus | BufferFlags.ControlVolume | BufferFlags.ControlFrequency | BufferFlags.GetCurrentPosition2; //desc.AlgorithmFor3D = Guid.Empty; int blockAlign = nrChannels * bytesPerSample; int averageBytesPerSecond = samplesPerSecond * blockAlign; WaveFormat format = WaveFormat.CreateCustomFormat(WaveFormatEncoding.Pcm, samplesPerSecond, nrChannels, averageBytesPerSecond, blockAlign, bytesPerSample * 8); desc.Format = format; silence = new char[bufferSizeBytes]; Array.Clear(silence, 0, silence.Length); audioBuffer = new SecondarySoundBuffer(directSound, desc); Volume = volume; offsetBytes = 0; prevPlayPos = 0; ptsPos = 0; prevPtsPos = 0; playLoops = 0; ptsLoops = 0; //log.Info("Direct Sound Initialized"); } catch (Exception e) { throw new VideoPlayerException("Error initializing Direct Sound: " + e.Message, e); } }
public static void Create() { if (Program.Form == null || Program.Form.IsDisposed) { return; } Device = new DirectSound(); Device.SetCooperativeLevel(Program.Form.Handle, CooperativeLevel.Normal); LoadSoundList(); }
public Sound(IntPtr handle) { test[1] = test[0] + 2; test[2] = test[1] + 2; test[3] = test[2] + 1; test[4] = test[3] + 2; test[5] = test[4] + 2; test[6] = test[5] + 2; DirectSound directSound = new DirectSound(); // Set Cooperative Level to PRIORITY (priority level can call the SetFormat and Compact methods) // directSound.SetCooperativeLevel(handle, CooperativeLevel.Priority); // Create PrimarySoundBuffer var primaryBufferDesc = new SoundBufferDescription(); primaryBufferDesc.Flags = BufferFlags.PrimaryBuffer; primaryBufferDesc.AlgorithmFor3D = Guid.Empty; var primarySoundBuffer = new PrimarySoundBuffer(directSound, primaryBufferDesc); // Play the PrimarySound Buffer primarySoundBuffer.Play(0, PlayFlags.Looping); // Default WaveFormat Stereo 44100 16 bit waveFormat = new WaveFormat(); // Create SecondarySoundBuffer var secondaryBufferDesc = new SoundBufferDescription(); secondaryBufferDesc.BufferBytes = waveFormat.ConvertLatencyToByteSize(10000); secondaryBufferDesc.Format = waveFormat; secondaryBufferDesc.Flags = BufferFlags.GetCurrentPosition2 | BufferFlags.ControlPositionNotify | BufferFlags.GlobalFocus | BufferFlags.ControlVolume | BufferFlags.StickyFocus; secondaryBufferDesc.AlgorithmFor3D = Guid.Empty; secondarySoundBuffer = new SecondarySoundBuffer(directSound, secondaryBufferDesc); // Get Capabilties from secondary sound buffer capabilities = secondarySoundBuffer.Capabilities; sounds = new short[capabilities.BufferBytes / waveFormat.BlockAlign]; // Play the song secondarySoundBuffer.Play(0, PlayFlags.Looping); for (int i = 0; i < sounds.Length; i++) { sounds[i] = 0; } }
public void Initialize(IntPtr handle) { if (isInitialized) { Dispose(); } isInitialized = false; LoadSettings(); //Create the device Console.WriteLine("DirectSound: Initializing directSound ..."); _SoundDevice = new DirectSound(); _SoundDevice.SetCooperativeLevel(handle, CooperativeLevel.Normal); //Create the wav format WaveFormat wav = new WaveFormat(); wav.FormatTag = WaveFormatTag.Pcm; wav.SamplesPerSecond = Program.Settings.Audio_Frequency; wav.Channels = 1; wav.BitsPerSample = Program.Settings.Audio_BitsPerSample; wav.AverageBytesPerSecond = wav.SamplesPerSecond * wav.Channels * (wav.BitsPerSample / 8); wav.BlockAlignment = (short)(wav.Channels * wav.BitsPerSample / 8); //BufferSize = (int)(wav.AverageBytesPerSecond * ((double)Program.Settings.Audio_BufferSizeInMilliseconds) / (double)1000); BufferSize = Program.Settings.Audio_BufferSizeInBytes; //latency_in_bytes = (int)((double)wav.AverageBytesPerSecond * (double)(Program.Settings.Audio_LatencyInPrecentage / (double)1000)); latency_in_bytes = (Program.Settings.Audio_LatencyInPrecentage * BufferSize) / 100; latency_in_samples = latency_in_bytes / 2; Console.WriteLine("DirectSound: BufferSize = " + BufferSize + " Byte"); Console.WriteLine("DirectSound: Latency in bytes = " + latency_in_bytes + " Byte"); //Description SoundBufferDescription des = new SoundBufferDescription(); des.Format = wav; des.SizeInBytes = BufferSize; des.Flags = BufferFlags.ControlVolume | BufferFlags.ControlFrequency | BufferFlags.ControlPan | BufferFlags.Software; buffer = new SecondarySoundBuffer(_SoundDevice, des); //buffer.Play(0, PlayFlags.Looping); // Set volume SetVolume(volume); Console.WriteLine("DirectSound: DirectSound initialized OK."); isInitialized = true; Shutdown(); }
void InitDevice(Guid device) { Device = new DirectSound(device); Device.SetCooperativeLevel(Handle, CooperativeLevel.Priority); /* search for highest possible sampling rate */ bool success = false; foreach (int rate in SamplingRates) { if (!success) { success = SetOutputRate(rate); } } }
public CSound(string fileName, int volume, Form controlForm) { try { if (_dSound == null) { _dSound = new DirectSound(); } _dSound.SetCooperativeLevel(controlForm.Handle, CooperativeLevel.Priority); SetSound(fileName, volume); } catch { throw new Exception("Sound-card is missing: aborting"); } }
public AudioDevice(IntPtr hwnd) { // initialise directsound _directSound = new DirectSound(); _directSound.SetCooperativeLevel(hwnd, CooperativeLevel.Priority); // create primary sound buffer var primaryBufferDesc = new SoundBufferDescription { Flags = BufferFlags.PrimaryBuffer, AlgorithmFor3D = Guid.Empty }; _primarySoundBuffer = new PrimarySoundBuffer(_directSound, primaryBufferDesc) { Format = new WaveFormat(), }; }
/// <summary> /// Initializes DirectSound for playback. /// </summary> /// <param name="WinHandle">A pointer to the main form of this program.</param> /// <param name="root">The root directory of the sounds.</param> public static void initialize(IntPtr WinHandle, String root) { playLock = new object(); maxMusicVol = 0.80f; setRootDirectory(root); SoundPath = "s"; NSoundPath = SoundPath + "\\n"; NumPath = NSoundPath + "\\ns"; objDS = new DirectSound(); //if this object is destroyed, all sounds created with it will also be flushed. objDS.SetCooperativeLevel(WinHandle, CooperativeLevel.Priority); //WinHandle must be passed from the main form // SpeakerConfiguration sConfig; //SpeakerGeometry sGeo; //objDS.GetSpeakerConfiguration(sConfig, sGeo); //objDS.SetSpeakerConfiguration(sConfig, SpeakerGeometry.None); //get the listener: setListener(); }
private void initDirectSound() { // create DirectSound object. directSound = new DirectSound(); // set cooperative level. directSound.SetCooperativeLevel(windowHandle, SlimDX.DirectSound.CooperativeLevel.Priority); // create the primary sound buffer. SoundBufferDescription desc = new SoundBufferDescription(); desc.Flags = SlimDX.DirectSound.BufferFlags.PrimaryBuffer; primaryBuffer = new PrimarySoundBuffer(directSound, desc); // create secondary sound buffer bgMusicBuffer = loadSoundFile("hustlepong_10.wav"); paddleHitBuffer = loadSoundFile("tennis_ball_hit_by_racket.wav"); wallHitBuffer = loadSoundFile("tennis_ball_single_bounce_floor_001.wav"); }
public DxPlaySound(int frequency) { device = new DirectSound(); //音频设备对象 IntPtr hwnd = new WindowInteropHelper(DisPlayWindow.HMainWindow).Handle; //设置窗口句柄 device.SetCooperativeLevel(hwnd, CooperativeLevel.Priority); //设置Wav音频文件对象属性 WaveFormat waveformat = SetWaveFormat(frequency); //设置通知对象 mNotifySize = waveformat.AverageBytesPerSecond / 5; //0.2S数据 int mainBufferSize = waveformat.AverageBytesPerSecond * 2; // 2s数据长度 cNotifyNum = mainBufferSize / mNotifySize; //通知个数 10 == 2s/0.2s //设置主缓存区 SoundBufferDescription sndBufferDesc = new SoundBufferDescription { SizeInBytes = mainBufferSize, Format = waveformat, Flags = BufferFlags.ControlPositionNotify | BufferFlags.ControlFrequency | BufferFlags.GlobalFocus | BufferFlags.GetCurrentPosition2 }; scdBuffer = new SecondarySoundBuffer(device, sndBufferDesc); //为声音建立二级缓存 if (scdBuffer != null) { mNotificationEvent = new AutoResetEvent(false); isRunning = true; Task.Factory.StartNew(NotifyThread); NotificationPosition[] positionNotify = new NotificationPosition[cNotifyNum]; //通知数组 for (int i = 0; i < cNotifyNum; i++) { positionNotify[i].Offset = mNotifySize * (i + 1) - 1; positionNotify[i].Event = mNotificationEvent; } scdBuffer.SetNotificationPositions(positionNotify); } }
public static void Startup() { DirectSoundDevice = new DirectSound(); if (DirectSoundDevice.SetCooperativeLevel(Process.GetCurrentProcess().MainWindowHandle, CooperativeLevel.Priority).IsFailure) { throw new InvalidOperationException("Initializing DirectSound was failed."); } PrimaryBufferDesc = new SoundBufferDescription { Format = null, Flags = BufferFlags.PrimaryBuffer, SizeInBytes = 0, }; PrimaryBuffer = new PrimarySoundBuffer(DirectSoundDevice, PrimaryBufferDesc); PrimaryBuffer.Play(0, PlayFlags.Looping); }
// Private Methods. private bool InitializeDirectSound(IntPtr windowHandler) { try { // Initialize the direct sound interface pointer for the default sound device. _DirectSound = new DirectSound(); try { _DirectSound.SetCooperativeLevel(windowHandler, CooperativeLevel.Priority); } catch { return(false); } // Setup the primary buffer description. SoundBufferDescription primaryBufferDesc = new SoundBufferDescription() { Flags = BufferFlags.PrimaryBuffer | BufferFlags.ControlVolume | BufferFlags.Control3D, AlgorithmFor3D = Guid.Empty }; // Get control of the primary sound buffer on the default sound device. _PrimaryBuffer = new PrimarySoundBuffer(_DirectSound, primaryBufferDesc); _Listener = new SoundListener3D(_PrimaryBuffer); _Listener.Deferred = false; _Listener.Position = new Vector3(0.0f, 0.0f, 0.0f); } catch (Exception) { return(false); } return(true); }
// Private Methods. private bool InitializeDirectSound(IntPtr windowHandler) { try { // Initialize the direct sound interface pointer for the default sound device. _DirectSound = new DirectSound(); try { _DirectSound.SetCooperativeLevel(windowHandler, CooperativeLevel.Priority); } catch { return(false); } // Setup the primary buffer description. SoundBufferDescription primaryBufferDesc = new SoundBufferDescription() { Flags = BufferFlags.PrimaryBuffer | BufferFlags.ControlVolume, AlgorithmFor3D = Guid.Empty }; // Get control of the primary sound buffer on the default sound device. _PrimaryBuffer = new PrimarySoundBuffer(_DirectSound, primaryBufferDesc); // Setup the format of the primary sound buffer. // In this case it is a . _PrimaryBuffer.Format = new WaveFormat(44100, 16, 2); } catch (Exception) { return(false); } return(true); }
private void InitDirectSound(Control parent) { Debug.WriteLine(this, "Initializing APU ....", DebugStatus.None); //Create the device _SoundDevice = new DirectSound(); _SoundDevice.SetCooperativeLevel(parent.Parent.Handle, CooperativeLevel.Normal); //Create the wav format var wav = new WaveFormat(); wav.FormatTag = WaveFormatTag.Pcm; wav.SamplesPerSecond = 44100; wav.Channels = (short) (STEREO ? 2 : 1); AD = (STEREO ? 4 : 2); //Stereo / Mono wav.BitsPerSample = 16; wav.AverageBytesPerSecond = wav.SamplesPerSecond*wav.Channels*(wav.BitsPerSample/8); wav.BlockAlignment = (short) (wav.Channels*wav.BitsPerSample/8); BufferSize = wav.AverageBytesPerSecond; //Description var des = new SoundBufferDescription { Format = wav, SizeInBytes = BufferSize, Flags = BufferFlags.ControlVolume | BufferFlags.ControlFrequency | BufferFlags.ControlPan | BufferFlags.ControlEffects }; //des.Flags = BufferFlags.GlobalFocus | BufferFlags.Software; //buffer DATA = new byte[BufferSize]; buffer = new SecondarySoundBuffer(_SoundDevice, des); buffer.Play(0, PlayFlags.Looping); //channels InitChannels(); Debug.WriteLine(this, "APU initialized ok !!", DebugStatus.Cool); }
/// <summary>Initialises the sound system.</summary> public override void Initialise() { _directSound = new DirectSound(); _directSound.SetCooperativeLevel(_control.Handle, CooperativeLevel.Priority); }
private void init_directsound() { try { device = new DirectSound(DirectSoundGuid.DefaultPlaybackDevice); device.SetCooperativeLevel(((Video)(video_reference)).Screen_Handle, CooperativeLevel.Normal); sound_buffers = new SecondarySoundBuffer[10]; sound_files = new WaveStream[10]; sound_statuses = new bool[10]; load_sound_file(ref stream, ref sound_files[0], ref sound_data, ref buf_desc, ref sound_buffers[0], "Ufo.wav", ref sound_statuses[0]); load_sound_file(ref stream, ref sound_files[1], ref sound_data, ref buf_desc, ref sound_buffers[1], "Shot.wav", ref sound_statuses[1]); load_sound_file(ref stream, ref sound_files[2], ref sound_data, ref buf_desc, ref sound_buffers[2], "BaseHit.wav", ref sound_statuses[2]); load_sound_file(ref stream, ref sound_files[3], ref sound_data, ref buf_desc, ref sound_buffers[3], "InvHit.wav", ref sound_statuses[3]); load_sound_file(ref stream, ref sound_files[4], ref sound_data, ref buf_desc, ref sound_buffers[4], "Walk1.wav", ref sound_statuses[4]); load_sound_file(ref stream, ref sound_files[5], ref sound_data, ref buf_desc, ref sound_buffers[5], "Walk2.wav", ref sound_statuses[5]); load_sound_file(ref stream, ref sound_files[6], ref sound_data, ref buf_desc, ref sound_buffers[6], "Walk3.wav", ref sound_statuses[6]); load_sound_file(ref stream, ref sound_files[7], ref sound_data, ref buf_desc, ref sound_buffers[7], "Walk4.wav", ref sound_statuses[7]); load_sound_file(ref stream, ref sound_files[8], ref sound_data, ref buf_desc, ref sound_buffers[8], "UfoHit.wav", ref sound_statuses[8]); load_sound_file(ref stream, ref sound_files[9], ref sound_data, ref buf_desc, ref sound_buffers[9], "ELife.wav", ref sound_statuses[9]); } catch { MessageBox.Show("A failure has been detected during DirectSound initialization, please contact the author for assistance.", "Error!", MessageBoxButtons.OK); critical_failure = true; } }
/// <summary> /// Constructs a new Audio Output Device. /// </summary> /// /// <param name="device">Global identifier of the audio output device.</param> /// <param name="owner">The owner window handle.</param> /// <param name="samplingRate">The sampling rate of the device.</param> /// <param name="channels">The number of channels of the device.</param> /// public AudioOutputDevice(Guid device, IntPtr owner, int samplingRate, int channels) { this.owner = owner; this.samplingRate = samplingRate; this.channels = channels; this.device = device; DirectSound ds = new DirectSound(device); ds.SetCooperativeLevel(owner, CooperativeLevel.Priority); // Set the output format WaveFormat waveFormat = new WaveFormat(); waveFormat.FormatTag = WaveFormatTag.IeeeFloat; waveFormat.BitsPerSample = 32; waveFormat.BlockAlignment = (short)(waveFormat.BitsPerSample * channels / 8); waveFormat.Channels = (short)channels; waveFormat.SamplesPerSecond = samplingRate; waveFormat.AverageBytesPerSecond = waveFormat.SamplesPerSecond * waveFormat.BlockAlignment; bufferSize = 8 * waveFormat.AverageBytesPerSecond; // Setup the secondary buffer SoundBufferDescription desc2 = new SoundBufferDescription(); desc2.Flags = BufferFlags.GlobalFocus | BufferFlags.ControlPositionNotify | BufferFlags.GetCurrentPosition2; desc2.SizeInBytes = bufferSize; desc2.Format = waveFormat; buffer = new SecondarySoundBuffer(ds, desc2); var list = new List<NotificationPosition>(); int numberOfPositions = 32; // Set notification for buffer percentiles for (int i = 0; i < numberOfPositions; i++) { list.Add(new NotificationPosition() { Event = new AutoResetEvent(false), Offset = i * bufferSize / numberOfPositions + 1, }); } // Set notification for end of buffer list.Add(new NotificationPosition() { Offset = bufferSize - 1, Event = new AutoResetEvent(false) }); firstHalfBufferIndex = numberOfPositions / 2; secondHalfBufferIndex = numberOfPositions; notifications = list.ToArray(); System.Diagnostics.Debug.Assert(notifications[firstHalfBufferIndex].Offset == bufferSize / 2 + 1); System.Diagnostics.Debug.Assert(notifications[secondHalfBufferIndex].Offset == bufferSize - 1); // Make a copy of the wait handles waitHandles = new WaitHandle[notifications.Length]; for (int i = 0; i < notifications.Length; i++) waitHandles[i] = notifications[i].Event; // Store all notification positions buffer.SetNotificationPositions(notifications); }