public void Play()
    {
        lock (this)
        {
            if (_loopForever == true)
            {
                if (_isPlaying)
                {
                    if (_isFading)
                    {
                        _isFading = false;
                        _singleSourceVoice.SetVolume(_initialVolumne);
                    }
                    return;
                }
                _singleSourceVoice = new SourceVoice(_xaudio, _waveFormat, true);
                _singleSourceVoice.SubmitSourceBuffer(_buffer, _soundstream.DecodedPacketsInfo);
                _singleSourceVoice.SetVolume(_initialVolumne);
                _singleSourceVoice.Start();
                _isPlaying = true;
                return;
            }
        }
        var sourceVoice = new SourceVoice(_xaudio, _waveFormat, true);

        sourceVoice.SubmitSourceBuffer(_buffer, _soundstream.DecodedPacketsInfo);
        sourceVoice.SetVolume(_initialVolumne);
        sourceVoice.Start();
    }
Exemplo n.º 2
0
 public void SetVolume(float v)
 {
     vset = MathHelper.Clamp(v, 0f, 1f);
     if (s != null && setv == false)
     {
         setv = true;
         Task.Run(() =>
         {
             while (Math.Abs(vset - s.Volume) > 0.0000001f)
             {
                 if (vset < s.Volume)
                 {
                     s.SetVolume(s.Volume - 0.000025f);
                 }
                 else
                 {
                     s.SetVolume(s.Volume + 0.000025f);
                 }
             }
             setv = false;
         });
     }
     else
     {
         vset = v;
     }
 }
Exemplo n.º 3
0
        private void Refresh3DVoiceData()
        {
            //Change output speakers parameter to simulate 3D sound
            DspSettings settings3D = _soundEngine.X3DAudio.Calculate(_soundEngine.Listener, Emitter, CalculateFlags.Matrix, PlayingDataSource.WaveFormat.Channels, _soundEngine.DeviceDetail.OutputFormat.Channels);

            _voice.SetOutputMatrix(PlayingDataSource.WaveFormat.Channels, _soundEngine.DeviceDetail.OutputFormat.Channels, settings3D.MatrixCoefficients);

            //Set global input sound volume based on distance VS object
            float soundVolume = _voiceVolume *
                                (1.0f - (Math.Max(0.0f, Math.Min(1.0f, settings3D.EmitterToListenerDistance / _playingDataSource.Power)))) *
                                (_playingDataSource.Category == SourceCategory.Music ? _soundEngine.GlobalMusicVolume : _soundEngine.GlobalFXVolume);

            _voice.SetVolume(soundVolume, XAudio2.CommitNow);
        }
Exemplo n.º 4
0
 protected override void SetPlayingVolume(float value)
 {
     if (source != null)
     {
         source.SetVolume(value);
     }
 }
Exemplo n.º 5
0
        public static Task PlaySound(Stream stream)
        {
            var soundstream = new SoundStream(stream);
            var buffer      = new AudioBufferAndMetaData()
            {
                Stream             = soundstream.ToDataStream(),
                AudioBytes         = (int)soundstream.Length,
                Flags              = BufferFlags.EndOfStream,
                WaveFormat         = soundstream.Format,
                DecodedPacketsInfo = soundstream.DecodedPacketsInfo
            };

            var sourceVoice = new SourceVoice(XAudio, buffer.WaveFormat, true);

            sourceVoice.SetVolume(Volume, SharpDX.XAudio2.XAudio2.CommitNow);
            sourceVoice.SubmitSourceBuffer(buffer, buffer.DecodedPacketsInfo);


            //var effect = new SharpDX.XAPO.Fx.Echo(XAudio);
            //EffectDescriptor effectDescriptor = new EffectDescriptor(effect);
            //sourceVoice.SetEffectChain(effectDescriptor);
            //sourceVoice.EnableEffect(0);

            sourceVoice.Start();

            TaskCompletionSource <object> mediaDone = new TaskCompletionSource <object>();

            sourceVoice.StreamEnd += () => {
                mediaDone.SetResult(null);
            };

            return(mediaDone.Task);
        }
