Init() public method

Initialises the WaveOut device
public Init ( IWaveProvider waveProvider ) : void
waveProvider IWaveProvider WaveProvider to play
return void
		public AudioStreamHandler()
		{
		    log = Logger.GetLogger(GetType());
            WaveIn = new WasapiLoopbackCapture();
			WaveIn.DataAvailable += DataAvailable;
		    WaveIn.RecordingStopped += RecordingStopped;
            WaveOut = new WaveOut();
		    WaveOut.Init(new SilentWaveProvider());
		}
Exemplo n.º 2
2
 private void playButton_Click(object sender, EventArgs e)
 {
     waveOut = new WaveOut();
     waveOut.PlaybackStopped += waveOut_PlaybackStopped;
     reader = new WaveFileReader("sample.wav");
     waveOut.Init(reader);
     waveOut.Play();
 }
Exemplo n.º 3
0
 public void PlaySound(string name, Action done = null)
 {
     FileStream ms = File.OpenRead(_soundLibrary[name]);
     var rdr = new Mp3FileReader(ms);
     WaveStream wavStream = WaveFormatConversionStream.CreatePcmStream(rdr);
     var baStream = new BlockAlignReductionStream(wavStream);
     var waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback());
     waveOut.Init(baStream);
     waveOut.Play();
     var bw = new BackgroundWorker();
     bw.DoWork += (s, o) =>
                      {
                          while (waveOut.PlaybackState == PlaybackState.Playing)
                          {
                              Thread.Sleep(100);
                          }
                          waveOut.Dispose();
                          baStream.Dispose();
                          wavStream.Dispose();
                          rdr.Dispose();
                          ms.Dispose();
                          if (done != null) done();
                      };
     bw.RunWorkerAsync();
 }
Exemplo n.º 4
0
        void StartEncoding()
        {
            _startTime = DateTime.Now;
            _bytesSent = 0;
            _segmentFrames = 960;
            _encoder = new OpusEncoder(48000, 1, OpusNet.OpusApplication.Voip);
            _encoder.Bitrate = 8192;
            _decoder = new OpusDecoder(48000, 1);
            _bytesPerSegment = _encoder.FrameByteCount(_segmentFrames);

            _waveIn = new WaveIn(WaveCallbackInfo.FunctionCallback());
            _waveIn.BufferMilliseconds = 50;
            _waveIn.DeviceNumber = comboBox1.SelectedIndex;
            _waveIn.DataAvailable += _waveIn_DataAvailable;
            _waveIn.WaveFormat = new WaveFormat(48000, 16, 1);

            _playBuffer = new BufferedWaveProvider(new WaveFormat(48000, 16, 1));

            _waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback());
            _waveOut.DeviceNumber = comboBox2.SelectedIndex;
            _waveOut.Init(_playBuffer);

            _waveOut.Play();
            _waveIn.StartRecording();

            if (_timer == null)
            {
                _timer = new Timer();
                _timer.Interval = 1000;
                _timer.Tick += _timer_Tick;
            }
            _timer.Start();
        }
