Ejemplo n.º 1
0
        private void TaskAudioPlayback(CancellationToken cancelToken, BlockingCollection <ClientAudio> queue)
        {
            //var lastTransmitTime = DateTime.UtcNow;
            //string lastTransmitClientID = "";

            while (!cancelToken.IsCancellationRequested)
            {
                if (queue.TryTake(out ClientAudio data, 100))
                {
                    byte[] decoded = _decoder.Decode(data.Data, data.Data.Length, out int decodedLength);

                    if (networkAudioBuffers.Any(b => b.Callsign == data.Callsign))
                    {
                        var buffer = networkAudioBuffers.First(b => b.Callsign == data.Callsign);
                        buffer.LastUsedUTC = DateTime.UtcNow;
                        buffer.Provider.AddSamples(decoded, 0, decodedLength);
                    }
                    else if (networkAudioBuffers.Any(b => b.InUse == false))
                    {
                        var reader = new WaveFileReader("Samples\\click_float.wav");     //Start of transmission
                        mixer.AddInputStream(reader);
                        var buffer = networkAudioBuffers.First(b => b.InUse == false);
                        buffer.InUse       = true;
                        buffer.Callsign    = data.Callsign;
                        buffer.LastUsedUTC = DateTime.UtcNow;
                        buffer.Provider.AddSamples(decoded, 0, decodedLength);
                    }
                }
                else
                {
                    CleanupNetworkAudioBuffers();
                }
            }
            taskAudioPlayback = null;
        }
Ejemplo n.º 2
0
        public static void SetMusic(string musicFile)
        {
            if (!File.Exists(musicFile))
            {
                Console.WriteLine("file not found: " + musicFile);
                return;
            }
            if (music != null)
            {
                mixer.RemoveInputStream(music);
                music.Dispose();
            }
            var audioFileReader = new AudioFileReader(musicFile);

            if (audioFileReader.WaveFormat.SampleRate != mixer.WaveFormat.SampleRate)
            {
                audioFileReader.Dispose();
                musicCompatible = false;
                return;
            }
            musicCompatible = true;
            music           = new WaveChannel32(audioFileReader)
            {
                Volume = 0.2f
            };
            mixer.AddInputStream(music);
            sw.Restart();
            //music.CurrentTime = new TimeSpan(0, 0, 30);
        }
Ejemplo n.º 3
0
        static Audio()
        {
            var asioDrivers = AsioOut.GetDriverNames();

            if (asioDrivers.Length == 0)
            {
                Console.WriteLine("please install http://www.asio4all.org/");
                Console.WriteLine("press any key to exit");
                Console.ReadKey();
                Environment.Exit(0);
            }
            asioOut = new AsioOut(asioDrivers[0]);
            mixer   = new MixingWaveProvider32();
            hit     = new WaveChannel32(new AudioFileReader("hitsound.wav"))
            {
                Volume = 0.2f,
            };
            miss = new WaveChannel32(new AudioFileReader("miss.wav"))
            {
                Volume = 0.2f,
            };
            var err = new SignalGenerator()
            {
                Type = SignalGeneratorType.SawTooth,
                Gain = 0.2,
            }.Take(TimeSpan.FromSeconds(0.1d)).ToWaveProvider();

            mixer.AddInputStream(hit);
            mixer.AddInputStream(miss);
            asioOut.Init(mixer);
            asioOut.Play();
        }