Exemplo n.º 6
0
        public override void Play(AudioBuffer buffer)
        {
            _xa2Buffer            = (XAudio2AudioBuffer)buffer;
            _channelCount         = GetChannelCount(_xa2Buffer.Format);
            _emitter.ChannelCount = _channelCount;
            if ((_channelCount > 1 && !_stereoState) || (_channelCount == 1 && _stereoState))
            {
                float volume = _sourceVoice.Volume;
                _sourceVoice.DestroyVoice();
                _sourceVoice.Dispose();
                WaveFormat waveFormat = new WaveFormat(_xa2Buffer.Frequency, GetChannelCount(_xa2Buffer.Format));
                _sourceVoice = new SourceVoice(_engine.XAudio2, waveFormat, VoiceFlags.None, maxFrequencyRatio: 2.0f);
                _sourceVoice.SetVolume(volume);
                _emitter.ChannelAzimuths = new[] { 0.0f };
                _dspSettings             = new DspSettings(_channelCount, 2);
                UpdateSourcePosition();
                _stereoState = _channelCount == 2;
            }

            if (_sourcePositionDirty)
            {
                UpdateSourcePosition();
                _sourcePositionDirty = false;
            }

            _audioBuffer.Stream     = _xa2Buffer.DataStream;
            _audioBuffer.AudioBytes = _xa2Buffer.SizeInBytes;
            _audioBuffer.Flags      = BufferFlags.EndOfStream;
            _sourceVoice.Stop();
            _sourceVoice.FlushSourceBuffers();
            _sourceVoice.SubmitSourceBuffer(_audioBuffer, null);
            _sourceVoice.Start();
        }
Exemplo n.º 7
0
 private void VolumeTrackBar_Scroll(object sender, EventArgs e)
 {
     if (playerState == PlayerState.Playing)
     {
         sourceVoice.SetVolume((float)VolumeTrackBar.Value / 100);
     }
 }
 private void PlatformSetVolume(float value)
 {
     if (_voice != null && SoundEffect.MasterVoice != null)
     {
         _voice.SetVolume(value, XAudio2.CommitNow);
     }
 }
    public SpeechAnimator(ChannelSystem channelSystem, BoneSystem boneSystem)
    {
        this.channelSystem = channelSystem;
        this.boneSystem    = boneSystem;

        this.synth   = new SpeechSynthesizer();
        synth.Volume = 100;

        synth.SelectVoice(Voice);
        synth.VisemeReached += Synth_VisemeReached;

        visemeChannels = VisemeChannelMap
                         .Select(name => name == null ? null : channelSystem.ChannelsByName[name + "?value"])
                         .ToArray();

        headBone = boneSystem.BonesByName["head"];

        var audioDevice = new XAudio2(XAudio2Flags.DebugEngine, ProcessorSpecifier.AnyProcessor);

        masteringVoice = new MasteringVoice(audioDevice);

        WaveFormat monoWaveFormat = WaveFormat.CreateIeeeFloatWaveFormat(44100, 2);

        sourceVoice = new SourceVoice(audioDevice, monoWaveFormat, VoiceFlags.None);
        sourceVoice.SetVolume(1);
        sourceVoice.Start();

        phononStream = new PhononSourceVoiceStream(sourceVoice);
        synth.SetOutputToAudioStream(phononStream, new SpeechAudioFormatInfo(44100, AudioBitsPerSample.Sixteen, AudioChannel.Mono));
    }
Exemplo n.º 10
0
 public void SetVolume(float volume)
 {
     if (m_voice != null)
     {
         m_voice.SetVolume(volume);
     }
 }
Exemplo n.º 11
0
        private void SetupVoice(AudioFormat format)
        {
            WaveFormat wFmt = new WaveFormat(format.SampleRate, format.BitsPerSample, format.Channels);

            _voice = new SourceVoice(_engine.Device, wFmt);
            _voice.SetVolume(_volume);
        }