Exemplo n.º 5
0
        //--------------------controls----------------------------------------
        /// <summary>
        /// Starts to play a file
        /// </summary>
        public void play()
        {
            try
            {
                //Call a helper method (look in the botom) to reset the playback

                stop();
                // open uncompresed strem pcm from mp3 file reader compresed stream.
                NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(this.songPath));

                stream = new NAudio.Wave.BlockAlignReductionStream(pcm);

                volProvider             = new VolumeWaveProvider16(stream);
                volProvider.Volume      = vol;
                output                  = new NAudio.Wave.WaveOut();//new NAudio.Wave.DirectSoundOut();
                output.PlaybackStopped += output_PlaybackStopped;
                output.Init(volProvider);
                output.Play();
                checkPlayback();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemplo n.º 6
0
        private void Form1_Load(object sender, EventArgs e)
        {
            byte[] apk, ask, bpk, bsk;
            NaClClient.CreateKeys(out apk, out ask);
            NaClClient.CreateKeys(out bpk, out bsk);

            var hasher = System.Security.Cryptography.SHA256.Create();

            _clientA = NaClClient.Create(apk, ask, bpk);
            _clientB = NaClClient.Create(bpk, bsk, apk);

            _sw = new Stopwatch();
            _sw.Start();

            _wave = new WaveIn(this.Handle);
            _wave.WaveFormat = new WaveFormat(12000, 8, 1);
            _wave.BufferMilliseconds = 100;
            _wave.DataAvailable += _wave_DataAvailable;
            _wave.StartRecording();

            _playback = new BufferedWaveProvider(_wave.WaveFormat);

            _waveOut = new WaveOut();
            _waveOut.DesiredLatency = 100;
            _waveOut.Init(_playback);
            _waveOut.Play();
        }
Exemplo n.º 7
0
        public static Task Play(this Captcha captcha)
        {
            return Task.Run(() =>
            {
                using (MemoryStream memory = new MemoryStream(captcha.Data, false))
                {
                    memory.Seek(0, SeekOrigin.Begin);

                    using (Mp3FileReader reader = new Mp3FileReader(memory))
                    using (WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(reader))
                    using (WaveStream stream = new BlockAlignReductionStream(pcm))
                    {
                        using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
                        {
                            waveOut.Init(stream);
                            waveOut.Play();

                            while (waveOut.PlaybackState == PlaybackState.Playing)
                            {
                                Thread.Sleep(100);
                            }
                        }
                    }
                }
            });
        }
Exemplo n.º 8
0
        public void Initialise(WaveFormat format, WaveOut driver)
        {
            if (driver == null)
            {
                throw new ArgumentNullException("driver", "Must specify a WaveIn device instance");
            }

            if (format == null)
            {
                throw new ArgumentNullException("format", "Must specify an audio format");
            }

            var caps = WaveOut.GetCapabilities(driver.DeviceNumber);

            device = new WaveOutDeviceData
            {
                Driver = driver,
                Name = caps.ProductName,
                Channels = caps.Channels,
                Buffers = new float[caps.Channels][]
            };

            Format = WaveFormat.CreateIeeeFloatWaveFormat(format.SampleRate, caps.Channels);
            OutputBuffer = new BufferedWaveProvider(Format);
            OutputBuffer.DiscardOnBufferOverflow = true;

            driver.Init(OutputBuffer);

            mapOutputs();
        }
Exemplo n.º 9
0
        public void Start()
        {
            if (WaveIn.DeviceCount < 1)
                throw new Exception("Insufficient input device(s)!");

            if (WaveOut.DeviceCount < 1)
                throw new Exception("Insufficient output device(s)!");

            frame_size = toxav.CodecSettings.audio_sample_rate * toxav.CodecSettings.audio_frame_duration / 1000;

            toxav.PrepareTransmission(CallIndex, false);

            WaveFormat format = new WaveFormat((int)toxav.CodecSettings.audio_sample_rate, (int)toxav.CodecSettings.audio_channels);
            wave_provider = new BufferedWaveProvider(format);
            wave_provider.DiscardOnBufferOverflow = true;

            wave_out = new WaveOut();
            //wave_out.DeviceNumber = config["device_output"];
            wave_out.Init(wave_provider);

            wave_source = new WaveIn();
            //wave_source.DeviceNumber = config["device_input"];
            wave_source.WaveFormat = format;
            wave_source.DataAvailable += wave_source_DataAvailable;
            wave_source.RecordingStopped += wave_source_RecordingStopped;
            wave_source.BufferMilliseconds = (int)toxav.CodecSettings.audio_frame_duration;
            wave_source.StartRecording();

            wave_out.Play();
        }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            var adj = new AdjustableTFunc {Value = 1600};

            var tFuncWaveProvider = new TFuncWaveProvider
                {
            //                  Amplitude = TFunc.Sin(new Frequency(adj.TFunc))
            //                  Amplitude = TFunc.Sin(new Frequency(t => TFuncs.Sin(Frequency.Hertz(1))(t) + 1000))
                    Amplitude = TFunc.Sin(TFunc.Sin(Frequency.Hertz(2)) + 1000)
                };
            var waveOut = new WaveOut();
            waveOut.Init(tFuncWaveProvider);
            waveOut.Play();

            Console.WriteLine("Press q to kill");
            char k;
            while ((k = Console.ReadKey().KeyChar) != 'q')
            {
                if (k == 'u')
                {
                    adj.Value+=10;
                }
                if (k == 'd')
                {
                    adj.Value-=10;
                }
                Console.Write(" ");
                Console.WriteLine(adj.Value);
            }

            waveOut.Stop();
            waveOut.Dispose();
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            // for recording
            waveFileWriter = new WaveFileWriter(@"C:\rec\out.wav", new WaveFormat(44100, 2));

            var sound = new MySound();
            sound.SetWaveFormat(44100, 2);
            sound.init();
            waveOut = new WaveOut();
            waveOut.Init(sound);
            waveOut.Play();

            ConsoleKeyInfo keyInfo;
            bool loop = true;
            while (loop)
            {
                keyInfo = Console.ReadKey();
                if (keyInfo.Key == ConsoleKey.Q)
                {
                    waveOut.Stop();
                    waveOut.Dispose();
                    waveFileWriter.Close();
                    waveFileWriter.Dispose();
                    loop = false;
                }
            }
        }