Ejemplo n.º 4
0
        public override async Task <CommandResult> RunVoiceCommand(string[] args, CommandContext context, ConnectionModel connection)
        {
            if (connection.Recording)
            {
                connection.Recording = false;
            }
            else
            {
                try
                {
                    SilenceProvider silence = new SilenceProvider(format);
                    mixer.AddInputStream(new Wave16ToFloatProvider(silence));
                    mixer.AddInputStream(new Wave16ToFloatProvider(new VolumeWaveProvider16(connection.RecordBuffer)
                    {
                        Volume = 0.1f
                    }));

                    path = Path.ChangeExtension(Path.GetTempFileName(), ".wav");

                    recorder = new WaveRecorder(mixer, path);
                    model    = connection;

                    connection.Connection.VoiceReceived += Connection_VoiceReceived;
                    connection.Disconnected             += Connection_Disconnected;
                    connection.Recording = true;

                    await context.ReplyAsync("Now recording...");

                    output = new WaveOut();
                    output.Init(new VolumeWaveProvider16(new WaveFloatTo16Provider(recorder))
                    {
                        Volume = 0.0f
                    });

                    int pingInSamples = (48000 * (connection.Connection.Ping / 1000)) * 2;
                    connection.RecordBuffer.ClearBuffer();
                    connection.RecordBuffer.AddSamples(Enumerable.Repeat((byte)0, pingInSamples).ToArray(), 0, pingInSamples);
                    output.Play();
                }
                catch { }

                while (connection.Connected && connection.Recording)
                {
                    await Task.Delay(100);
                }

                await CleanupAsync();

                string newPath = new Uri(Path.Combine(Path.GetTempPath(), $"{context.Guild.Name.ToLower()} - {DateTime.Now.ToString("dd-MM-yyyy HH-mm", CultureInfo.InvariantCulture)}.mp3")).LocalPath;
                MediaFoundationEncoder.EncodeToMp3(new WaveFileReader(path), newPath);
                await context.Channel.SendFileAsync(newPath, $"Here's your ~~clusterfuck~~ recording!");
            }

            return(CommandResult.Empty);
        }
Ejemplo n.º 5
0
        public void UpdateDevices(MMDevice input, MMDevice output)
        {
            outp?.Stop();
            outp?.Dispose();

            inp?.StopRecording();
            inp?.Dispose();

            inp = new WasapiCapture(input, true, 5);
            inp.DataAvailable += OnCapture;

            buffer = new BufferedWaveProvider(inp.WaveFormat);

            mixer = new MixingWaveProvider32();
            mixer.AddInputStream(buffer);

            if (resampler == null)
            {
                resampler = new AudioResampler(mixer);
            }
            else
            {
                resampler.Update(mixer);
            }

            outp = new WasapiOut(output, AudioClientShareMode.Shared, true, 5);
            outp.Init(resampler);

            inp.StartRecording();
            outp.Play();
        }
Ejemplo n.º 6
0
        private void InitializeSounds(MixingWaveProvider32 soundMixer)
        {
            var workingDir   = System.AppDomain.CurrentDomain.BaseDirectory;
            var soundsFolder = System.IO.Path.Combine(workingDir, "Audio");

            IAdjustableSound LoadSoundOrCreateDummyFrom(string fileName)
            {
                var filePath = System.IO.Path.Combine(soundsFolder, fileName);

                if (!File.Exists(filePath))
                {
                    StatusBlock.Text += $"File {filePath} not found. Not loading sound...\n";
                    return(new DummySound());
                }

                var loadedSound = new AdjustableSound(filePath);

                soundMixer.AddInputStream(loadedSound);
                return(loadedSound);
            }

            _engineRunSound  = LoadSoundOrCreateDummyFrom("train_engine_layer_piston.wav");
            _engineIdleSound = LoadSoundOrCreateDummyFrom("train_engine_layer_idle_01.wav");
            _gearboxSound    = LoadSoundOrCreateDummyFrom("train_engine_layer_gear.wav");
        }
