Exemplo n.º 1
0
        /// <summary>
        /// Initialize the media element for playback
        /// </summary>
        /// <param name="streamConfig">Object containing stream configuration details</param>
        void InitializeMediaPlayer(MoonlightStreamConfiguration streamConfig, AvStreamSource streamSource)
        {
            this._streamSource = streamSource;

            _videoMss = new MediaStreamSource(new VideoStreamDescriptor(VideoEncodingProperties.CreateH264()));
            _videoMss.BufferTime = TimeSpan.Zero;
            _videoMss.CanSeek = false;
            _videoMss.Duration = TimeSpan.Zero;
            _videoMss.SampleRequested += _videoMss_SampleRequested;

            XAudio2 xaudio = new XAudio2();
            MasteringVoice masteringVoice = new MasteringVoice(xaudio, 2, 48000);
            WaveFormat format = new WaveFormat(48000, 16, 2);

            // Set for low latency playback
            StreamDisplay.RealTimePlayback = true;

            // Render on the full window to avoid extra compositing
            StreamDisplay.IsFullWindow = true;

            // Disable built-in transport controls
            StreamDisplay.AreTransportControlsEnabled = false;

            // Start playing right away
            StreamDisplay.AutoPlay = true;

            StreamDisplay.SetMediaStreamSource(_videoMss);

            AvStream.SetSourceVoice(new SourceVoice(xaudio, format));
        }
Exemplo n.º 2
0
        private void CreateSourceVoice(XAudio2 device, SharpDX.Multimedia.WaveFormat sourceFormat, SharpDX.XAudio2.VoiceFlags flags, float maxFrequencyRatio, IntPtr callback, EffectDescriptor[] effectDescriptors)
        {
            var waveformatPtr = WaveFormat.MarshalToPtr(sourceFormat);

            try
            {
                if (effectDescriptors != null)
                {
                    unsafe
                    {
                        var tempSendDescriptor      = new EffectChain();
                        var effectDescriptorNatives = new EffectDescriptor.__Native[effectDescriptors.Length];
                        for (int i = 0; i < effectDescriptorNatives.Length; i++)
                        {
                            effectDescriptors[i].__MarshalTo(ref effectDescriptorNatives[i]);
                        }
                        tempSendDescriptor.EffectCount = effectDescriptorNatives.Length;
                        fixed(void *pEffectDescriptors = &effectDescriptorNatives[0])
                        {
                            tempSendDescriptor.EffectDescriptorPointer = (IntPtr)pEffectDescriptors;
                            device.CreateSourceVoice_(this, waveformatPtr, flags, maxFrequencyRatio, callback, null, tempSendDescriptor);
                        }
                    }
                }
                else
                {
                    device.CreateSourceVoice_(this, waveformatPtr, flags, maxFrequencyRatio, callback, null, null);
                }
            }
            finally
            {
                Marshal.FreeHGlobal(waveformatPtr);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Loads a sound file from the given resource.
        /// </summary>
        /// <param name="resource">The resource to load.</param>
        public static async Task <CachedSoundFile> FromResourceAsync(ResourceLink resource)
        {
            resource.EnsureNotNull(nameof(resource));

            CachedSoundFile result = new CachedSoundFile();

            using (Stream inStream = await resource.OpenInputStreamAsync())
                using (SDXM.SoundStream stream = new SDXM.SoundStream(inStream))
                {
                    await Task.Factory.StartNew(() =>
                    {
                        // Read all data into the adio buffer
                        SDXM.WaveFormat waveFormat = stream.Format;
                        XA.AudioBuffer buffer      = new XA.AudioBuffer
                        {
                            Stream     = stream.ToDataStream(),
                            AudioBytes = (int)stream.Length,
                            Flags      = XA.BufferFlags.EndOfStream
                        };

                        // Store members
                        result.m_decodedPacketsInfo = stream.DecodedPacketsInfo;
                        result.m_format             = waveFormat;
                        result.m_audioBuffer        = buffer;
                    });
                }

            return(result);
        }
Exemplo n.º 4
0
        private void DirectSound_Start(object sender, EventArgs e)
        {
            soundStream = new SoundStream(File.OpenRead(loadFilePath));
            WaveFormat format = soundStream.Format;

            AudioBuffer buffer = new AudioBuffer
            {
                Stream     = soundStream.ToDataStream(),
                AudioBytes = (int)soundStream.Length,
                Flags      = BufferFlags.EndOfStream
            };

            soundStream.Close();

            sourceVoice = new SourceVoice(xAudio2, format, true);
            sourceVoice.SubmitSourceBuffer(buffer, soundStream.DecodedPacketsInfo);
            sourceVoice.Start();

            if (directSoundEffect == 0)
            {
                SharpDX.XAPO.Fx.Echo effectEcho       = new SharpDX.XAPO.Fx.Echo(xAudio2);
                EffectDescriptor     effectDescriptor = new EffectDescriptor(effectEcho);
                sourceVoice.SetEffectChain(effectDescriptor);
                sourceVoice.EnableEffect(0);
            }
            else if (directSoundEffect == 1)
            {
                SharpDX.XAPO.Fx.Reverb effectReverb     = new SharpDX.XAPO.Fx.Reverb(xAudio2);
                EffectDescriptor       effectDescriptor = new EffectDescriptor(effectReverb);
                sourceVoice.SetEffectChain(effectDescriptor);
                sourceVoice.EnableEffect(0);
            }
        }
Exemplo n.º 5
0
 // Method to marshal from native to managed struct
 internal unsafe void __MarshalFrom(__Native* @ref)
 {
     this.Format = null;
     this.FormatPointer = @ref->FormatPointer;
     if (this.FormatPointer != IntPtr.Zero)
         this.Format = WaveFormat.MarshalFrom(this.FormatPointer);
     this.MaxFrameCount = @ref->MaxFrameCount;
 }
Exemplo n.º 6
0
        public MySourceVoice(XAudio2 device, WaveFormat sourceFormat)
        {
            m_voice = new SourceVoice(device, sourceFormat, true);
            m_voice.BufferEnd += OnStopPlaying;
            m_valid = true;

            Flush();
        }
Exemplo n.º 7
0
        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);
        }
Exemplo n.º 8
0
        public MySourceVoice(XAudio2 device, WaveFormat sourceFormat)
        {
            m_voice = new SourceVoice(device, sourceFormat, true);
            m_voice.BufferEnd += OnStopPlayingBuffered;
            m_valid = true;
            m_dataStreams = new Queue<DataStream>();

            Flush();
        }
Exemplo n.º 9
0
 public MySourceVoicePool(XAudio2 audioEngine, WaveFormat waveformat, MyCueBank owner)
 {
     m_audioEngine = audioEngine;
     m_waveFormat = waveformat;
     m_owner = owner;
     m_availableVoices = new MyConcurrentQueue<MySourceVoice>(32);
     m_fadingOutVoices = new List<MySourceVoice>();
     m_currentCount = 0;
 }
Exemplo n.º 10
0
 /// <summary>
 /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
 /// </summary>
 public void Dispose()
 {
     if (m_audioBuffer != null)
     {
         GraphicsHelper.DisposeObject(m_audioBuffer.Stream);
         m_format      = null;
         m_audioBuffer = null;
     }
 }
Exemplo n.º 11
0
 public XAudioSound(string filename, XAudioDevice device)
     : base(filename, device)
 {
     xAudio = device.XAudio2;
     using (var stream = LoadStream("Content/" + filename + ".wav"))
     {
         format = stream.Format;
         length = CalculateLengthInSeconds(format, (int)stream.Length);
         buffer = CreateAudioBuffer(stream.ToDataStream());
         decodedInfo = stream.DecodedPacketsInfo;
     }
 }