Exemplo n.º 12
0
 public APU()
 {
     this.audioBuffer = new AudioBuffer();
     NESWaveProvider nesWaveProvider = new NESWaveProvider(audioBuffer);
     waveOut = new WaveOut();
     waveOut.Init(nesWaveProvider);
 }
Exemplo n.º 13
0
 private void StartPlayback()
 {
     masterMix = new MixingSampleProvider(WaveFormat.CreateIeeeFloatWaveFormat(44100, 2));
     foreach (var source in trackSources) masterMix.AddMixerInput(source);
     outDevice = new WaveOut();
     outDevice.Init(masterMix);
     outDevice.Play();
 }
Exemplo n.º 14
0
 public Player(NAudio.Wave.IWaveProvider provider)
 {
     _provider             = provider;
     _waveOut              = new NAudio.Wave.WaveOut();
     _waveOut.DeviceNumber = SelectedDevice;
     _waveOut.Init(_provider);
     Play();
 }
Exemplo n.º 15
0
        //------------------------------------------------------------------------------------------------------------------------
        #endregion

        #region Constructor
        //------------------------------------------------------------------------------------------------------------------------
        public Speaker()
        {
            waveout = new WaveOut();
            bufferedWaveProvider = new BufferedWaveProvider(new WaveFormat(8000, 16, 2));
            waveout.PlaybackStopped += Waveout_PlaybackStopped;
            volumeProvider = new VolumeWaveProvider16(bufferedWaveProvider);
            waveout.Init(volumeProvider);
        }
Exemplo n.º 16
0
 /// <summary>
 /// Первоначальная инициализация звуковой системы
 /// </summary>
 public static void InitAudio()
 {
     player = new Player();
     player.SetWaveFormat(SampleRate, 1);
     waveOut = new WaveOut();
     waveOut.DesiredLatency = 200; // длина буфера /2=50 миллисекунд
     waveOut.Init(player);
 }
 public void Init(string path)
 {
     durationStopwatch = new Stopwatch();
     waveIn = new WasapiLoopbackCapture();
     wri = new LameMP3FileWriter(@path + ".mp3", waveIn.WaveFormat, 32);
     waveOut = new WaveOut();
     waveOut.Init(new SilenceGenerator());
 }
Exemplo n.º 18
0
		private void CreateWaveOut()
		{
			if (_waveOut == null)
			{
				_waveOut = new WaveOut();
				_waveOut.Init(_inStream);
				_waveOut.PlaybackStopped += HandleWaveOutPlaybackStopped;
			}
		}
Exemplo n.º 19
0
 public void PlayMusic(string id)
 {
     NAudio.Vorbis.VorbisWaveReader data = _musicMap[id];
     if (data != null)
     {
         musicPlayer.Init(data);
         musicPlayer.Play();
     }
 }
Exemplo n.º 20
0
Arquivo: Preview.cs Projeto: kebby/jss
        public void Play()
        {
            Stop();
            SetWaveFormat(44100, 2); // 16kHz mono

            Out = new WaveOut();
            Out.Init(this);
            Out.Play();
        }
Exemplo n.º 21
0
 private void playnhac()
 {
     IWavePlayer waveOutDevice;
     AudioFileReader audioFileReader;
     waveOutDevice = new WaveOut();
     audioFileReader = new AudioFileReader("animal.mp3");
     waveOutDevice.Init(audioFileReader);
     waveOutDevice.Play();
 }
Exemplo n.º 22
0
        private void button3_Click_1(object sender, EventArgs e)
        {
            //waveOut

            var reader = new WaveFileReader("v.wav");
            var waveOut = new WaveOut(); // or WaveOutEvent()
            waveOut.Init(reader);
            waveOut.Play();
        }