Ejemplo n.º 7
0
        public void PlayAudioSample(string path)
        {
            StopPlaying();
            var reader = new MediaFoundationReader(path);
            var stream = new MediaFoundationResampler(reader, inp.WaveFormat);

            last = stream;
            mixer.AddInputStream(last);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Plays given chord.
        /// </summary>
        /// <param name="chordName">Name of chord played</param>
        public void PlayChord(ChordName chordName)
        {
            Chord chord = new Chord(scale, chordName);

            foreach (Pitch pitch in chord.Tones)
            {
                harmonyProvider.AddInputStream(PitchSelector.GetWavePlayer(pitch, session.WaveForm).Channel);
            }
            lastChord = chord;
        }
Ejemplo n.º 9
0
        public void FadeInOut(WavePlayer fadein, WavePlayer fadeout, int milliSeconds)
        {
            var fadeInProvider  = fadein._reader.ToSampleProvider();
            var fadeOutProvider = fadeout._reader.ToSampleProvider();

            _mixer.RemoveInputStream(fadeout._channels);
            _mixer.RemoveInputStream(fadein._channels);

            var fadeOutObject = new FadeInOutSampleProvider(fadeOutProvider);
            var fadeInObject  = new FadeInOutSampleProvider(fadeInProvider);

            var waveStream  = new WaveProviderToWaveStream(fadeOutObject.ToWaveProvider());
            var waveStream2 = new WaveProviderToWaveStream(fadeInObject.ToWaveProvider());

            fadeout._channels = new WaveChannel32(waveStream);
            fadein._channels  = new WaveChannel32(waveStream2);

            _mixer.AddInputStream(fadeout._channels);
            _mixer.AddInputStream(fadein._channels);

            fadeOutObject.BeginFadeOut(milliSeconds);
            fadeInObject.BeginFadeIn(milliSeconds);
        }
Ejemplo n.º 10
0
        public GameBoyAudioMixer()
        {
            Channels = new List <NAudioChannelOutput>
            {
                new NAudioChannelOutput(this, "Square + Sweep"),
                new NAudioChannelOutput(this, "Square"),
                new NAudioChannelOutput(this, "Wave"),
                new NAudioChannelOutput(this, "Noise"),
            }.AsReadOnly();

            foreach (var channel in Channels)
            {
                _mixer.AddInputStream(channel);
            }
        }
Ejemplo n.º 11
0
        public GameBoyAudioMixer()
        {
            Channels = new List <NAudioChannelOutput>
            {
                new NAudioChannelOutput(this),
                new NAudioChannelOutput(this),
                new NAudioChannelOutput(this),
                new NAudioChannelOutput(this),
            }.AsReadOnly();

            foreach (var channel in Channels)
            {
                _mixer.AddInputStream(channel);
            }
        }
Ejemplo n.º 12
0
        public static void PlaySound(string path)
        {
            soundStream = getWaveStream(path);

            var mixer = new MixingWaveProvider32();

            soundWaveChannel = new WaveChannel32(soundStream);
            soundWaveChannel.PadWithZeroes = false;
            // set the volume of background file
            soundWaveChannel.Volume = soundVolume;
            //add stream into the mixer
            mixer.AddInputStream(soundWaveChannel);

            soundOutput.Init(mixer);

            soundOutput.Play();
        }
Ejemplo n.º 13
0
 public static void AddWaveProvider(IWaveProvider waveprovider, string name)
 {
     //Wave16ToFloatProviderとか使ってIeeeFloatにしないとだめ
     if (waveprovider.WaveFormat.Encoding != WaveFormatEncoding.IeeeFloat)
     {
         return;
     }
     if (waveprovider.WaveFormat.SampleRate != waveformat.SampleRate ||
         waveprovider.WaveFormat.Channels != waveformat.Channels)
     {
         return;
     }
     if (DctWaveProvider.ContainsKey(name))
     {
         RemoveWaveProvider(name);
     }
     DctWaveProvider.Add(name, waveprovider);
     mixer.AddInputStream(waveprovider);
 }
Ejemplo n.º 14
0
        public void Play(IEnumerable <Beeper> beepers, bool looping = false)
        {
            Beepers = beepers;

            MixingWaveProvider32 mixer = new MixingWaveProvider32();

            foreach (Beeper beeper in beepers)
            {
                beeper.Stream.Seek(0, SeekOrigin.Begin);
                mixer.AddInputStream(new WaveChannel32(new WaveFileReader(beeper.Stream)));
            }

            Sound = new WaveOut(WaveCallbackInfo.FunctionCallback());
            Sound.Init(mixer);

            IsLooping              = looping;
            Sound.PlaybackStopped += OnSoundPlayBackStopped;
            Sound.Play();
            IsPlaying = true;
        }
Ejemplo n.º 15
0
 //Voor het afspelen van een geluid
 public static void PlaySound(SineWaveProvider32 wave)
 {
     WaveList.Add(wave);                                          //Geluid wordt toegevoegd aan de lijst met huidige items in de queue.
     mixingWaveProvider.AddInputStream(WaveList.LastOrDefault()); //Meest recente Item wordt toegevoegd aan de mixer
     outputDevice.Play();                                         //Speelt geluid af.
 }
Ejemplo n.º 16
0
        public void Start(string serverIpAddress, string clientID, string inputDevice, string outputDevice)
        {
            _startTime = DateTime.Now;
            callsign   = clientID;

            taskDataPub = new Task(() => TaskDataPub(cancelTokenSource.Token, dataPublishInputQueue, "tcp://" + serverIpAddress + ":60001"), TaskCreationOptions.LongRunning);
            taskDataPub.Start();
            taskDataSub = new Task(() => TaskDataSub(cancelTokenSource.Token, "tcp://" + serverIpAddress + ":60000"), TaskCreationOptions.LongRunning);
            taskDataSub.Start();
            taskAudioPub = new Task(() => TaskAudioPub(cancelTokenSource.Token, audioPublishInputQueue, "tcp://" + serverIpAddress + ":60003"), TaskCreationOptions.LongRunning);
            taskAudioPub.Start();
            taskAudioSub = new Task(() => TaskAudioSub(cancelTokenSource.Token, audioPlaybackQueue, "tcp://" + serverIpAddress + ":60002"), TaskCreationOptions.LongRunning);
            taskAudioSub.Start();

            _segmentFrames   = 960;
            _encoder         = OpusEncoder.Create(48000, 1, FragLabs.Audio.Codecs.Opus.Application.Voip);
            _encoder.Bitrate = 65536;
            _decoder         = OpusDecoder.Create(48000, 1);
            _bytesPerSegment = _encoder.FrameByteCount(_segmentFrames);

            _waveIn = new WaveIn(WaveCallbackInfo.FunctionCallback());
            _waveIn.BufferMilliseconds = 50;
            Console.WriteLine("Input device: " + WaveIn.GetCapabilities(0).ProductName);
            _waveIn.DeviceNumber   = MapInputDevice(inputDevice);
            _waveIn.DataAvailable += _waveIn_DataAvailable;
            _waveIn.WaveFormat     = new WaveFormat(48000, 16, 1);

            networkAudioBuffers = new List <ClientMixerInput>
            {
                new ClientMixerInput()
                {
                    InUse    = false,
                    Provider = new BufferedWaveProvider(new WaveFormat(48000, 16, 1))
                               //Provider = new BufferedWaveProvider(WaveFormat.CreateIeeeFloatWaveFormat(48000, 1))
                },
                new ClientMixerInput()
                {
                    InUse    = false,
                    Provider = new BufferedWaveProvider(new WaveFormat(48000, 16, 1))
                               //Provider = new BufferedWaveProvider(WaveFormat.CreateIeeeFloatWaveFormat(48000, 1))
                },
                new ClientMixerInput()
                {
                    InUse    = false,
                    Provider = new BufferedWaveProvider(new WaveFormat(48000, 16, 1))
                               //Provider = new BufferedWaveProvider(WaveFormat.CreateIeeeFloatWaveFormat(48000, 1))
                },
                new ClientMixerInput()
                {
                    InUse    = false,
                    Provider = new BufferedWaveProvider(new WaveFormat(48000, 16, 1))
                               //Provider = new BufferedWaveProvider(WaveFormat.CreateIeeeFloatWaveFormat(48000, 1))
                }
            };

            mixer = new MixingWaveProvider32();
            //mixer.ReadFully = true;
            foreach (var buffer in networkAudioBuffers)
            {
                mixer.AddInputStream(new SampleToWaveProvider(new Equalizer(new WaveToSampleProvider(new Wave16ToFloatProvider(buffer.Provider)), bands)));
            }
            //_playBuffer = new BufferedWaveProvider(mixer.WaveFormat);
            //mixer.AddInputStream(_playBuffer);
            taskAudioPlayback = new Task(() => TaskAudioPlayback(cancelTokenSource.Token, audioPlaybackQueue), TaskCreationOptions.LongRunning);
            taskAudioPlayback.Start();

            //_waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback());
            _waveOut = new WaveOut();
            Console.WriteLine("Output device: " + WaveOut.GetCapabilities(0).ProductName);
            _waveOut.DeviceNumber   = MapOutputDevice(outputDevice);
            _waveOut.DesiredLatency = 200;      //Default is 300
            //_waveOut.Init(_playBuffer);
            _waveOut.Init(mixer);
            _waveOut.Play();
            _waveIn.StartRecording();

            if (_timer == null)
            {
                _timer          = new System.Timers.Timer();
                _timer.Interval = 1000;
                _timer.Elapsed += _timer_Elapsed;
            }
            _timer.Start();

            started = true;
        }