Exemplo n.º 12
0
        /// <summary>
        /// Creates and configures a source voice.
        /// </summary>
        /// <param name="device">an instance of <see cref = "SharpDX.XAudio2.XAudio2" /></param>
        /// <param name="sourceFormat">[in]  Pointer to a <see cref="SharpDX.Multimedia.WaveFormat"/> structure. This structure contains the expected format for all audio buffers submitted to the source voice. XAudio2 supports voice types of PCM, xWMA, ADPCM (Windows only), and XMA (Xbox 360 only). XAudio2 supports the following PCM formats.   8-bit (unsigned) integer PCM   16-bit integer PCM (Optimal format for XAudio2)   20-bit integer PCM (either in 24 or 32 bit containers)   24-bit integer PCM (either in 24 or 32 bit containers)   32-bit integer PCM   32-bit float PCM (Preferred format after 16-bit integer)   The number of channels in a source voice must be less than or equal to XAUDIO2_MAX_AUDIO_CHANNELS. The sample rate of a source voice must be between XAUDIO2_MIN_SAMPLE_RATE and XAUDIO2_MAX_SAMPLE_RATE. Note Data formats such as XMA, {{ADPCM}}, and {{xWMA}} that require more information than provided by <see cref="SharpDX.Multimedia.WaveFormat"/> have a <see cref="SharpDX.Multimedia.WaveFormat"/> structure as the first member in their format structure. When creating a source voice with one of those formats cast the format's structure as a <see cref="SharpDX.Multimedia.WaveFormat"/> structure and use it as the value for pSourceFormat. </param>
        /// <param name="flags">[in]  Flags that specify the behavior of the source voice. A flag can be 0 or a combination of one or more of the following: ValueDescriptionXAUDIO2_VOICE_NOPITCHNo pitch control is available on the voice.?XAUDIO2_VOICE_NOSRCNo sample rate conversion is available on the voice, the voice's  outputs must have the same sample rate.Note The XAUDIO2_VOICE_NOSRC flag causes the voice to behave as though the XAUDIO2_VOICE_NOPITCH flag also is specified. ?XAUDIO2_VOICE_USEFILTERThe filter effect should be available on this voice.?XAUDIO2_VOICE_MUSICThe voice is used to play background music. The system automatically  can replace the voice with music selected by the user.? </param>
        /// <param name="maxFrequencyRatio">[in]  Highest allowable frequency ratio that can be set on this voice. The value for this argument must be between XAUDIO2_MIN_FREQ_RATIO and XAUDIO2_MAX_FREQ_RATIO. Subsequent calls to <see cref="SharpDX.XAudio2.SourceVoice.SetFrequencyRatio"/> are clamped between XAUDIO2_MIN_FREQ_RATIO and MaxFrequencyRatio. The maximum value for this argument is defined as XAUDIO2_MAX_FREQ_RATIO, which allows pitch to be raised by up to 10 octaves. If MaxFrequencyRatio is less than 1.0, the voice will use that ratio immediately after being created (rather than the default of 1.0). Xbox 360  For XMA voices there is an additional restriction on the MaxFrequencyRatio argument and the voice's sample rate. The product of these two numbers cannot exceed XAUDIO2_MAX_RATIO_TIMES_RATE_XMA_MONO for one-channel voices or XAUDIO2_MAX_RATIO_TIMES_RATE_XMA_MULTICHANNEL for voices with any other number of channels. If the value specified for MaxFrequencyRatio is too high for the specified format, the call to CreateSourceVoice fails and produces a debug message.  Note XAudio2's memory usage can be reduced by using the lowest possible MaxFrequencyRatio value. </param>
        /// <param name="callback">[in, optional]  Pointer to a client-provided callback interface, <see cref="SharpDX.XAudio2.VoiceCallback"/>. </param>
        /// <returns>No documentation.</returns>
        /// <unmanaged>HRESULT IXAudio2::CreateSourceVoice([Out] IXAudio2SourceVoice** ppSourceVoice,[In] const WAVEFORMATEX* pSourceFormat,[None] UINT32 Flags,[None] float MaxFrequencyRatio,[In, Optional] IXAudio2VoiceCallback* pCallback,[In, Optional] const XAUDIO2_VOICE_SENDS* pSendList,[In, Optional] const XAUDIO2_EFFECT_CHAIN* pEffectChain)</unmanaged>
        public SourceVoice(XAudio2 device, SharpDX.Multimedia.WaveFormat sourceFormat, SharpDX.XAudio2.VoiceFlags flags, float maxFrequencyRatio, VoiceCallback callback)
            : base(IntPtr.Zero)
        {
            var waveformatPtr = WaveFormat.MarshalToPtr(sourceFormat);

            try
            {
                device.CreateSourceVoice_(this, waveformatPtr, flags, maxFrequencyRatio, callback == null ? IntPtr.Zero : VoiceShadow.ToIntPtr(callback), null, null);
            } finally
            {
                Marshal.FreeHGlobal(waveformatPtr);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Creates and configures a source voice with callback through delegates.
        /// </summary>
        /// <param name="device">an instance of <see cref="SharpDX.XAudio2.XAudio2" /></param>
        /// <param name="sourceFormat">[in]  Pointer to a <see cref="SharpDX.Multimedia.WaveFormat" /> structure. This structure contains the expected format for all audio buffers submitted to the source voice. XAudio2 supports voice types of PCM, xWMA, ADPCM (Windows only), and XMA (Xbox 360 only). XAudio2 supports the following PCM formats.   8-bit (unsigned) integer PCM   16-bit integer PCM (Optimal format for XAudio2)   20-bit integer PCM (either in 24 or 32 bit containers)   24-bit integer PCM (either in 24 or 32 bit containers)   32-bit integer PCM   32-bit float PCM (Preferred format after 16-bit integer)   The number of channels in a source voice must be less than or equal to XAUDIO2_MAX_AUDIO_CHANNELS. The sample rate of a source voice must be between XAUDIO2_MIN_SAMPLE_RATE and XAUDIO2_MAX_SAMPLE_RATE. Note Data formats such as XMA, {{ADPCM}}, and {{xWMA}} that require more information than provided by <see cref="SharpDX.Multimedia.WaveFormat" /> have a <see cref="SharpDX.Multimedia.WaveFormat" /> structure as the first member in their format structure. When creating a source voice with one of those formats cast the format's structure as a <see cref="SharpDX.Multimedia.WaveFormat" /> structure and use it as the value for pSourceFormat.</param>
        /// <param name="flags">[in]  Flags that specify the behavior of the source voice. A flag can be 0 or a combination of one or more of the following: ValueDescriptionXAUDIO2_VOICE_NOPITCHNo pitch control is available on the voice.?XAUDIO2_VOICE_NOSRCNo sample rate conversion is available on the voice, the voice's  outputs must have the same sample rate.Note The XAUDIO2_VOICE_NOSRC flag causes the voice to behave as though the XAUDIO2_VOICE_NOPITCH flag also is specified. ?XAUDIO2_VOICE_USEFILTERThe filter effect should be available on this voice.?XAUDIO2_VOICE_MUSICThe voice is used to play background music. The system automatically  can replace the voice with music selected by the user.?</param>
        /// <param name="maxFrequencyRatio">[in]  Highest allowable frequency ratio that can be set on this voice. The value for this argument must be between XAUDIO2_MIN_FREQ_RATIO and XAUDIO2_MAX_FREQ_RATIO. Subsequent calls to <see cref="SharpDX.XAudio2.SourceVoice.SetFrequencyRatio" /> are clamped between XAUDIO2_MIN_FREQ_RATIO and MaxFrequencyRatio. The maximum value for this argument is defined as XAUDIO2_MAX_FREQ_RATIO, which allows pitch to be raised by up to 10 octaves. If MaxFrequencyRatio is less than 1.0, the voice will use that ratio immediately after being created (rather than the default of 1.0). Xbox 360  For XMA voices there is an additional restriction on the MaxFrequencyRatio argument and the voice's sample rate. The product of these two numbers cannot exceed XAUDIO2_MAX_RATIO_TIMES_RATE_XMA_MONO for one-channel voices or XAUDIO2_MAX_RATIO_TIMES_RATE_XMA_MULTICHANNEL for voices with any other number of channels. If the value specified for MaxFrequencyRatio is too high for the specified format, the call to CreateSourceVoice fails and produces a debug message.  Note XAudio2's memory usage can be reduced by using the lowest possible MaxFrequencyRatio value.</param>
        /// <param name="enableCallbackEvents">if set to <c>true</c> [enable callback events].</param>
        /// <returns>No enableCallbackEvents.</returns>
        ///   <unmanaged>HRESULT IXAudio2::CreateSourceVoice([Out] IXAudio2SourceVoice** ppSourceVoice,[In] const WAVEFORMATEX* pSourceFormat,[None] UINT32 Flags,[None] float MaxFrequencyRatio,[In, Optional] IXAudio2VoiceCallback* pCallback,[In, Optional] const XAUDIO2_VOICE_SENDS* pSendList,[In, Optional] const XAUDIO2_EFFECT_CHAIN* pEffectChain)</unmanaged>
        public SourceVoice(XAudio2 device, SharpDX.Multimedia.WaveFormat sourceFormat, SharpDX.XAudio2.VoiceFlags flags, float maxFrequencyRatio, bool enableCallbackEvents)
            : base(IntPtr.Zero)
        {
            var waveformatPtr = WaveFormat.MarshalToPtr(sourceFormat);

            try
            {
                device.CreateSourceVoice_(this, waveformatPtr, flags, maxFrequencyRatio, enableCallbackEvents ? VoiceShadow.ToIntPtr(voiceCallbackImpl = new VoiceCallbackImpl(this)) : IntPtr.Zero, null, null);
            } finally
            {
                Marshal.FreeHGlobal(waveformatPtr);
            }
        }
        /// <summary>Creates a sound.</summary>
        /// <param name="samples">A byte array containing the sample data (Mono 16-bit Signed samples).</param>
        /// <param name="frequency">The sample frequency in herz.</param>
        /// <param name="soundIndex">The index of the sound.</param>
        /// <param name="speakerSound">Whether the sound is a speaker sound otherwise it is a sampled sound.</param>
        /// <returns>The Sound.</returns>
        public override SoundSystem.Sound CreateSound(byte[] samples, int frequency, int soundIndex, bool speakerSound)
        {
            WaveFormat waveFormat = new WaveFormat(frequency, 16, 1);

            SoundBufferDescription soundBufferDescription = new SoundBufferDescription();
            soundBufferDescription.Format = waveFormat;
            soundBufferDescription.Flags = BufferFlags.ControlVolume;
            soundBufferDescription.BufferBytes = samples.Length;

            SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(_directSound, soundBufferDescription);
            secondarySoundBuffer.Write(samples, 0, LockFlags.EntireBuffer);

            return new SharpDXSound(secondarySoundBuffer);
        }
Exemplo n.º 15
0
        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();
        }
Exemplo n.º 16
0
        public MyInMemoryWave(MyObjectBuilder_CueDefinition cue, string filename)
        {
            m_stream = new SoundStream(File.OpenRead(filename));
            m_waveFormat = m_stream.Format;
            m_buffer = new AudioBuffer
                            {
                                Stream = m_stream.ToDataStream(),
                                AudioBytes = (int)m_stream.Length,
                                Flags = BufferFlags.None
                            };

            if (cue.Loopable)
                m_buffer.LoopCount = AudioBuffer.LoopInfinite;

            m_stream.Close();
        }
Exemplo n.º 17
0
        /// <summary>
        /// Function to play an mp3.
        /// </summary>
        /// <param name="path">The path to the mp3 file.</param>
        public async Task PlayMp3Async(string path)
        {
            if (_currentPlayback != null)
            {
                await _currentPlayback;
                return;
            }

            _tokenSource     = new CancellationTokenSource();
            _currentPlayback = Task.Run(() =>
            {
                var stream           = new Mm.SoundStream(File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None));
                Mm.WaveFormat format = stream.Format;
                var buffer           = new Xa.AudioBuffer
                {
                    Stream     = stream.ToDataStream(),
                    AudioBytes = (int)stream.Length,
                    Flags      = Xa.BufferFlags.EndOfStream
                };

                stream.Close();

                var source = new Xa.SourceVoice(_audio, format);
                source.SubmitSourceBuffer(buffer, stream.DecodedPacketsInfo);
                source.Start();

                try
                {
                    while ((!_tokenSource.Token.IsCancellationRequested) && (!source.IsDisposed) && (source.State.BuffersQueued > 0))
                    {
                        Thread.Sleep(10);
                    }

                    source.Stop();
                }
                finally
                {
                    buffer.Stream?.Dispose();
                    source.Dispose();
                    stream?.Dispose();
                }
            }, _tokenSource.Token);

            await _currentPlayback;

            _currentPlayback = null;
        }