Exemplo n.º 23
0
 public void PlaySound(string id)
 {
     NAudio.Vorbis.VorbisWaveReader data = _soundMap[id];
     if (data != null)
     {
         soundPlayer.Init(data);
         soundPlayer.Play();
     }
 }
Exemplo n.º 24
0
 public WzMp3Streamer(WzSoundProperty sound, bool repeat)
 {
     this.repeat = repeat;
     this.sound = sound;
     byteStream = new MemoryStream(sound.GetBytes(false));
     mpegStream = new Mp3FileReader(byteStream);
     wavePlayer = new WaveOut(WaveCallbackInfo.FunctionCallback());
     wavePlayer.Init(mpegStream);
     wavePlayer.PlaybackStopped +=new EventHandler(wavePlayer_PlaybackStopped);
 }
Exemplo n.º 25
0
        public static void PlaySound(NotificationSound sound)
        {
            IWavePlayer waveOutDevice;
            AudioFileReader audioFileReader;
            waveOutDevice = new WaveOut();

            audioFileReader = new AudioFileReader("resources/sounds/message.mp3");
            waveOutDevice.Init(audioFileReader);
            waveOutDevice.Play();
        }
Exemplo n.º 26
0
		private async Task PlayAsync(Action onFinished, Action<Viseme> onVisemeHit, CancellationToken token)
		{
			try
			{
				using (var m = new MemoryStream(_tts.waveStreamData))
				{
					using (var reader = new WaveFileReader(m))
					{
						using (var player = new WaveOut())
						{
							player.Init(reader);
							player.Play();

							var visemes = _tts.visemes;

							int nextViseme = 0;
							double nextVisemeTime = 0;

							while (player.PlaybackState == PlaybackState.Playing)
							{
								if (onVisemeHit != null)
								{
									var s = reader.CurrentTime.TotalSeconds;
									if (s >= nextVisemeTime)
									{
										var v = visemes[nextViseme];
										nextViseme++;
										if (nextViseme >= visemes.Length)
											nextVisemeTime = double.PositiveInfinity;
										else
											nextVisemeTime += v.duration;

										onVisemeHit(v.viseme);
									}
								}

								await Task.Delay(1);
								if (token.IsCancellationRequested)
									break;

								//Console.WriteLine("...next");
							}
							player.Stop();
							onFinished?.Invoke();
						}
					}
				}
			}
			catch (Exception e)
			{
				Console.WriteLine(e.Message);
				throw e;
			}
		}
Exemplo n.º 27
0
        public void Play()
        {
            var path = Path.Combine(@"E:\Dropbox\Music\Imagine Dragons\Night Visions", "01 - Radioactive.mp3");
            var wavePlayer = new WaveOut();
            var file = new AudioFileReader(path);
            file.Volume = 0.8f;
            wavePlayer.Init(file);
            ////wavePlayer.PlaybackStopped += wavePlayer_PlaybackStopped;
            wavePlayer.Play();

            Thread.Sleep(10000);
        }
Exemplo n.º 28
0
 public void PlayNonStop()
 {
     var reader = new WaveFileReader(_sample);
         var loop = new LoopStream(reader);
         var effects = new EffectChain();
         var effectStream = new EffectStream(effects, loop);
         _pitch = new SuperPitch();
         effectStream.AddEffect(_pitch);
         _wave = new WaveOut();
         _wave.Init(effectStream);
         _wave.Play();
 }
        public void Play(Uri songUri)
        {
            (songUri != null).Should().BeTrue();
            songUri.IsAbsoluteUri.Should().BeTrue();

            Stop();

            WaveOut = new WaveOut();
            Reader = new Mp3FileReader(songUri.AbsolutePath);
            WaveOut.Init(Reader);
            WaveOut.Play();
        }