Exemplo n.º 12
0
        private void CreateSourceVoices(float playBegin = 0)
        {
            if (playBegin > 0)
            {
                foreach (var voice in voices)
                {
                    voice.audioBuffer.PlayBegin = (int)(voice.soundStream.Format.SampleRate * playBegin) / 128 * 128;
                }
                if (playtimer.IsRunning)
                {
                    playtimer.Restart();
                }
                else
                {
                    playtimer.Reset();
                }
                playBeginMs = (int)(playBegin * 1000);
            }
            else
            {
                playBeginMs = 0;
            }

            trackFinished = false;
            foreach (var voice in voices)
            {
                var sourceVoice = new SourceVoice(xAudio2, voice.soundStream.Format, true);
                sourceVoice.SubmitSourceBuffer(voice.audioBuffer, voice.soundStream.DecodedPacketsInfo);
                sourceVoice.BufferEnd += (context) => trackFinished = true;
                sourceVoice.SetVolume(volume);
                sourceVoice.SetOutputMatrix(1, 2, voice.outputMatrix);
                voice.sourceVoice = sourceVoice;
            }
        }
Exemplo n.º 13
0
 public void SetVolume(float volume)
 {
     if (IsValid)
     {
         m_voice.SetVolume(volume);
     }
 }
Exemplo n.º 14
0
 private void PlatformSetVolume(float value)
 {
     if (_voice != null)
     {
         _voice.SetVolume(value, XAudio2.CommitNow);
     }
 }
Exemplo n.º 15
0
 public void setVolume(float v)
 {
     if (!isNull())
     {
         sourceVoice.SetVolume(v);
     }
     m_volume = v;
 }
Exemplo n.º 16
0
 public void SetVolume(float volume)
 {
     m_volumeBase = volume;
     if (IsValid)
     {
         m_voice.SetVolume(m_volumeBase * m_volumeMultiplier);
     }
 }
Exemplo n.º 17
0
        public void PlaySound(string file, double volume)
        {
            if (!FileNameLookup.ContainsKey(file))
            {
                file = FileNameLookup[file] = new System.IO.FileInfo(file).FullName;
            }
            else
            {
                file = FileNameLookup[file];
            }
            if (!CurrentVoices.ContainsKey(file))
            {
                CurrentVoices.Add(file, new Queue <SourceVoice>());
            }
            //if (CurrentVoices[file].Count > 0)
            //{
            //    var voice = CurrentVoices[file].Dequeue();
            //    voice.SetVolume((float)volume);
            //    voice.Start();
            //    return;
            //}
            SoundData data;

            if (!Voices.ContainsKey(file))
            {
                using (var nativeFilestream = new NativeFileStream(file, NativeFileMode.Open, NativeFileAccess.Read))
                    using (var soundstream = new SoundStream(nativeFilestream))
                    {
                        var waveformat = soundstream.Format;
                        var buffer     = new AudioBuffer()
                        {
                            Stream     = soundstream.ToDataStream(),
                            AudioBytes = (int)soundstream.Length,
                            Flags      = BufferFlags.EndOfStream
                        };
                        data = new SoundData()
                        {
                            waveformat         = waveformat,
                            buffer             = buffer,
                            decodedPacketsInfo = soundstream.DecodedPacketsInfo
                        };
                        Voices.Add(file, data);
                    }
            }
            else
            {
                data = Voices[file];
            }
            var sourceVoice = new SourceVoice(xaudio, data.waveformat, true);

            sourceVoice.SubmitSourceBuffer(data.buffer, data.decodedPacketsInfo);
            sourceVoice.StreamEnd += () =>
            {
                CurrentVoices[file].Enqueue(sourceVoice);
            };
            sourceVoice.SetVolume((float)volume);
            sourceVoice.Start();
        }
Exemplo n.º 18
0
        public void Play()
        {
            Stop();

            AudioBuffer.Stream.Position = 0;

            SourceVoice.SubmitSourceBuffer(AudioBuffer, DecodedPacketsInfo);
            SourceVoice.SetVolume(Volume);
            SourceVoice.Start();
        }