Exemplo n.º 18
0
        public PlayForm()
        {
            InitializeComponent();

            // Initalize XAudio2
            xaudio2 = new XAudio2(XAudio2Flags.None, ProcessorSpecifier.DefaultProcessor);
            masteringVoice = new MasteringVoice(xaudio2);

            var waveFormat = new WaveFormat(44100, 32, 2);
             sourceVoice = new SourceVoice(xaudio2, waveFormat);

            int bufferSize = waveFormat.ConvertLatencyToByteSize(60000);
            DataStream dataStream = new DataStream(bufferSize, true, true);

            // Prepare the initial sound to modulate
            int numberOfSamples = bufferSize / waveFormat.BlockAlign;
            for (int i = 0; i < numberOfSamples; i++)
            {
                float value = (float)(Math.Cos(2 * Math.PI * 220.0 * i / waveFormat.SampleRate) * 0.5);
                dataStream.Write(value);
                dataStream.Write(value);
            }
            dataStream.Position = 0;

            audioBuffer = new AudioBuffer
                              {
                                  Stream = dataStream,
                                  Flags = BufferFlags.EndOfStream,
                                  AudioBytes = bufferSize,
                                  LoopBegin = 0,
                                  LoopLength = numberOfSamples,
                                  LoopCount = AudioBuffer.LoopInfinite
                              };

            // Set the effect on the source
            ModulatorEffect = new ModulatorEffect();
            modulatorDescriptor = new EffectDescriptor(ModulatorEffect);
            reverb = new Reverb(xaudio2);
            effectDescriptor = new EffectDescriptor(reverb);
            //sourceVoice.SetEffectChain(modulatorDescriptor, effectDescriptor);
            sourceVoice.SetEffectChain(modulatorDescriptor);
            //sourceVoice.EnableEffect(0);

            this.Closed += new EventHandler(PlayForm_Closed);
        }
Exemplo n.º 19
0
        public MySourceVoice(MySourceVoicePool owner, XAudio2 device, WaveFormat sourceFormat)
        {
            // This value influences how many native memory is allocated in XAudio
            // When shifting sound to higher frequency it needs more data, because it's compressed in time
            // Ratio 2 equals to 11 or 12 semitones (=1 octave)
            // Values around 32 should be pretty safe
            // Values around 128 needs large amount of memory
            // Values > 128 are memory killer
            const float MaxFrequencyRatio = 2;

            m_voice = new SourceVoice(device, sourceFormat, VoiceFlags.UseFilter, MaxFrequencyRatio, true);
            m_voice.BufferEnd += OnStopPlaying;
            m_valid = true;

            m_owner = owner;
            m_owner.OnAudioEngineChanged += m_owner_OnAudioEngineChanged;
            Flush();
        }
Exemplo n.º 20
0
        /// <summary>
        /// Load the sound data from the sound-file.
        /// </summary>
        public override void Load()
        {
            var nativeFileStream = new NativeFileStream(
                File.Path,
                NativeFileMode.Open,
                NativeFileAccess.Read,
                NativeFileShare.Read);

            m_soundStream = new SoundStream(nativeFileStream);
            m_waveFormat = m_soundStream.Format;
            m_buffer = new AudioBuffer
            {
                Stream = m_soundStream.ToDataStream(),
                AudioBytes = (int)m_soundStream.Length,
                Flags = BufferFlags.EndOfStream
            };

            OnLoaded();
        }
        public MyInMemoryWave(MySoundData cue, string path)
        {
            using (var stream = MyFileSystem.OpenRead(path))
            {
                m_stream = new SoundStream(stream);
                m_waveFormat = m_stream.Format;
                m_buffer = new AudioBuffer
                {
                    Stream = m_stream.ToDataStream(),
                    AudioBytes = (int)m_stream.Length,
                    Flags = BufferFlags.None
                };

                if (cue.Loopable)
                    m_buffer.LoopCount = AudioBuffer.LoopInfinite;

                m_stream.Close();
            }
        }
Exemplo n.º 22
0
        private int historySize; // buffers

        #endregion Fields

        #region Constructors

        public BeatDetector(WaveFormat waveFormat, int historyLength, int bufferSize)
        {
            //this.bufferSize = bufferSize;
            this.historyLength = historyLength;

            // Number of history buffers needed to be equivalent to historyLength (milliseconds)
            historySize = waveFormat.ConvertLatencyToByteSize(historyLength) / bufferSize;
            beatsSize = historySize;

            history = new float[historySize];
            historyIndex = 0;

            beats = new float[beatsSize];
            beatIndex = 0;

            fft = new FastFourierTransform(beatsSize, 1);

            InstantaneousEnergy = 0.0f;
            AverageEnergy = 0.0f;
        }
Exemplo n.º 23
0
        public SoundEffect(string soundFxPath)
        {
            _xaudio = new XAudio2();
            var masteringsound = new MasteringVoice(_xaudio);

            var nativefilestream = new NativeFileStream(
            soundFxPath,
            NativeFileMode.Open,
            NativeFileAccess.Read,
            NativeFileShare.Read);

            _soundstream = new SoundStream(nativefilestream);
            _waveFormat = _soundstream.Format;
            _buffer = new AudioBuffer
            {
                Stream = _soundstream.ToDataStream(),
                AudioBytes = (int)_soundstream.Length,
                Flags = BufferFlags.EndOfStream
            };
        }
Exemplo n.º 24
0
        /// <summary>
        /// SharpDX XAudio2 sample. Plays a generated sound with some reverb.
        /// </summary>
        static void Main(string[] args)
        {
            var xaudio2 = new XAudio2();
            var masteringVoice = new MasteringVoice(xaudio2);

            var waveFormat = new WaveFormat(44100, 32, 2);
            var sourceVoice = new SourceVoice(xaudio2, waveFormat);

            int bufferSize = waveFormat.ConvertLatencyToByteSize(60000);
            var dataStream = new DataStream(bufferSize, true, true);

            int numberOfSamples = bufferSize/waveFormat.BlockAlign;
            for (int i = 0; i < numberOfSamples; i++)
            {
                double vibrato = Math.Cos(2 * Math.PI * 10.0 * i / waveFormat.SampleRate);
                float value = (float) (Math.Cos(2*Math.PI*(220.0 + 4.0*vibrato)*i/waveFormat.SampleRate)*0.5); 
                dataStream.Write(value);
                dataStream.Write(value);
            }
            dataStream.Position = 0;

            var audioBuffer = new AudioBuffer {Stream = dataStream, Flags = BufferFlags.EndOfStream, AudioBytes = bufferSize};

            var reverb = new Reverb();
            var effectDescriptor = new EffectDescriptor(reverb);
            sourceVoice.SetEffectChain(effectDescriptor);
            sourceVoice.EnableEffect(0);

            sourceVoice.SubmitSourceBuffer(audioBuffer, null);

            sourceVoice.Start();

            Console.WriteLine("Play sound");
            for(int i = 0; i < 60; i++)
            {
                Console.Write(".");
                Console.Out.Flush();
                Thread.Sleep(1000);
            }
        }
Exemplo n.º 25
0
 /// <summary>
 /// Helper function to marshal WaveFormat to an IntPtr
 /// </summary>
 /// <param name="format">WaveFormat</param>
 /// <returns>IntPtr to WaveFormat structure (needs to be freed by callee)</returns>
 public static IntPtr MarshalToPtr(WaveFormat format)
 {
     if (format == null) return IntPtr.Zero;
     return format.MarshalToPtr();
 }
Exemplo n.º 26
0
        /// <summary>
        /// Helper function to retrieve a WaveFormat structure from a pointer
        /// </summary>
        /// <param name="pointer">Pointer to the WaveFormat rawdata</param>
        /// <returns>WaveFormat structure</returns>
        public static unsafe WaveFormat MarshalFrom(IntPtr pointer)
        {
            if (pointer == IntPtr.Zero) return null;

            var pcmWaveFormat = *(__PcmNative*)pointer;
            var encoding = pcmWaveFormat.waveFormatTag;

            // Load simple PcmWaveFormat if channels <= 2 and encoding is Pcm, IeeFloat, Wmaudio2, Wmaudio3
            // See http://msdn.microsoft.com/en-us/library/microsoft.directx_sdk.xaudio2.waveformatex%28v=vs.85%29.aspx
            if (pcmWaveFormat.channels <= 2 && (encoding == WaveFormatEncoding.Pcm || encoding == WaveFormatEncoding.IeeeFloat || encoding == WaveFormatEncoding.Wmaudio2 || encoding == WaveFormatEncoding.Wmaudio3))
            {
                var waveFormat = new WaveFormat();
                waveFormat.__MarshalFrom(ref pcmWaveFormat);
                return waveFormat;
            }

            if (encoding == WaveFormatEncoding.Extensible)
            {
                var waveFormat = new WaveFormatExtensible();
                waveFormat.__MarshalFrom(ref *(WaveFormatExtensible.__Native*)pointer);
                return waveFormat;
            }

            if (encoding == WaveFormatEncoding.Adpcm)
            {
                var waveFormat = new WaveFormatAdpcm();
                waveFormat.__MarshalFrom(ref *(WaveFormatAdpcm.__Native*)pointer);
                return waveFormat;
            }

            throw new InvalidOperationException(string.Format("Unsupported WaveFormat [{0}]", encoding));
        }