Exemplo n.º 30
0
        internal static void Main(string[] args)
        {
            // Create a SID reader.
            sid = new SidReader("Tests/2short1s.sid", 44100, 2, SidModel.MOS8580, SidClock.NTSC);

            // Initialize the player and start.
            IWavePlayer player = new WaveOut();
            player.Init(sid);

            // Initialize track count
            track = sid.CurrentSong;

            // Display the initial track information.
            DisplayTrackInfo();

            // Loop to check if the user hits left or right arrow keys to change tracks.
            ConsoleKeyInfo keyInfo;
            do
            {
                keyInfo = Console.ReadKey();
                if (keyInfo.Key == ConsoleKey.LeftArrow)
                {
                    if (track > 1)
                    {
                        track--;
                        sid.SetTune(track);
                        DisplayTrackInfo();
                    }
                }
                else if (keyInfo.Key == ConsoleKey.RightArrow)
                {
                    if (track != sid.NumberOfSubtunes)
                    {
                        track++;
                        sid.SetTune(track);
                        DisplayTrackInfo();
                    }
                }
                else if (keyInfo.Key == ConsoleKey.Spacebar)
                {
                    if (isPlaying)
                    {
                        player.Pause();
                        isPlaying = false;
                    }
                    else
                    {
                        player.Play();
                        isPlaying = true;
                    }
                }
            } while (keyInfo.Key != ConsoleKey.Escape && keyInfo.Key != ConsoleKey.Enter);
        }
Exemplo n.º 31
0
 // セリフ音声の再生
 private async Task Speak(string s)
 {
     byte[] buffer = (byte[])Properties.Resources.ResourceManager.GetObject(s);
     using var stream     = new MemoryStream(buffer);
     using WaveStream pcm = new Mp3FileReader(stream);
     pl.Init(pcm);
     pl.Play();
     while (pl.PlaybackState == PlaybackState.Playing)
     {
         await Task.Delay(10);
     }
 }
Exemplo n.º 32
0
        public void StopRecord()
        {
            //stop recording
            recordingStream.StopRecording();
            recordingStream.Dispose();
            recordingStream = null;

            //stop writing
            waveWriter.Dispose();
            WaveStream streamOut = new WaveFileReader(waveFileName);
            waveReader = new WaveOut();
            waveReader.Init(streamOut);
        }
Exemplo n.º 33
0
 public void PlayTone(int frequency, double duration) {
     _sineWave.Frequency = frequency;
     ;
     _sineWave.SetWaveFormat(44100, 1);
     using (_waveOut = new WaveOut()) {
         _waveOut.DeviceNumber = 0;
         _waveOut.Init(_sineWave);
         _waveOut.Play();
         System.Threading.Thread.Sleep(2000);
         _waveOut.Stop();
         _waveOut = null;
     }
 }
Exemplo n.º 34
0
        public void SetAudioData(byte[] wavData)
        {
            ClearAudioData();

            var wavStream = new MemoryStream(wavData);
            _waveProvider = new WaveFileReader(wavStream);
            _waveOut = new WaveOut();
            _loopStream = new LoopStream(_waveProvider);
            _waveOut.Init(_loopStream);
            _waveOut.Volume = _volume;

            HasData = true;
        }
Exemplo n.º 35
0
        public void play_sound(string file)
        {
            NAudio.Wave.DirectSoundOut waveOut = new NAudio.Wave.DirectSoundOut();

            NAudio.Wave.WaveFileReader wfr  = new NAudio.Wave.WaveFileReader(file);
            NAudio.Wave.WaveOut        wOut = new NAudio.Wave.WaveOut();
            wOut.DeviceNumber = 0;
            wOut.Init(wfr);
            wOut.Play();

            waveOut.Init(wfr);

            waveOut.Play();
        }
Exemplo n.º 36
0
        // セリフ音声の再生
        private async void Speach(string s)
        {
            NAudio.Wave.WaveOut player;

            player = new NAudio.Wave.WaveOut();
            byte[] buffer = (byte[])Properties.Resources.ResourceManager.GetObject(s);
            using var stream     = new MemoryStream(buffer);
            using WaveStream pcm = new Mp3FileReader(stream);
            player.Init(pcm);
            player.Play();
            while (player.PlaybackState == PlaybackState.Playing)
            {
                await Task.Delay(10);
            }
            player.Dispose();
        }
Exemplo n.º 37
0
            public void ChangeDevice()
            {
                var state           = _waveOut.PlaybackState;
                var latency         = _waveOut.DesiredLatency;
                var numberOfBuffers = _waveOut.NumberOfBuffers;
                var waveFormat      = _waveOut.OutputWaveFormat;
                var volume          = _waveOut.Volume;

                _waveOut.Dispose();
                _waveOut = new WaveOut();
                _waveOut.DeviceNumber = SelectedDevice;
                _waveOut.Init(_provider);

                switch (state)
                {
                case PlaybackState.Paused: Pause(); break;

                case PlaybackState.Playing: Play(); break;
                }
            }