Exemplo n.º 19
0
        public void play()
        {
            var         dataStream = DataStream.Create(BufferSamples, true, true);
            AudioBuffer buffer     = new AudioBuffer
            {
                /*LoopCount = AudioBuffer.LoopInfinite,*/
                Stream     = dataStream,
                AudioBytes = (int)dataStream.Length,
                Flags      = BufferFlags.EndOfStream
            };


            sourcevoice.SubmitSourceBuffer(buffer, null);
            sourcevoice.SetVolume(vol);



            sourcevoice.Start();
        }
Exemplo n.º 20
0
        public int Play(PlayOptions options)
        {
            if (!isLoaded)
            {
                Load();
            }

            if (options.Repeats != defaultRepeat)
            {
                int loopCount;
                if (options.Repeats == -1)
                {
                    loopCount = AudioBuffer.LoopInfinite;
                }
                else
                {
                    loopCount = options.Repeats;
                }

                LoadNextVoice(loopCount);
            }

            if (options.Pan != 0)
            {
                float   panLeft    = (float)0.5 - (options.Pan / 2);
                float   panRight   = (float)0.5 + (options.Pan / 2);
                int     matrixSize = masteringVoice.VoiceDetails.InputChannelCount * nextVoice.VoiceDetails.InputChannelCount;
                float[] matrix     = new float[matrixSize];

                for (int i = 0; i < matrixSize; i++)
                {
                    if (i % 2 == 0)
                    {
                        matrix[i] = panLeft;
                    }
                    else
                    {
                        matrix[i] = panRight;
                    }
                }

                nextVoice.SetOutputMatrix(nextVoice.VoiceDetails.InputChannelCount, masteringVoice.VoiceDetails.InputChannelCount, matrix);
            }

            nextVoice.SetFrequencyRatio(options.Pitch);
            nextVoice.SetVolume(options.Volume);

            Play();

            return(voiceListKey);
        }
Exemplo n.º 21
0
 public void SetVolume(float volume)
 {
     m_volumeBase = volume;
     if (IsValid)
     {
         try
         {
             m_voice.SetVolume(m_volumeBase * m_volumeMultiplier);
         }
         catch (NullReferenceException)
         {
         }
     }
 }
Exemplo n.º 22
0
 /// <summary>
 /// Load an instrument
 /// </summary>
 /// <param name="instr">Sample instrument, or synthesis instrument</param>
 public void LoadInstrument(IInstrument instr)
 {
     if (Voice != null)
     {
         Destroy();
     }
     Instrument = instr;
     Voice      = new SourceVoice(Device, new WaveFormat(44100, 16, 1), VoiceFlags.None, 16, false);
     ReloadBuffer(1, true);
     Voices.Add(Voice);
     Voice.SetVolume(1, XAudio2.CommitNow);
     ActualFrequencyRatio = 1;
     PlayingPitch         = -1;
 }
Exemplo n.º 23
0
        private void SetupVoice(AudioFormat format)
        {
            WaveFormat wFmt = new WaveFormat(format.SampleRate, format.BitsPerSample, format.Channels);

            SourceVoice = new SourceVoice(_engine.Device, wFmt);

            if (_submixer != null)
            {
                var vsDesc = new VoiceSendDescriptor(_submixer.SubMixerVoice);
                SourceVoice.SetOutputVoices(new VoiceSendDescriptor[] { vsDesc });
            }

            SourceVoice.SetVolume(_volume);
        }
Exemplo n.º 24
0
 private void Play(float volume)
 {
     IsFinished = false;
     try
     {
         _sourceVoice.SubmitSourceBuffer(_buffer, _stream.DecodedPacketsInfo);
         _sourceVoice.SetVolume(volume * PlayerConfig.Current.Volume.Main * PlayerConfig.Current.Volume.Hitsound);
         _sourceVoice.Start();
     }
     catch (Exception)
     {
         IsFinished = true;
     }
 }