Exemplo n.º 27
0
 /// <summary>
 /// Creates a new 32 bit IEEE floating point wave format
 /// </summary>
 /// <param name="sampleRate">sample rate</param>
 /// <param name="channels">number of channels</param>
 public static WaveFormat CreateIeeeFloatWaveFormat(int sampleRate, int channels)
 {
     var wf = new WaveFormat
                  {
                      waveFormatTag = WaveFormatEncoding.IeeeFloat,
                      channels = (short) channels,
                      bitsPerSample = 32,
                      sampleRate = sampleRate,
                      blockAlign = (short) (4*channels)
                  };
     wf.averageBytesPerSecond = sampleRate * wf.blockAlign;
     wf.extraSize = 0;
     return wf;
 }
Exemplo n.º 28
0
 /// <summary>
 /// Creates a WaveFormat with custom members
 /// </summary>
 /// <param name="tag">The encoding</param>
 /// <param name="sampleRate">Sample Rate</param>
 /// <param name="channels">Number of channels</param>
 /// <param name="averageBytesPerSecond">Average Bytes Per Second</param>
 /// <param name="blockAlign">Block Align</param>
 /// <param name="bitsPerSample">Bits Per Sample</param>
 /// <returns></returns>
 public static WaveFormat CreateCustomFormat(WaveFormatEncoding tag, int sampleRate, int channels, int averageBytesPerSecond, int blockAlign, int bitsPerSample)
 {
     var waveFormat = new WaveFormat
                          {
                              waveFormatTag = tag,
                              channels = (short) channels,
                              sampleRate = sampleRate,
                              averageBytesPerSecond = averageBytesPerSecond,
                              blockAlign = (short) blockAlign,
                              bitsPerSample = (short) bitsPerSample,
                              extraSize = 0
                          };
     return waveFormat;
 }
Exemplo n.º 29
0
 /// <summary>
 /// Creates and configures a source voice with callback through delegates.
 /// </summary>
 /// <param name="device">an instance of <see cref="SharpDX.XAudio2.XAudio2" /></param>
 /// <param name="sourceFormat">[in]  Pointer to a <see cref="SharpDX.Multimedia.WaveFormat" /> structure. This structure contains the expected format for all audio buffers submitted to the source voice. XAudio2 supports voice types of PCM, xWMA, ADPCM (Windows only), and XMA (Xbox 360 only). XAudio2 supports the following PCM formats.   8-bit (unsigned) integer PCM   16-bit integer PCM (Optimal format for XAudio2)   20-bit integer PCM (either in 24 or 32 bit containers)   24-bit integer PCM (either in 24 or 32 bit containers)   32-bit integer PCM   32-bit float PCM (Preferred format after 16-bit integer)   The number of channels in a source voice must be less than or equal to XAUDIO2_MAX_AUDIO_CHANNELS. The sample rate of a source voice must be between XAUDIO2_MIN_SAMPLE_RATE and XAUDIO2_MAX_SAMPLE_RATE. Note Data formats such as XMA, {{ADPCM}}, and {{xWMA}} that require more information than provided by <see cref="SharpDX.Multimedia.WaveFormat" /> have a <see cref="SharpDX.Multimedia.WaveFormat" /> structure as the first member in their format structure. When creating a source voice with one of those formats cast the format's structure as a <see cref="SharpDX.Multimedia.WaveFormat" /> structure and use it as the value for pSourceFormat.</param>
 /// <param name="flags">[in]  Flags that specify the behavior of the source voice. A flag can be 0 or a combination of one or more of the following: ValueDescriptionXAUDIO2_VOICE_NOPITCHNo pitch control is available on the voice.?XAUDIO2_VOICE_NOSRCNo sample rate conversion is available on the voice, the voice's  outputs must have the same sample rate.Note The XAUDIO2_VOICE_NOSRC flag causes the voice to behave as though the XAUDIO2_VOICE_NOPITCH flag also is specified. ?XAUDIO2_VOICE_USEFILTERThe filter effect should be available on this voice.?XAUDIO2_VOICE_MUSICThe voice is used to play background music. The system automatically  can replace the voice with music selected by the user.?</param>
 /// <param name="maxFrequencyRatio">[in]  Highest allowable frequency ratio that can be set on this voice. The value for this argument must be between XAUDIO2_MIN_FREQ_RATIO and XAUDIO2_MAX_FREQ_RATIO. Subsequent calls to <see cref="SharpDX.XAudio2.SourceVoice.SetFrequencyRatio" /> are clamped between XAUDIO2_MIN_FREQ_RATIO and MaxFrequencyRatio. The maximum value for this argument is defined as XAUDIO2_MAX_FREQ_RATIO, which allows pitch to be raised by up to 10 octaves. If MaxFrequencyRatio is less than 1.0, the voice will use that ratio immediately after being created (rather than the default of 1.0). Xbox 360  For XMA voices there is an additional restriction on the MaxFrequencyRatio argument and the voice's sample rate. The product of these two numbers cannot exceed XAUDIO2_MAX_RATIO_TIMES_RATE_XMA_MONO for one-channel voices or XAUDIO2_MAX_RATIO_TIMES_RATE_XMA_MULTICHANNEL for voices with any other number of channels. If the value specified for MaxFrequencyRatio is too high for the specified format, the call to CreateSourceVoice fails and produces a debug message.  Note XAudio2's memory usage can be reduced by using the lowest possible MaxFrequencyRatio value.</param>
 /// <param name="enableCallbackEvents">if set to <c>true</c> [enable callback events].</param>
 /// <returns>No enableCallbackEvents.</returns>
 ///   <unmanaged>HRESULT IXAudio2::CreateSourceVoice([Out] IXAudio2SourceVoice** ppSourceVoice,[In] const WAVEFORMATEX* pSourceFormat,[None] UINT32 Flags,[None] float MaxFrequencyRatio,[In, Optional] IXAudio2VoiceCallback* pCallback,[In, Optional] const XAUDIO2_VOICE_SENDS* pSendList,[In, Optional] const XAUDIO2_EFFECT_CHAIN* pEffectChain)</unmanaged>
 public SourceVoice(XAudio2 device, SharpDX.Multimedia.WaveFormat sourceFormat, SharpDX.XAudio2.VoiceFlags flags, float maxFrequencyRatio, bool enableCallbackEvents)
     : this(device, sourceFormat, flags, maxFrequencyRatio, enableCallbackEvents, null)
 {
 }
Exemplo n.º 30
0
 /// <summary>
 /// Creates and configures a source voice.
 /// </summary>
 /// <param name="device">an instance of <see cref = "SharpDX.XAudio2.XAudio2" /></param>
 /// <param name="sourceFormat">[in]  Pointer to a <see cref="SharpDX.Multimedia.WaveFormat"/> structure. This structure contains the expected format for all audio buffers submitted to the source voice. XAudio2 supports voice types of PCM, xWMA, ADPCM (Windows only), and XMA (Xbox 360 only). XAudio2 supports the following PCM formats.   8-bit (unsigned) integer PCM   16-bit integer PCM (Optimal format for XAudio2)   20-bit integer PCM (either in 24 or 32 bit containers)   24-bit integer PCM (either in 24 or 32 bit containers)   32-bit integer PCM   32-bit float PCM (Preferred format after 16-bit integer)   The number of channels in a source voice must be less than or equal to XAUDIO2_MAX_AUDIO_CHANNELS. The sample rate of a source voice must be between XAUDIO2_MIN_SAMPLE_RATE and XAUDIO2_MAX_SAMPLE_RATE. Note Data formats such as XMA, {{ADPCM}}, and {{xWMA}} that require more information than provided by <see cref="SharpDX.Multimedia.WaveFormat"/> have a <see cref="SharpDX.Multimedia.WaveFormat"/> structure as the first member in their format structure. When creating a source voice with one of those formats cast the format's structure as a <see cref="SharpDX.Multimedia.WaveFormat"/> structure and use it as the value for pSourceFormat. </param>
 /// <param name="flags">[in]  Flags that specify the behavior of the source voice. A flag can be 0 or a combination of one or more of the following: ValueDescriptionXAUDIO2_VOICE_NOPITCHNo pitch control is available on the voice.?XAUDIO2_VOICE_NOSRCNo sample rate conversion is available on the voice, the voice's  outputs must have the same sample rate.Note The XAUDIO2_VOICE_NOSRC flag causes the voice to behave as though the XAUDIO2_VOICE_NOPITCH flag also is specified. ?XAUDIO2_VOICE_USEFILTERThe filter effect should be available on this voice.?XAUDIO2_VOICE_MUSICThe voice is used to play background music. The system automatically  can replace the voice with music selected by the user.? </param>
 /// <returns>No documentation.</returns>
 /// <unmanaged>HRESULT IXAudio2::CreateSourceVoice([Out] IXAudio2SourceVoice** ppSourceVoice,[In] const WAVEFORMATEX* pSourceFormat,[None] UINT32 Flags,[None] float MaxFrequencyRatio,[In, Optional] IXAudio2VoiceCallback* pCallback,[In, Optional] const XAUDIO2_VOICE_SENDS* pSendList,[In, Optional] const XAUDIO2_EFFECT_CHAIN* pEffectChain)</unmanaged>
 public SourceVoice(XAudio2 device, SharpDX.Multimedia.WaveFormat sourceFormat, SharpDX.XAudio2.VoiceFlags flags)
     : this(device, sourceFormat, flags, true)
 {
 }