Exemplo n.º 38
0
        public static String playSound(int deviceNumber, String audioPatch, EventHandler Stopped_Event = null)
        {
            disposeWave();

            try
            {
                if (audioPatch.EndsWith(".mp3"))
                {
                    NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(audioPatch));
                    stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
                }
                else if (audioPatch.EndsWith(".wav"))
                {
                    NAudio.Wave.WaveChannel32 pcm = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(audioPatch));
                    stream            = new NAudio.Wave.BlockAlignReductionStream(pcm);
                    pcm.PadWithZeroes = false;
                }
                else
                {
                    return("Not a valid audio file");
                }

                output = new NAudio.Wave.WaveOut();
                output.DeviceNumber = deviceNumber;
                output.Init(stream);
                output.Play();

                if (Stopped_Event != null)
                {
                    output.PlaybackStopped += new EventHandler <StoppedEventArgs>(Stopped_Event);
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }

            return("true");
        }
Exemplo n.º 39
0
        public void LoadFile(string filePath)
        {
            DisposeWave();
            pausePlay = true;

            if (filePath.EndsWith(".mp3"))
            {
                NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(filePath));
                stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
            }
            else if (filePath.EndsWith(".wav"))
            {
                NAudio.Wave.WaveStream pcm = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(filePath));
                stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
            }
            else
            {
                throw new InvalidOperationException("oh my god just put in the right file type you twat");
            }

            output = new NAudio.Wave.WaveOut();
            output.DeviceNumber = comboBox2.SelectedIndex;

            textBox2.Text = comboBox2.GetItemText(comboBox2.SelectedItem);

            var audioFileReader = new AudioFileReader(filePath);

            string min = Convert.ToInt32(audioFileReader.TotalTime.TotalMinutes).ToString();
            string sec = Convert.ToInt32(audioFileReader.TotalTime.TotalSeconds % 60).ToString();
            string mil = Convert.ToInt32(audioFileReader.TotalTime.TotalMilliseconds % 1000).ToString();

            if (min.Length < 2)
            {
                min = "0" + min;
            }
            if (sec.Length < 2)
            {
                sec = "0" + sec;
            }
            if (mil.Length < 2)
            {
                mil = "00" + mil;
            }
            else if (mil.Length < 3)
            {
                mil = "0" + mil;
            }

            textBox9.Text = "Total " + min + ":" + sec + ":" + mil;

            audioFileReader.Volume = vol2.Volume;
            output.Init(audioFileReader);
            Stopwatch time = new Stopwatch();

            time.Start();
            stopwatches.Add(time, "time");

            totalMil = Convert.ToInt64(audioFileReader.TotalTime.TotalMilliseconds);

            output.Play();

            if (comboBox1.SelectedIndex != comboBox2.SelectedIndex)
            {
                if (filePath.EndsWith(".mp3"))
                {
                    NAudio.Wave.WaveStream pcm2 = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(filePath));
                    stream2 = new NAudio.Wave.BlockAlignReductionStream(pcm2);
                }
                else if (filePath.EndsWith(".wav"))
                {
                    NAudio.Wave.WaveStream pcm2 = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(filePath));
                    stream2 = new NAudio.Wave.BlockAlignReductionStream(pcm2);
                }
                else
                {
                    throw new InvalidOperationException("Not a compatabible audio file type.");
                }

                outputLocal = new NAudio.Wave.WaveOut();
                outputLocal.DeviceNumber = comboBox1.SelectedIndex;

                textBox4.Text = comboBox1.GetItemText(comboBox1.SelectedItem);

                var audioFileReader2 = new AudioFileReader(filePath);
                audioFileReader2.Volume = volumeSlider1.Volume;
                outputLocal.Init(audioFileReader2);
                outputLocal.Play();

                //float a = volumeSlider1.Volume;
                //outputLocal.Volume = a;
                //outputLocal.Init(stream2);
                //outputLocal.Play();
            }
        }