Exemplo n.º 25
0
        /// <summary>
        /// Воспроизвести звуковой эффект.
        /// </summary>
        /// <param name="source">Путь к WAV файлу.</param>
        /// <param name="volume">Громкость (-224 <> 224)</param>
        public async Task PlaySound(string source, float volume = 1)
        {
            if (volume < -224 || volume > 224)
            {
                throw new ArgumentOutOfRangeException("volume");
            }

            var buffer = await GetBuffer(source);

            var sourceVoice = new SourceVoice(xAudio, buffer.WaveFormat, true);

            sourceVoice.SetVolume(volume, XAudio2.CommitNow);
            sourceVoice.SubmitSourceBuffer(buffer, buffer.DecodedPacketsInfo);
            sourceVoice.Start();
        }
Exemplo n.º 26
0
 public void NoteOn(byte num, byte key, byte velocity)
 {
     try
     {
         Instrument  instrument  = instrumentTable[new Tuple <byte, byte>(Bank, Instrument)];
         int         value       = instrument.GetSampleEntry(key).Value;
         Sample      sample      = soundData.SampleBanks[soundData.InstrumentBanks[Bank].Wsys][(short)instrument.Samples[value].Id];
         AudioBuffer audioBuffer = new AudioBuffer();
         audioBuffer.AudioBytes = sample.Data.Length;
         audioBuffer.Stream     = new DataStream(sample.Data.Length, canRead: true, canWrite: true);
         audioBuffer.Stream.Write(sample.Data, 0, sample.Data.Length);
         audioBuffer.PlayBegin  = 0;
         audioBuffer.PlayLength = 0;
         audioBuffer.LoopCount  = (sample.IsLooping ? 255 : 0);
         audioBuffer.LoopBegin  = sample.LoopStart;
         audioBuffer.LoopLength = 0;
         WaveFormat  sourceFormat = new WaveFormat(sample.SamplesPerSecond, sample.BitsPerSample, sample.Channels);
         SourceVoice sourceVoice  = new SourceVoice(engine, sourceFormat, VoiceFlags.None, 1024f);
         sourceVoice.SetOutputVoices(new VoiceSendDescriptor(submix));
         sourceVoice.SubmitSourceBuffer(audioBuffer, null);
         float num2 = XAudio2.SemitonesToFrequencyRatio((!instrument.IsPercussion) ? (key - sample.RootKey) : 0) * instrument.Samples[value].FrequenyMultiplier * instrument.FrequencyMultiplier;
         sourceVoice.SetFrequencyRatio(num2);
         sourceVoice.SetVolume(ValueToAmplitude(velocity));
         NoteData noteData = new NoteData(sourceVoice, num2, velocity, instrument.IsPercussion);
         if (instrument.IsPercussion)
         {
             noteData.PercussionPan = instrument.Samples[value].Pan.Value;
             sbyte b = (sbyte)(noteData.PercussionPan - 63);
             sourceVoice.SetOutputMatrix(1, 2, new float[2]
             {
                 0.5f - (float)b / 127f,
                 0.5f + (float)b / 127f
             });
         }
         else
         {
             sourceVoice.SetOutputMatrix(1, 2, outputMatrix);
         }
         noteData.BufferStream = audioBuffer.Stream;
         noteData.Voice.Start();
         voiceTable.Add(num, noteData);
         sourceFormat = null;
         GC.Collect();
     }
     catch
     {
     }
 }
Exemplo n.º 27
0
        private void InitializeAudio(AwcAudio audio, float playBegin = 0)
        {
            currentAudio = audio;
            trackLength  = audio.Length;

            if (xAudio2 == null)
            {
                xAudio2        = new XAudio2();
                masteringVoice = new MasteringVoice(xAudio2);
            }

            Stream      wavStream   = audio.GetWavStream();
            SoundStream soundStream = new SoundStream(wavStream);

            audioBuffer = new AudioBuffer
            {
                Stream     = soundStream.ToDataStream(),
                AudioBytes = (int)soundStream.Length,
                Flags      = BufferFlags.EndOfStream
            };
            if (playBegin > 0)
            {
                audioBuffer.PlayBegin = (int)(soundStream.Format.SampleRate * playBegin) / 128 * 128;
                if (playtime.IsRunning)
                {
                    playtime.Restart();
                }
                else
                {
                    playtime.Reset();
                }
                playBeginMs = (int)(playBegin * 1000);
            }
            else
            {
                playBeginMs = 0;
            }
            soundStream.Close();
            wavStream.Close();

            trackFinished = false;
            sourceVoice   = new SourceVoice(xAudio2, soundStream.Format, true);
            sourceVoice.SubmitSourceBuffer(audioBuffer, soundStream.DecodedPacketsInfo);
            sourceVoice.BufferEnd += (context) => trackFinished = true;
            sourceVoice.SetVolume((float)VolumeTrackBar.Value / 100);
        }