Exemplo n.º 31
0
		public unsafe XAudio2Renderer()
		{
			waveFormat = new WaveFormat();
			xAudio = new XAudio2(XAudio2Flags.None, ProcessorSpecifier.AnyProcessor);
			masteringVoice = new MasteringVoice(xAudio, 2, 44100);
		}
Exemplo n.º 32
0
 /// <summary>
 /// Creates and configures a source voice.
 /// </summary>
 /// <param name="device">an instance of <see cref = "SharpDX.XAudio2.XAudio2" /></param>
 /// <param name="sourceFormat">[in]  Pointer to a <see cref="SharpDX.Multimedia.WaveFormat"/> structure. This structure contains the expected format for all audio buffers submitted to the source voice. XAudio2 supports voice types of PCM, xWMA, ADPCM (Windows only), and XMA (Xbox 360 only). XAudio2 supports the following PCM formats.   8-bit (unsigned) integer PCM   16-bit integer PCM (Optimal format for XAudio2)   20-bit integer PCM (either in 24 or 32 bit containers)   24-bit integer PCM (either in 24 or 32 bit containers)   32-bit integer PCM   32-bit float PCM (Preferred format after 16-bit integer)   The number of channels in a source voice must be less than or equal to XAUDIO2_MAX_AUDIO_CHANNELS. The sample rate of a source voice must be between XAUDIO2_MIN_SAMPLE_RATE and XAUDIO2_MAX_SAMPLE_RATE. Note Data formats such as XMA, {{ADPCM}}, and {{xWMA}} that require more information than provided by <see cref="SharpDX.Multimedia.WaveFormat"/> have a <see cref="SharpDX.Multimedia.WaveFormat"/> structure as the first member in their format structure. When creating a source voice with one of those formats cast the format's structure as a <see cref="SharpDX.Multimedia.WaveFormat"/> structure and use it as the value for pSourceFormat. </param>
 /// <param name="flags">[in]  Flags that specify the behavior of the source voice. A flag can be 0 or a combination of one or more of the following: ValueDescriptionXAUDIO2_VOICE_NOPITCHNo pitch control is available on the voice.?XAUDIO2_VOICE_NOSRCNo sample rate conversion is available on the voice, the voice's  outputs must have the same sample rate.Note The XAUDIO2_VOICE_NOSRC flag causes the voice to behave as though the XAUDIO2_VOICE_NOPITCH flag also is specified. ?XAUDIO2_VOICE_USEFILTERThe filter effect should be available on this voice.?XAUDIO2_VOICE_MUSICThe voice is used to play background music. The system automatically  can replace the voice with music selected by the user.? </param>
 /// <param name="maxFrequencyRatio">[in]  Highest allowable frequency ratio that can be set on this voice. The value for this argument must be between XAUDIO2_MIN_FREQ_RATIO and XAUDIO2_MAX_FREQ_RATIO. Subsequent calls to <see cref="SharpDX.XAudio2.SourceVoice.SetFrequencyRatio"/> are clamped between XAUDIO2_MIN_FREQ_RATIO and MaxFrequencyRatio. The maximum value for this argument is defined as XAUDIO2_MAX_FREQ_RATIO, which allows pitch to be raised by up to 10 octaves. If MaxFrequencyRatio is less than 1.0, the voice will use that ratio immediately after being created (rather than the default of 1.0). Xbox 360  For XMA voices there is an additional restriction on the MaxFrequencyRatio argument and the voice's sample rate. The product of these two numbers cannot exceed XAUDIO2_MAX_RATIO_TIMES_RATE_XMA_MONO for one-channel voices or XAUDIO2_MAX_RATIO_TIMES_RATE_XMA_MULTICHANNEL for voices with any other number of channels. If the value specified for MaxFrequencyRatio is too high for the specified format, the call to CreateSourceVoice fails and produces a debug message.  Note XAudio2's memory usage can be reduced by using the lowest possible MaxFrequencyRatio value. </param>
 /// <returns>No documentation.</returns>
 /// <unmanaged>HRESULT IXAudio2::CreateSourceVoice([Out] IXAudio2SourceVoice** ppSourceVoice,[In] const WAVEFORMATEX* pSourceFormat,[None] UINT32 Flags,[None] float MaxFrequencyRatio,[In, Optional] IXAudio2VoiceCallback* pCallback,[In, Optional] const XAUDIO2_VOICE_SENDS* pSendList,[In, Optional] const XAUDIO2_EFFECT_CHAIN* pEffectChain)</unmanaged>
 public SourceVoice(XAudio2 device, SharpDX.Multimedia.WaveFormat sourceFormat, SharpDX.XAudio2.VoiceFlags flags, float maxFrequencyRatio)
     : this(device, sourceFormat, flags, maxFrequencyRatio, true)
 {
 }
Exemplo n.º 33
0
 public static unsafe WaveFormat MarshalFrom(byte[] rawdata)
 {
     fixed(byte *numPtr = rawdata)
     return(WaveFormat.MarshalFrom((IntPtr)((void *)numPtr)));
 }
Exemplo n.º 34
0
        private void CreateBuffers(WaveFormat format, DataStream dataStream, int loopStart, int loopLength)
        {
            _format = format;
            _dataStream = dataStream;

            // Convert the loop points from bytes to samples.
            var bytesPerSample = 2 * _format.Channels;
            loopStart /= bytesPerSample;
            loopLength /= bytesPerSample;

            _buffer = new AudioBuffer
            {
                Stream = _dataStream,
                AudioBytes = (int)_dataStream.Length,
                Flags = BufferFlags.EndOfStream,
                PlayBegin = loopStart,
                PlayLength = loopLength,
                Context = new IntPtr(42),
            };

            _loopedBuffer = new AudioBuffer
            {
                Stream = _dataStream,
                AudioBytes = (int)_dataStream.Length,
                Flags = BufferFlags.EndOfStream,
                LoopBegin = loopStart,
                LoopLength = loopLength,
                LoopCount = AudioBuffer.LoopInfinite,
                Context = new IntPtr(42),
            };
        }
Exemplo n.º 35
0
 /// <summary>
 /// Creates and configures a source voice with callback through delegates.
 /// </summary>
 /// <param name="device">an instance of <see cref="SharpDX.XAudio2.XAudio2" /></param>
 /// <param name="sourceFormat">[in]  Pointer to a <see cref="SharpDX.Multimedia.WaveFormat" /> structure. This structure contains the expected format for all audio buffers submitted to the source voice. XAudio2 supports voice types of PCM, xWMA, ADPCM (Windows only), and XMA (Xbox 360 only). XAudio2 supports the following PCM formats.   8-bit (unsigned) integer PCM   16-bit integer PCM (Optimal format for XAudio2)   20-bit integer PCM (either in 24 or 32 bit containers)   24-bit integer PCM (either in 24 or 32 bit containers)   32-bit integer PCM   32-bit float PCM (Preferred format after 16-bit integer)   The number of channels in a source voice must be less than or equal to XAUDIO2_MAX_AUDIO_CHANNELS. The sample rate of a source voice must be between XAUDIO2_MIN_SAMPLE_RATE and XAUDIO2_MAX_SAMPLE_RATE. Note Data formats such as XMA, {{ADPCM}}, and {{xWMA}} that require more information than provided by <see cref="SharpDX.Multimedia.WaveFormat" /> have a <see cref="SharpDX.Multimedia.WaveFormat" /> structure as the first member in their format structure. When creating a source voice with one of those formats cast the format's structure as a <see cref="SharpDX.Multimedia.WaveFormat" /> structure and use it as the value for pSourceFormat.</param>
 /// <param name="flags">[in]  Flags that specify the behavior of the source voice. A flag can be 0 or a combination of one or more of the following: ValueDescriptionXAUDIO2_VOICE_NOPITCHNo pitch control is available on the voice.?XAUDIO2_VOICE_NOSRCNo sample rate conversion is available on the voice, the voice's  outputs must have the same sample rate.Note The XAUDIO2_VOICE_NOSRC flag causes the voice to behave as though the XAUDIO2_VOICE_NOPITCH flag also is specified. ?XAUDIO2_VOICE_USEFILTERThe filter effect should be available on this voice.?XAUDIO2_VOICE_MUSICThe voice is used to play background music. The system automatically  can replace the voice with music selected by the user.?</param>
 /// <param name="maxFrequencyRatio">[in]  Highest allowable frequency ratio that can be set on this voice. The value for this argument must be between XAUDIO2_MIN_FREQ_RATIO and XAUDIO2_MAX_FREQ_RATIO. Subsequent calls to <see cref="SharpDX.XAudio2.SourceVoice.SetFrequencyRatio" /> are clamped between XAUDIO2_MIN_FREQ_RATIO and MaxFrequencyRatio. The maximum value for this argument is defined as XAUDIO2_MAX_FREQ_RATIO, which allows pitch to be raised by up to 10 octaves. If MaxFrequencyRatio is less than 1.0, the voice will use that ratio immediately after being created (rather than the default of 1.0). Xbox 360  For XMA voices there is an additional restriction on the MaxFrequencyRatio argument and the voice's sample rate. The product of these two numbers cannot exceed XAUDIO2_MAX_RATIO_TIMES_RATE_XMA_MONO for one-channel voices or XAUDIO2_MAX_RATIO_TIMES_RATE_XMA_MULTICHANNEL for voices with any other number of channels. If the value specified for MaxFrequencyRatio is too high for the specified format, the call to CreateSourceVoice fails and produces a debug message.  Note XAudio2's memory usage can be reduced by using the lowest possible MaxFrequencyRatio value.</param>
 /// <param name="enableCallbackEvents">if set to <c>true</c> [enable callback events].</param>
 /// <param name="effectDescriptors">[in, optional] Pointer to a list of XAUDIO2_EFFECT_CHAIN structures that describe an effect chain to use in the source voice.</param>
 /// <returns>No enableCallbackEvents.</returns>
 ///   <unmanaged>HRESULT IXAudio2::CreateSourceVoice([Out] IXAudio2SourceVoice** ppSourceVoice,[In] const WAVEFORMATEX* pSourceFormat,[None] UINT32 Flags,[None] float MaxFrequencyRatio,[In, Optional] IXAudio2VoiceCallback* pCallback,[In, Optional] const XAUDIO2_VOICE_SENDS* pSendList,[In, Optional] const XAUDIO2_EFFECT_CHAIN* pEffectChain)</unmanaged>
 public SourceVoice(XAudio2 device, SharpDX.Multimedia.WaveFormat sourceFormat, SharpDX.XAudio2.VoiceFlags flags, float maxFrequencyRatio, bool enableCallbackEvents, EffectDescriptor[] effectDescriptors)
     : base(device)
 {
     CreateSourceVoice(device, sourceFormat, flags, maxFrequencyRatio, enableCallbackEvents ? VoiceShadow.ToIntPtr(voiceCallbackImpl = new VoiceCallbackImpl(this)) : IntPtr.Zero, effectDescriptors);
 }