Exemplo n.º 40
0
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string         outputFileName = "";
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter      = "Wave File (*.wav) | *.wav|MP3 Files (*.mp3) | *.mp3|All Files (*.*) | *.*";
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                outputFileName = openFileDialog.FileName;
            }
            else
            {
                return;
            }
            if (openFileDialog.FileName.Contains(".mp3"))
            {
                outputFileName = outputFileName.Substring(0, outputFileName.Length - 3) + "wav";
                Mp3ToWav(openFileDialog.FileName, outputFileName);
            }

            //OpenFileDialog open = new OpenFileDialog();
            //open.Filter = "Wave File (*.wav) | *.wav";
            //if (open.ShowDialog() != DialogResult.OK) return;

            waveViewer1.WaveStream = new NAudio.Wave.WaveFileReader(outputFileName);
            waveViewer1.GetTotal   = true;
            waveViewer1.Refresh();

            var datalow  = waveViewer1.Datax;
            var datahigh = waveViewer1.Datay;
            //take the data and look for patterns in the frame of 8 secs
            var peaks  = detectpeak(200, datahigh, true);
            var trough = detectpeak(200, datahigh, false);

            peaks              = filterpeak(20, peaks);
            trough             = filterpeak(20, trough);
            waveViewer1.peaks  = peaks;
            waveViewer1.trough = trough;

            double[][] highamp = new double[peaks.Count][];
            for (int a = 0; a < peaks.Count - 1; a++)
            {
                highamp[a]    = new double[2];
                highamp[a][0] = peaks[a + 1] - peaks[a];
                highamp[a][1] = datahigh[peaks[a]];
            }
            highamp[peaks.Count - 1]    = new double[2];
            highamp[peaks.Count - 1][0] = 0; highamp[peaks.Count - 1][1] = 0;
            double[][] lowamp = new double[trough.Count][];
            for (int a = 0; a < trough.Count - 1; a++)
            {
                lowamp[a]    = new double[2];
                lowamp[a][0] = trough[a + 1] - trough[a];
                lowamp[a][1] = datahigh[trough[a]];
            }
            lowamp[trough.Count - 1]    = new double[2];
            lowamp[trough.Count - 1][0] = 0; lowamp[trough.Count - 1][1] = 0;
            //cluster both

            Accord.MachineLearning.KMeans gm  = new Accord.MachineLearning.KMeans(5);
            Accord.MachineLearning.KMeans gml = new Accord.MachineLearning.KMeans(5);
            var ans  = gm.Compute(highamp);
            var lans = gml.Compute(lowamp);

            var fclus = filtercluster(ans, peaks);

            cluspos = MixerControls.ToDict(fclus);
            var flans = filtercluster(lans, trough);//ignore bot

            waveViewer1.peakclus   = ans;
            waveViewer1.troughclus = lans;

            IWavePlayer play;

            play  = new NAudio.Wave.WaveOut();
            audio = new AudioFileReader(outputFileName);
            play.Init(audio);
            play.Play();
            Application.Idle += Application_Idle;
            timer1.Interval   = 20;
            timer1.Enabled    = true;
            timer1.Start();
            Rectangle workingArea = Screen.GetWorkingArea(this);

            this.Location = new Point(workingArea.Right - Size.Width - 20,
                                      workingArea.Bottom - Size.Height - 20);
            //this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.TopMost = true;
            this.Opacity = .8;
            openToolStripMenuItem.Visible = false;
            menuStrip1.Visible            = false;
            this.pictureBox1.Image        = Image.FromFile("D:\\AllVSProject232015\\AudioMix\\AudioMix\\Hypnoctivity-Logo.png");
        }
Exemplo n.º 41
-1
        static void Main(string[] args)
        {
            string mp3FilesDir = Directory.GetCurrentDirectory();

            if (args.Length > 0)
            {
                mp3FilesDir = args.First();
            }

            var waveOutDevice = new WaveOut();

            var idToFile = Directory.GetFiles(mp3FilesDir, "*.mp3", SearchOption.AllDirectories).ToDictionary(k => int.Parse(Regex.Match(Path.GetFileName(k), @"^\d+").Value));
            while (true)
            {
                Console.WriteLine("Wprowadz numer nagrania");
                var trackId = int.Parse(Console.ReadLine());

                using (var audioFileReader = new AudioFileReader(idToFile[trackId]))
                {
                    waveOutDevice.Init(audioFileReader);
                    waveOutDevice.Play();

                    Console.ReadLine();
                }
            }
            
        }