Exemplo n.º 28
0
 public void Say(string speech, float pan = 0)
 {
     Task.Run(async() =>
     {
         if (currentSpeechVoice != null)
         {
             while (Math.Abs(currentSpeechVoice.Volume) > 0.001f)
             {
                 currentSpeechVoice.SetVolume(MathHelper.Clamp(currentSpeechVoice.Volume - 0.00005f, 0f, 1f));
             }
             currentSpeechVoice.Stop();
         }
         _speechSynthesizer.Voice = SpeechSynthesizer.AllVoices.First(p => p.Gender == VoiceGender.Female);
         var stream         = await _speechSynthesizer.SynthesizeTextToStreamAsync(speech);
         var c              = new Cue(this, AudioChannels.Synth, stream.AsStreamForRead());
         currentSpeechVoice = c.Start(pan);
     });
 }
Exemplo n.º 29
0
        public void PlayImmediate(short[] data, int sampleRate, float volume)
        {
            StopImmediate();

            immediateDonePlaying = false;

            immediateAudioBuffer = new AudioBuffer();
            immediateAudioBuffer.AudioDataPointer = Utilities.AllocateMemory(data.Length * sizeof(short));
            immediateAudioBuffer.AudioBytes       = data.Length * sizeof(short);
            Marshal.Copy(data, 0, immediateAudioBuffer.AudioDataPointer, data.Length);

            var waveFormat = new WaveFormat(sampleRate, 16, 1);

            immediateVoice            = new SourceVoice(xaudio2, waveFormat);
            immediateVoice.BufferEnd += ImmediateVoice_BufferEnd;
            immediateVoice.SetVolume(volume);
            immediateVoice.SubmitSourceBuffer(immediateAudioBuffer, null);
            immediateVoice.Start();
        }
Exemplo n.º 30
0
        private void PlaySound(int soundID,
                               Emitter emitter,
                               float volume,
                               LinkedSoundList list,
                               ref VoiceSendDescriptor voiceSendDescriptor,
                               Action <IntPtr>?onFxEnd = null)
        {
            if (!_soundBuffer.TryGetValue(soundID, out SoundBuffer buffer))
            {
                return;
            }

            SourceVoice sourceVoice = new SourceVoice(_xAudio2, buffer.Format, VoiceFlags.None, true);

            sourceVoice.SetVolume(volume);
            sourceVoice.SubmitSourceBuffer(buffer.AudioBuffer, buffer.DecodedPacketsInfo);
            sourceVoice.SetOutputVoices(voiceSendDescriptor);

            LinkedSoundList.Sound sound = new LinkedSoundList.Sound(emitter, sourceVoice);
            list.Add(sound);

            sourceVoice.BufferEnd += _ =>
            {
                list.Remove(sound);
                sourceVoice.DestroyVoice();
            };

            if (onFxEnd != null)
            {
                sourceVoice.BufferEnd += onFxEnd;
            }
            sourceVoice.Start();

            DspSettings settings = _x3DAudio.Calculate(
                _listener,
                sound.Emitter,
                CalculateFlags.Matrix | CalculateFlags.Doppler,
                buffer.Format.Channels,
                _inputChannelCount);

            sound.SourceVoice.SetOutputMatrix(buffer.Format.Channels, _inputChannelCount, settings.MatrixCoefficients);
            sound.SourceVoice.SetFrequencyRatio(settings.DopplerFactor);
        }