Exemplo n.º 36
0
        private void Initialize(SourceReader reader)
        {
            // Invalidate selection for all streams
            reader.SetStreamSelection(SourceReaderIndex.AllStreams, false);

            // Select only audio stream
            reader.SetStreamSelection(SourceReaderIndex.FirstAudioStream, true);

            // Get the media type for the current stream.
            using (var mediaType = reader.GetNativeMediaType(SourceReaderIndex.FirstAudioStream, 0))
            {
                var majorType = mediaType.Get(MediaTypeAttributeKeys.MajorType);
                if (majorType != MediaTypeGuids.Audio)
                    throw new InvalidOperationException("Input stream doesn't contain an audio stream.");
            }

            // Set the type on the source reader to use PCM
            using (var partialType = new MediaType())
            {
                partialType.Set(MediaTypeAttributeKeys.MajorType, MediaTypeGuids.Audio);
                partialType.Set(MediaTypeAttributeKeys.Subtype, AudioFormatGuids.Pcm);
                reader.SetCurrentMediaType(SourceReaderIndex.FirstAudioStream, partialType);
            }

            // Retrieve back the real media type
            using (var realMediaType = reader.GetCurrentMediaType(SourceReaderIndex.FirstAudioStream))
            {
                int sizeRef;
                WaveFormat = realMediaType.ExtracttWaveFormat(out sizeRef);
            }

            Duration = new TimeSpan(reader.GetPresentationAttribute(SourceReaderIndex.MediaSource, PresentationDescriptionAttributeKeys.Duration));
        }
Exemplo n.º 37
0
 public static WaveFormat CreateMuLawFormat(int sampleRate, int channels)
 {
     return(WaveFormat.CreateCustomFormat(WaveFormatEncoding.Mulaw, sampleRate, channels, sampleRate * channels, 1, 8));
 }
Exemplo n.º 38
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new UIForm());

            UIHandler.Init();
            GraphicsManager.Init();
            ThemeManager.LoadDefault();
            InteropManager.Init();

            /*UIForm f1 = new UIForm(1);
            UIForm f2 = new UIForm(2);

            Button b = new Button();
            b.SetBounds(48, 48, 48, 48);
            b.Click += (Object s, EventArgs e) => {
                new UIForm(32).Show();
            };
            f1.Controls.Add(b);

            f2.Show();*/
            new WindowMain().Open();

            UIManager.SpawnUIUpdateThread();
            //Application.Run(f1);
            Application.Run();

            bool yes = true;
            if (yes) return;

            //
            XAudio2 audio = new XAudio2();
            WaveFormat format = new WaveFormat(44100, 32, 2);
            MasteringVoice mvoice = new MasteringVoice(audio);
            SourceVoice voice = new SourceVoice(audio, format);

            int bufferSize = format.ConvertLatencyToByteSize(500);

            DataStream stream = new DataStream(bufferSize, true, true);

            int samples = bufferSize / format.BlockAlign;
            for (int i = 0; i < samples; i++) {
                float val = (float)(Math.Sin(2*Math.PI*500*i/format.SampleRate));// * (0.5 + Math.Sin(2*Math.PI*2.2*i/format.SampleRate)*0.5));
                //if (val == 0) val = 1;
                //val = val / Math.Abs(val);
                for (int j = 0; j < 3; j++) val = val * val;
                stream.Write(val);
                stream.Write(val);
                //stream.Write(val * (float)(0.5 + Math.Sin(2 * Math.PI * 2.2 * i / format.SampleRate) * 0.5));
                //stream.Write(val * (float)(0.5 + Math.Cos(2 * Math.PI * 2.2 * i / format.SampleRate) * 0.5));
            }

            stream.Position = 0;

            AudioBuffer buffer = new AudioBuffer { Stream = stream, Flags = BufferFlags.EndOfStream, AudioBytes = bufferSize };
            //buffer.LoopCount = AudioBuffer.LoopInfinite;
            voice.SubmitSourceBuffer(buffer, null);
            voice.SubmitSourceBuffer(buffer, null);
            voice.SubmitSourceBuffer(buffer, null);
            voice.SubmitSourceBuffer(buffer, null);
            voice.SubmitSourceBuffer(buffer, null);
            voice.SubmitSourceBuffer(buffer, null);
            voice.SubmitSourceBuffer(buffer, null);
            voice.SubmitSourceBuffer(buffer, null);
            voice.SubmitSourceBuffer(buffer, null);
            voice.SubmitSourceBuffer(buffer, null);
            voice.SubmitSourceBuffer(buffer, null);
            voice.SubmitSourceBuffer(buffer, null);
            voice.SubmitSourceBuffer(buffer, null);
            voice.SubmitSourceBuffer(buffer, null);

            voice.Start();
            Thread.Sleep(3000);
            long pos = stream.Position;
            stream.Position = 0;
            for (int i = 0; i < samples; i++) {
                float val = (float)(Math.Sin(2 * Math.PI * 500 * i / format.SampleRate));// * (0.5 + Math.Sin(2*Math.PI*2.2*i/format.SampleRate)*0.5));
                //if (val == 0) val = 1;
                //val = val / Math.Abs(val);
                //for (int j = 0; j < 8; j++) val = val * val;
                stream.Write(val);
                stream.Write(val);
                //stream.Write(val * (float)(0.5 + Math.Sin(2 * Math.PI * 2.2 * i / format.SampleRate) * 0.5));
                //stream.Write(val * (float)(0.5 + Math.Cos(2 * Math.PI * 2.2 * i / format.SampleRate) * 0.5));
            }
            //stream.Position = pos;
            //voice.State.p
            while (voice.State.BuffersQueued > 0) Thread.Sleep(100);
            //Thread.Sleep(6000);
        }
Exemplo n.º 39
0
        /// <summary>
        /// Initializes the specified stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        private unsafe void Initialize(Stream stream)
        {
            var parser = new RiffParser(stream);

            FileFormatName = "Unknown";

            // Parse Header
            if (!parser.MoveNext() || parser.Current == null)
            {
                ThrowInvalidFileFormat();
                return;
            }

            // Check that WAVE or XWMA header is present
            FileFormatName = parser.Current.Type;
            if (FileFormatName != "WAVE" && FileFormatName != "XWMA")
            {
                throw new InvalidOperationException("Unsupported " + FileFormatName + " file format. Only WAVE or XWMA");
            }

            // Parse inside the first chunk
            parser.Descend();

            // Get all the chunk
            var chunks = parser.GetAllChunks();

            // Get "fmt" chunk
            var fmtChunk = Chunk(chunks, "fmt ");

            if (fmtChunk.Size < sizeof(WaveFormat.__PcmNative))
            {
                ThrowInvalidFileFormat();
            }

            try
            {
                Format = WaveFormat.MarshalFrom(fmtChunk.GetData());
            }
            catch (InvalidOperationException ex)
            {
                ThrowInvalidFileFormat(ex);
            }

            // If XWMA
            if (FileFormatName == "XWMA")
            {
                // Check that format is Wma
                if (Format.Encoding != WaveFormatEncoding.Wmaudio2 && Format.Encoding != WaveFormatEncoding.Wmaudio3)
                {
                    ThrowInvalidFileFormat();
                }

                // Check for "dpds" chunk
                // Get the dpds decoded packed cumulative bytes
                var dpdsChunk = Chunk(chunks, "dpds");
                DecodedPacketsInfo = dpdsChunk.GetDataAsArray <uint>();
            }
            else
            {
                switch (Format.Encoding)
                {
                case WaveFormatEncoding.Pcm:
                case WaveFormatEncoding.IeeeFloat:
                case WaveFormatEncoding.Extensible:
                case WaveFormatEncoding.Adpcm:
                    break;

                default:
                    ThrowInvalidFileFormat();
                    break;
                }
            }

            // Check for "data" chunk
            var dataChunk = Chunk(chunks, "data");

            startPositionOfData = dataChunk.DataPosition;
            length = dataChunk.Size;

            input.Position = startPositionOfData;
        }
Exemplo n.º 40
0
 // Extended constructor which supports custom formats / compression.
 internal SoundEffect(WaveFormat format, byte[] buffer, int offset, int count, int loopStart, int loopLength)
 {
     Initialize(format, buffer, offset, count, loopStart, loopLength);
 }
Exemplo n.º 41
0
 /// <summary>
 /// Creates and configures a source voice.
 /// </summary>
 /// <param name="device">an instance of <see cref = "SharpDX.XAudio2.XAudio2" /></param>
 /// <param name="sourceFormat">[in]  Pointer to a <see cref="SharpDX.Multimedia.WaveFormat"/> structure. This structure contains the expected format for all audio buffers submitted to the source voice. XAudio2 supports voice types of PCM, xWMA, ADPCM (Windows only), and XMA (Xbox 360 only). XAudio2 supports the following PCM formats.   8-bit (unsigned) integer PCM   16-bit integer PCM (Optimal format for XAudio2)   20-bit integer PCM (either in 24 or 32 bit containers)   24-bit integer PCM (either in 24 or 32 bit containers)   32-bit integer PCM   32-bit float PCM (Preferred format after 16-bit integer)   The number of channels in a source voice must be less than or equal to XAUDIO2_MAX_AUDIO_CHANNELS. The sample rate of a source voice must be between XAUDIO2_MIN_SAMPLE_RATE and XAUDIO2_MAX_SAMPLE_RATE. Note Data formats such as XMA, {{ADPCM}}, and {{xWMA}} that require more information than provided by <see cref="SharpDX.Multimedia.WaveFormat"/> have a <see cref="SharpDX.Multimedia.WaveFormat"/> structure as the first member in their format structure. When creating a source voice with one of those formats cast the format's structure as a <see cref="SharpDX.Multimedia.WaveFormat"/> structure and use it as the value for pSourceFormat. </param>
 /// <returns>No documentation.</returns>
 /// <unmanaged>HRESULT IXAudio2::CreateSourceVoice([Out] IXAudio2SourceVoice** ppSourceVoice,[In] const WAVEFORMATEX* pSourceFormat,[None] UINT32 Flags,[None] float MaxFrequencyRatio,[In, Optional] IXAudio2VoiceCallback* pCallback,[In, Optional] const XAUDIO2_VOICE_SENDS* pSendList,[In, Optional] const XAUDIO2_EFFECT_CHAIN* pEffectChain)</unmanaged>
 public SourceVoice(XAudio2 device, SharpDX.Multimedia.WaveFormat sourceFormat)
     : this(device, sourceFormat, true)
 {
 }
Exemplo n.º 42
0
        private void Initialize(WaveFormat format, byte[] buffer, int offset, int count, int loopStart, int loopLength)
        {
            _format = format;

            _dataStream = DataStream.Create<byte>(buffer, true, false);

            // Use the loopStart and loopLength also as the range
            // when playing this SoundEffect a single time / unlooped.
            _buffer = new AudioBuffer()
            {
                Stream = _dataStream,
                AudioBytes = count,
                Flags = BufferFlags.EndOfStream,
                PlayBegin = loopStart,
                PlayLength = loopLength,
                Context = new IntPtr(42),
            };

            _loopedBuffer = new AudioBuffer()
            {
                Stream = _dataStream,
                AudioBytes = count,
                Flags = BufferFlags.EndOfStream,
                LoopBegin = loopStart,
                LoopLength = loopLength,
                LoopCount = AudioBuffer.LoopInfinite,
                Context = new IntPtr(42),
            };            
        }
Exemplo n.º 43
0
 /// <summary>
 /// Creates and configures a source voice.
 /// </summary>
 /// <param name="device">an instance of <see cref = "SharpDX.XAudio2.XAudio2" /></param>
 /// <param name="sourceFormat">[in]  Pointer to a <see cref="SharpDX.Multimedia.WaveFormat"/> structure. This structure contains the expected format for all audio buffers submitted to the source voice. XAudio2 supports voice types of PCM, xWMA, ADPCM (Windows only), and XMA (Xbox 360 only). XAudio2 supports the following PCM formats.   8-bit (unsigned) integer PCM   16-bit integer PCM (Optimal format for XAudio2)   20-bit integer PCM (either in 24 or 32 bit containers)   24-bit integer PCM (either in 24 or 32 bit containers)   32-bit integer PCM   32-bit float PCM (Preferred format after 16-bit integer)   The number of channels in a source voice must be less than or equal to XAUDIO2_MAX_AUDIO_CHANNELS. The sample rate of a source voice must be between XAUDIO2_MIN_SAMPLE_RATE and XAUDIO2_MAX_SAMPLE_RATE. Note Data formats such as XMA, {{ADPCM}}, and {{xWMA}} that require more information than provided by <see cref="SharpDX.Multimedia.WaveFormat"/> have a <see cref="SharpDX.Multimedia.WaveFormat"/> structure as the first member in their format structure. When creating a source voice with one of those formats cast the format's structure as a <see cref="SharpDX.Multimedia.WaveFormat"/> structure and use it as the value for pSourceFormat. </param>
 /// <param name="flags">[in]  Flags that specify the behavior of the source voice. A flag can be 0 or a combination of one or more of the following: ValueDescriptionXAUDIO2_VOICE_NOPITCHNo pitch control is available on the voice.?XAUDIO2_VOICE_NOSRCNo sample rate conversion is available on the voice, the voice's  outputs must have the same sample rate.Note The XAUDIO2_VOICE_NOSRC flag causes the voice to behave as though the XAUDIO2_VOICE_NOPITCH flag also is specified. ?XAUDIO2_VOICE_USEFILTERThe filter effect should be available on this voice.?XAUDIO2_VOICE_MUSICThe voice is used to play background music. The system automatically  can replace the voice with music selected by the user.? </param>
 /// <param name="enableCallbackEvents">True to enable delegate callbacks on this instance. Default is false</param>
 /// <returns>No documentation.</returns>
 /// <unmanaged>HRESULT IXAudio2::CreateSourceVoice([Out] IXAudio2SourceVoice** ppSourceVoice,[In] const WAVEFORMATEX* pSourceFormat,[None] UINT32 Flags,[None] float MaxFrequencyRatio,[In, Optional] IXAudio2VoiceCallback* pCallback,[In, Optional] const XAUDIO2_VOICE_SENDS* pSendList,[In, Optional] const XAUDIO2_EFFECT_CHAIN* pEffectChain)</unmanaged>
 public SourceVoice(XAudio2 device, SharpDX.Multimedia.WaveFormat sourceFormat, SharpDX.XAudio2.VoiceFlags flags, bool enableCallbackEvents)
     : this(device, sourceFormat, flags, 1.0f, enableCallbackEvents)
 {
 }
Exemplo n.º 44
0
 /// <summary>
 /// Creates and configures a source voice.
 /// </summary>
 /// <param name="device">an instance of <see cref = "SharpDX.XAudio2.XAudio2" /></param>
 /// <param name="sourceFormat">[in]  Pointer to a <see cref="SharpDX.Multimedia.WaveFormat"/> structure. This structure contains the expected format for all audio buffers submitted to the source voice. XAudio2 supports voice types of PCM, xWMA, ADPCM (Windows only), and XMA (Xbox 360 only). XAudio2 supports the following PCM formats.   8-bit (unsigned) integer PCM   16-bit integer PCM (Optimal format for XAudio2)   20-bit integer PCM (either in 24 or 32 bit containers)   24-bit integer PCM (either in 24 or 32 bit containers)   32-bit integer PCM   32-bit float PCM (Preferred format after 16-bit integer)   The number of channels in a source voice must be less than or equal to XAUDIO2_MAX_AUDIO_CHANNELS. The sample rate of a source voice must be between XAUDIO2_MIN_SAMPLE_RATE and XAUDIO2_MAX_SAMPLE_RATE. Note Data formats such as XMA, {{ADPCM}}, and {{xWMA}} that require more information than provided by <see cref="SharpDX.Multimedia.WaveFormat"/> have a <see cref="SharpDX.Multimedia.WaveFormat"/> structure as the first member in their format structure. When creating a source voice with one of those formats cast the format's structure as a <see cref="SharpDX.Multimedia.WaveFormat"/> structure and use it as the value for pSourceFormat. </param>
 /// <param name="flags">[in]  Flags that specify the behavior of the source voice. A flag can be 0 or a combination of one or more of the following: ValueDescriptionXAUDIO2_VOICE_NOPITCHNo pitch control is available on the voice.?XAUDIO2_VOICE_NOSRCNo sample rate conversion is available on the voice, the voice's  outputs must have the same sample rate.Note The XAUDIO2_VOICE_NOSRC flag causes the voice to behave as though the XAUDIO2_VOICE_NOPITCH flag also is specified. ?XAUDIO2_VOICE_USEFILTERThe filter effect should be available on this voice.?XAUDIO2_VOICE_MUSICThe voice is used to play background music. The system automatically  can replace the voice with music selected by the user.? </param>
 /// <param name="maxFrequencyRatio">[in]  Highest allowable frequency ratio that can be set on this voice. The value for this argument must be between XAUDIO2_MIN_FREQ_RATIO and XAUDIO2_MAX_FREQ_RATIO. Subsequent calls to <see cref="SharpDX.XAudio2.SourceVoice.SetFrequencyRatio"/> are clamped between XAUDIO2_MIN_FREQ_RATIO and MaxFrequencyRatio. The maximum value for this argument is defined as XAUDIO2_MAX_FREQ_RATIO, which allows pitch to be raised by up to 10 octaves. If MaxFrequencyRatio is less than 1.0, the voice will use that ratio immediately after being created (rather than the default of 1.0). Xbox 360  For XMA voices there is an additional restriction on the MaxFrequencyRatio argument and the voice's sample rate. The product of these two numbers cannot exceed XAUDIO2_MAX_RATIO_TIMES_RATE_XMA_MONO for one-channel voices or XAUDIO2_MAX_RATIO_TIMES_RATE_XMA_MULTICHANNEL for voices with any other number of channels. If the value specified for MaxFrequencyRatio is too high for the specified format, the call to CreateSourceVoice fails and produces a debug message.  Note XAudio2's memory usage can be reduced by using the lowest possible MaxFrequencyRatio value. </param>
 /// <param name="callback">[in, optional]  Pointer to a client-provided callback interface, <see cref="SharpDX.XAudio2.VoiceCallback"/>. </param>
 /// <returns>No documentation.</returns>
 /// <unmanaged>HRESULT IXAudio2::CreateSourceVoice([Out] IXAudio2SourceVoice** ppSourceVoice,[In] const WAVEFORMATEX* pSourceFormat,[None] UINT32 Flags,[None] float MaxFrequencyRatio,[In, Optional] IXAudio2VoiceCallback* pCallback,[In, Optional] const XAUDIO2_VOICE_SENDS* pSendList,[In, Optional] const XAUDIO2_EFFECT_CHAIN* pEffectChain)</unmanaged>
 public SourceVoice(XAudio2 device, SharpDX.Multimedia.WaveFormat sourceFormat, SharpDX.XAudio2.VoiceFlags flags, float maxFrequencyRatio, VoiceCallback callback)
     : this(device, sourceFormat, flags, maxFrequencyRatio, callback, null)
 {
 }
Exemplo n.º 45
0
 /// <summary>
 /// Creates and configures a source voice.
 /// </summary>
 /// <param name="device">an instance of <see cref = "SharpDX.XAudio2.XAudio2" /></param>
 /// <param name="sourceFormat">[in]  Pointer to a <see cref="SharpDX.Multimedia.WaveFormat"/> structure. This structure contains the expected format for all audio buffers submitted to the source voice. XAudio2 supports voice types of PCM, xWMA, ADPCM (Windows only), and XMA (Xbox 360 only). XAudio2 supports the following PCM formats.   8-bit (unsigned) integer PCM   16-bit integer PCM (Optimal format for XAudio2)   20-bit integer PCM (either in 24 or 32 bit containers)   24-bit integer PCM (either in 24 or 32 bit containers)   32-bit integer PCM   32-bit float PCM (Preferred format after 16-bit integer)   The number of channels in a source voice must be less than or equal to XAUDIO2_MAX_AUDIO_CHANNELS. The sample rate of a source voice must be between XAUDIO2_MIN_SAMPLE_RATE and XAUDIO2_MAX_SAMPLE_RATE. Note Data formats such as XMA, {{ADPCM}}, and {{xWMA}} that require more information than provided by <see cref="SharpDX.Multimedia.WaveFormat"/> have a <see cref="SharpDX.Multimedia.WaveFormat"/> structure as the first member in their format structure. When creating a source voice with one of those formats cast the format's structure as a <see cref="SharpDX.Multimedia.WaveFormat"/> structure and use it as the value for pSourceFormat. </param>
 /// <param name="flags">[in]  Flags that specify the behavior of the source voice. A flag can be 0 or a combination of one or more of the following: ValueDescriptionXAUDIO2_VOICE_NOPITCHNo pitch control is available on the voice.?XAUDIO2_VOICE_NOSRCNo sample rate conversion is available on the voice, the voice's  outputs must have the same sample rate.Note The XAUDIO2_VOICE_NOSRC flag causes the voice to behave as though the XAUDIO2_VOICE_NOPITCH flag also is specified. ?XAUDIO2_VOICE_USEFILTERThe filter effect should be available on this voice.?XAUDIO2_VOICE_MUSICThe voice is used to play background music. The system automatically  can replace the voice with music selected by the user.? </param>
 /// <param name="maxFrequencyRatio">[in]  Highest allowable frequency ratio that can be set on this voice. The value for this argument must be between XAUDIO2_MIN_FREQ_RATIO and XAUDIO2_MAX_FREQ_RATIO. Subsequent calls to <see cref="SharpDX.XAudio2.SourceVoice.SetFrequencyRatio"/> are clamped between XAUDIO2_MIN_FREQ_RATIO and MaxFrequencyRatio. The maximum value for this argument is defined as XAUDIO2_MAX_FREQ_RATIO, which allows pitch to be raised by up to 10 octaves. If MaxFrequencyRatio is less than 1.0, the voice will use that ratio immediately after being created (rather than the default of 1.0). Xbox 360  For XMA voices there is an additional restriction on the MaxFrequencyRatio argument and the voice's sample rate. The product of these two numbers cannot exceed XAUDIO2_MAX_RATIO_TIMES_RATE_XMA_MONO for one-channel voices or XAUDIO2_MAX_RATIO_TIMES_RATE_XMA_MULTICHANNEL for voices with any other number of channels. If the value specified for MaxFrequencyRatio is too high for the specified format, the call to CreateSourceVoice fails and produces a debug message.  Note XAudio2's memory usage can be reduced by using the lowest possible MaxFrequencyRatio value. </param>
 /// <param name="callback">[in, optional]  Pointer to a client-provided callback interface, <see cref="SharpDX.XAudio2.VoiceCallback"/>. </param>
 /// <param name="effectDescriptors">[in, optional] Pointer to a list of XAUDIO2_EFFECT_CHAIN structures that describe an effect chain to use in the source voice.</param>
 /// <returns>No documentation.</returns>
 /// <unmanaged>HRESULT IXAudio2::CreateSourceVoice([Out] IXAudio2SourceVoice** ppSourceVoice,[In] const WAVEFORMATEX* pSourceFormat,[None] UINT32 Flags,[None] float MaxFrequencyRatio,[In, Optional] IXAudio2VoiceCallback* pCallback,[In, Optional] const XAUDIO2_VOICE_SENDS* pSendList,[In, Optional] const XAUDIO2_EFFECT_CHAIN* pEffectChain)</unmanaged>
 public SourceVoice(XAudio2 device, SharpDX.Multimedia.WaveFormat sourceFormat, SharpDX.XAudio2.VoiceFlags flags, float maxFrequencyRatio, VoiceCallback callback, EffectDescriptor[] effectDescriptors)
     : base(device)
 {
     CreateSourceVoice(device, sourceFormat, flags, maxFrequencyRatio, callback == null ? IntPtr.Zero : VoiceShadow.ToIntPtr(callback), effectDescriptors);
 }
Exemplo n.º 46
0
        IMySourceVoice IMyAudio.GetSound(IMy3DSoundEmitter source, int sampleRate, int channels, MySoundDimensions dimension)
        {
            if (!m_canPlay)
                return null;

            var waveFormat = new WaveFormat(sampleRate, channels);
            source.SourceChannels = channels;
            var sourceVoice = new MySourceVoice(m_audioEngine, waveFormat);

            float volume = source.CustomVolume.HasValue ? source.CustomVolume.Value : 1;
            float maxDistance = source.CustomMaxDistance.HasValue ? source.CustomMaxDistance.Value : 0;

            sourceVoice.SetVolume(volume);

            if (dimension == MySoundDimensions.D3)
            {
                m_helperEmitter.UpdateValuesOmni(source.SourcePosition, source.Velocity, maxDistance, m_deviceDetails.OutputFormat.Channels, MyCurveType.Linear);
                sourceVoice.distanceToListener = m_x3dAudio.Apply3D(sourceVoice.Voice, m_listener, m_helperEmitter, source.SourceChannels, m_deviceDetails.OutputFormat.Channels, m_calculateFlags, maxDistance, sourceVoice.FrequencyRatio, sourceVoice.Silent, source.Realistic);
                Update3DCuesState();
                Add3DCueToUpdateList(source);

                ++m_soundInstancesTotal3D;
            }

            return sourceVoice;
        }
Exemplo n.º 47
0
		private static float CalculateLengthInSeconds(WaveFormat format, int dataLength)
		{
			return (float)dataLength / format.BlockAlign / format.SampleRate;
		}
Exemplo n.º 48
-1
        /// <summary>
        /// Initialize the media element for playback
        /// </summary>
        /// <param name="streamConfig">Object containing stream configuration details</param>
        void InitializeMediaPlayer(MoonlightStreamConfiguration streamConfig, AvStreamSource streamSource)
        {
            this._streamSource = streamSource;

            // This code is based upon the MS FFmpegInterop project on GitHub
            VideoEncodingProperties videoProps = VideoEncodingProperties.CreateH264();
            videoProps.ProfileId = H264ProfileIds.High;
            videoProps.Width = (uint)streamConfig.GetWidth();
            videoProps.Height = (uint)streamConfig.GetHeight();
            videoProps.Bitrate = (uint)streamConfig.GetBitrate();

            _videoMss = new MediaStreamSource(new VideoStreamDescriptor(videoProps));
            _videoMss.BufferTime = TimeSpan.Zero;
            _videoMss.CanSeek = false;
            _videoMss.Duration = TimeSpan.Zero;
            _videoMss.SampleRequested += _videoMss_SampleRequested;

            XAudio2 xaudio = new XAudio2();
            MasteringVoice masteringVoice = new MasteringVoice(xaudio, 2, 48000);
            WaveFormat format = new WaveFormat(48000, 16, 2);

            // Set for low latency playback
            StreamDisplay.RealTimePlayback = true;

            // Render on the full window to avoid extra compositing
            StreamDisplay.IsFullWindow = true;

            // Disable built-in transport controls
            StreamDisplay.AreTransportControlsEnabled = false;

            StreamDisplay.SetMediaStreamSource(_videoMss);
            AvStream.SetSourceVoice(new SourceVoice(xaudio, format));
        }