示例#1
0
 private void ProximaMusica()
 {
     try
     {
         if (output != null)
         {
             output.Stop();
         }
         if (musicatoc == TreeMostra.Nodes.Count - 1)
         {
             musicatoc = 0;
         }
         else
         {
             musicatoc++;
         }
         NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(TreeMostra.Nodes[musicatoc].Text));//TreeMostra.SelectedNode.Text
         stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
         output = new NAudio.Wave.DirectSoundOut();
         output.Init(stream);
         output.Play();
         BtnPause.Enabled     = true;
         BtnPlaySelec.Enabled = false;
         BtnStop.Enabled      = true;
         BtnProximo.Enabled   = true;
     }
     catch
     {
         MessageBox.Show("Você tem que selecionar uma música primeiro para depois tocar a proxima ");
     }
 }
示例#2
0
        private void BtnNext_Click(object sender, EventArgs e)
        {
            if (output == null)
            {
                MessageBox.Show("No more songs in playlist.", "Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (ListBox.SelectedIndex != ListBox.Items.Count - 1)
            {
                //counter for get selected index in listbox
                int count = 0;
                ListBox.SetSelected(count + 1, true);

                int nextIndex = ListBox.SelectedIndex + 1;
                DisposeWave();

                OpenFileDialog forwardSong = new OpenFileDialog();
                //getting the string of the next song
                string nextSong            = ListBox.Items[nextIndex].ToString();
                NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(forwardSong.FileName));
                stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
                output = new NAudio.Wave.DirectSoundOut();
                output.Init(stream);

                LblTest.Text       = path[0];
                LblNowPlaying.Text = files[0];

                //play output
                output.Play();
            }
        }
示例#3
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);
                            }
                        }
                    }
                }
            });
        }
示例#4
0
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            DisposeWave();
            string query1 = "Select Track.track_path from Track where Track_name = '" + listBox1.SelectedItem.ToString() + "'";


            SqlCommand cmd1 = new SqlCommand(query1, con);


            SqlDataReader dbr1;


            dbr1 = cmd1.ExecuteReader();
            string sname = null;

            while (dbr1.Read())

            {
                sname = (string)dbr1["track_path"];;  // is coming from database
            }
            dbr1.Close();

            pcm    = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(sname));
            stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
            output = new NAudio.Wave.DirectSoundOut();
            output.Init(stream);
            output.Play();
        }
        public void CanRepositionToNonBlockAlignedPositions()
        {
            BlockAlignedWaveStream inputStream = new BlockAlignedWaveStream(726, 80000);
            BlockAlignReductionStream blockStream = new BlockAlignReductionStream(inputStream);


            byte[] inputBuffer = new byte[1024];
            int read = blockStream.Read(inputBuffer, 0, 1024);
            Assert.AreEqual(1024, read, "bytes read 1");
            Assert.AreEqual(blockStream.Position, 1024);
            CheckReadBuffer(inputBuffer, 1024, 0);

            read = blockStream.Read(inputBuffer, 0, 1024);
            Assert.AreEqual(1024, read, "bytes read 2");
            Assert.AreEqual(2048, blockStream.Position, "position 2");
            CheckReadBuffer(inputBuffer, 1024, 1024);


            // can reposition correctly
            blockStream.Position = 1000;
            read = blockStream.Read(inputBuffer, 0, 1024);
            Assert.AreEqual(1024, read, "bytes read 3");
            Assert.AreEqual(2024, blockStream.Position, "position 3");
            CheckReadBuffer(inputBuffer, 1024, 1000);
            
        }
 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();
 }
 public void CanCreateBlockAlignmentReductionStream()
 {
     BlockAlignedWaveStream inputStream = new BlockAlignedWaveStream(726, 80000);
     BlockAlignReductionStream blockStream = new BlockAlignReductionStream(inputStream);
     Assert.AreEqual(726, inputStream.BlockAlign);
     Assert.AreEqual(2, blockStream.BlockAlign);
 }
示例#8
0
        private void Aleatorio()
        {
            int i = 0;

            for (i = 0; i < TreeMostra.Nodes.Count; i++)
            {
                //Só pra contar quantos nodes tem para pegar o index dele e fazer o aleatorio
            }
            Random rdn = new Random();
            int    strNumeroaleatorio;

            strNumeroaleatorio = rdn.Next(0, i - 1);// gera  o numero aleatorio de 0 até o tamanho do treeview

            if (output != null)
            {
                output.Stop();
            }
            NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(TreeMostra.Nodes[strNumeroaleatorio].Text));//TreeMostra.SelectedNode.Text
            stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
            output = new NAudio.Wave.DirectSoundOut();
            output.Init(stream);
            output.Play();
            BtnPause.Enabled     = true;
            BtnPlaySelec.Enabled = false;
            BtnStop.Enabled      = true;
            BtnProximo.Enabled   = true;
        }
示例#9
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);
            }
        }
示例#10
0
文件: Music.cs 项目: eihi/Barricade
 public Music(string path)
 {
     DisposeMusic();
     WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(path));
     stream = new BlockAlignReductionStream(pcm);
     output = new DirectSoundOut();
     output.Init(stream);
 }
示例#11
0
 private void DisposeWave()
 {
     if (stream != null)
     {
         stream.Dispose();
         stream = null;
     }
 }
示例#12
0
 private static WaveChannel32 OpenMp3Stream(string fileName)
 {
     WaveChannel32 inputStream;
     WaveStream mp3Reader = new Mp3FileReader(fileName);
     WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(mp3Reader);
     WaveStream blockAlignedStream = new BlockAlignReductionStream(pcmStream);
     inputStream = new WaveChannel32(blockAlignedStream);
     return inputStream;
 }
示例#13
0
 public Mp3Player(string fileName)
 {
     this._fileName = fileName;
     this._pcm      = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(this._fileName));
     this._stream   = new NAudio.Wave.BlockAlignReductionStream(_pcm);
     this._output   = new NAudio.Wave.WaveOutEvent();
     this._output.Init(this._stream);
     this._time = Convert.ToInt32(this._stream.TotalTime.TotalSeconds);
 }
示例#14
0
 public WaveStream CreateWaveStream(string fileName)
 {
     WaveStream readerStream = new WaveFileReader(fileName);
     if (readerStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm && readerStream.WaveFormat.Encoding != WaveFormatEncoding.IeeeFloat)
     {
         readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream);
         readerStream = new BlockAlignReductionStream(readerStream);
     }
     return readerStream;
 }
示例#15
0
 private static WaveStream OpenWavStream(string fileName)
 {
     WaveStream readerStream = new WaveFileReader(fileName);
     if (readerStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm)
     {
         readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream);
         readerStream = new BlockAlignReductionStream(readerStream);
     }
     return readerStream;
 }
示例#16
0
        public void playSound(string file)
        {
            NAudio.Wave.WaveStream    pcm    = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(file));
            BlockAlignReductionStream stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
            DirectSoundOut            output = new NAudio.Wave.DirectSoundOut();

            output.Init(stream);
            output.Play();
            Thread.Sleep(((int)new AudioFileReader(file).TotalTime.TotalMilliseconds) + soundDelay);
        }
示例#17
0
        public static void PreviousChannelWhoosh()
        {
            _wave = WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(@"..\..\Resources\Sounds\woosh_prev.mp3"));

            _stream = new BlockAlignReductionStream(_wave);

            _output = new DirectSoundOut();
            _output.Init(_stream);
            _output.Play();
        }
示例#18
0
        private void BtnOpenFiles_Click(object sender, EventArgs e)
        {
            //make sure listbox is visible to the user
            ListBox.Visible = true;

            //when open file loads set login page to not visible
            LblUsernameLogin.Visible = false;
            LblPasswordLogin.Visible = false;
            TxtUsername.Visible      = false;
            TxtPassword.Visible      = false;
            CBoxSavePassword.Visible = false;
            BtnLoginUserPass.Visible = false;
            BtnLogin.Text            = "Login";


            OpenFileDialog songChoice = new OpenFileDialog();

            //filter only mp3 filetypes in files
            songChoice.Filter = "Mp3 File(*.mp3)|*.mp3";

            //select more than one track
            songChoice.Multiselect = true;

            if (songChoice.ShowDialog() == DialogResult.OK)
            {
                files = songChoice.SafeFileNames;
                path  = songChoice.FileNames;

                //adding items to list
                for (int index = 0; index < files.Length; index++)
                {
                    ListBox.Items.Add(files[index]);
                }

                //highlights current song playing
                ListBox.SetSelected(0, true);

                //dispose function to get rid of the current song in WaveStream NAudio
                DisposeWave();

                NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(songChoice.FileName));
                stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
                output = new NAudio.Wave.DirectSoundOut();
                output.Init(stream);

                LblTest.Text       = path[0];
                LblNowPlaying.Text = files[0];
                //play song
                output.Play();

                //hide the play button
                BtnPlay.Visible  = false;
                BtnPause.Visible = true;
            }
        }
示例#19
0
        public void Read(string filepath)
        {
            DisposeWave();

            stream = new BlockAlignReductionStream(
                WaveFormatConversionStream.CreatePcmStream(
                    new Mp3FileReader(filepath)));
            sample_rate = stream.WaveFormat.SampleRate;
            data        = new byte[stream.Length];
            stream.Read(data, 0, (int)stream.Length);
        }
示例#20
0
 private void DisposeWave()
 {
     if (SoundOut != null)
     {
         if (SoundOut.PlaybackState == NAudio.Wave.PlaybackState.Playing) SoundOut.Stop();
         SoundOut.Dispose();
         SoundOut = null;
     }
     if (BlockStream != null)
     {
         BlockStream.Dispose();
         BlockStream = null;
     }
 }
示例#21
0
        private static WaveStream CreateInputStream(string fileName)
        {
            WaveChannel32 inputStream;
            WaveStream readerStream = null;

            if (fileName.EndsWith(".wav"))
            {
                readerStream = new WaveFileReader(fileName);
            }
            //else if (fileName.EndsWith(".wma"))
            //{
            //    //                readerStream = new WMAFileReader2(fileName);

            //    MemoryStream memoryStream = new MemoryStream();
            //    using (FileStream infile = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            //    {
            //        while (infile.Position < infile.Length)
            //        {
            //            byte data = (byte)infile.ReadByte();
            //            memoryStream.WriteByte(data);
            //        }
            //    }
            //    memoryStream.Position = 0;
            //    readerStream = new WMAFileReader2(memoryStream);
            //}
            else
            {
                throw new InvalidOperationException("Unsupported extension");
            }

            // Provide PCM conversion if needed
            if (readerStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm)
            {
                readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream);
                readerStream = new BlockAlignReductionStream(readerStream);
            }

            // Provide conversion to 16 bits if needed
            if (readerStream.WaveFormat.BitsPerSample != 16)
            {
                var format = new WaveFormat(readerStream.WaveFormat.SampleRate,
                16, readerStream.WaveFormat.Channels);
                readerStream = new WaveFormatConversionStream(format, readerStream);
            }

            inputStream = new WaveChannel32(readerStream);

            return inputStream;
        }
示例#22
0
        private void DJDemo_Load(object sender, EventArgs e)
        {
            volume = 0.0f;

            sensors = new DistanceSensors();
            sensors.DistancesChanged += new DistanceSensors.DistancesChangedHandler(sensors_DistancesChanged);
            sensors.Connect();

            song = new Mp3FileReader("sounds/gangam style.mp3");
            wavStream = WaveFormatConversionStream.CreatePcmStream(song);
            baStream = new BlockAlignReductionStream(wavStream);
            music = new WaveOut(WaveCallbackInfo.FunctionCallback());
            music.Init(baStream);
            music.Volume = 0;
        }
		public void SoundOutput(string header, bool IsWin8)
		{
			/**
			 * 
			 * 출력할 소리가 wav인지 mp3인지 비프음인지 채크합니다.
			 * windows8 이상의 경우에는 비프음보다 윈도우8 기본 알림음이 더 알맞다고 생각하기에 IsWin8이 True면 아무 소리도 내보내지 않습니다.
			 * 
			**/

			DisposeWave();//알림이 동시에 여러개가 울릴 경우 소리가 겹치는 문제를 방지

			try
			{

				var Audiofile = GetRandomSound(header);

				if (!IsWin8 && Audiofile == null)
				{
					SystemSounds.Beep.Play();		//FileCheck에서 음소거 채크를 하고 음소거상태이거나 파일이 없는경우 비프음 출력
					return;
				}
				else if (IsWin8 && Audiofile == null)
					return;							//위와 동일한 조건이지만 윈도우8인경우는 이 소스에서는 아무 소리도 내보내지않음.

				float Volume = Settings.Current.CustomSoundVolume > 0 ? (float)Settings.Current.CustomSoundVolume / 100 : 0;

				if (Path.GetExtension(Audiofile).ToLower() == ".wav")
				{
					WaveStream pcm = new WaveChannel32(new WaveFileReader(Audiofile), Volume, 0);
					BlockStream = new BlockAlignReductionStream(pcm);
				}
				else if (Path.GetExtension(Audiofile).ToLower() == ".mp3")
				{
					WaveStream pcm = new WaveChannel32(new Mp3FileReader(Audiofile), Volume, 0);
					BlockStream = new BlockAlignReductionStream(pcm);
				}
				else
					return;

				SoundOut = new DirectSoundOut();
				SoundOut.Init(BlockStream);
				SoundOut.Play();
			}
			catch (Exception ex)
			{
				StatusService.Current.Notify("Unable to play sound notification: " + ex.Message);
			}
		}
        public void CanReadNonBlockAlignedLengths()
        {
            BlockAlignedWaveStream inputStream = new BlockAlignedWaveStream(726, 80000);
            BlockAlignReductionStream blockStream = new BlockAlignReductionStream(inputStream);

            byte[] inputBuffer = new byte[1024];
            int read = blockStream.Read(inputBuffer, 0, 1024);
            Assert.AreEqual(1024, read, "bytes read 1");
            Assert.AreEqual(blockStream.Position, 1024);
            CheckReadBuffer(inputBuffer, 1024, 0);

            read = blockStream.Read(inputBuffer, 0, 1024);
            Assert.AreEqual(1024, read, "bytes read 2");
            Assert.AreEqual(2048, blockStream.Position, "position 2");
            CheckReadBuffer(inputBuffer, 1024, 1024);
        }
示例#25
0
 public static void disposeWave()
 {
     if (output != null)
     {
         if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
         {
             output.Stop();
         }
         output.Dispose();
     }
     if (stream != null)
     {
         stream.Dispose();
         stream = null;
     }
 }
示例#26
0
 //Function to dispose the current mp3 file
 private void DisposeWave()
 {
     if (output != null)
     {
         if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
         {
             output.Dispose();
             output.Stop();
         }
         if (stream != null)
         {
             stream.Dispose();
             stream = null;
         }
     }
 }
示例#27
0
        public MusicCharacteristics AnalyzeFileMP3(Stream file)
        {
            var bbuffer = new byte[AnalyzeFrameSize];

            using (var reader = new Mp3FileReader(file))
            {
                using (WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(reader))
                {
                    using (WaveStream aligned = new BlockAlignReductionStream(pcm))
                    {
                        Console.WriteLine(aligned.WaveFormat);
                        Console.WriteLine(aligned.Read(bbuffer, 0, AnalyzeFrameSize));
                    }
                }
            }
            return new MusicCharacteristics();
        }
示例#28
0
文件: SpeechLib.cs 项目: radtek/DCEC
 public void MP3CloseFile()
 {
     if (output != null)
     {
         if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
         {
             output.Stop();
         }
         output.Dispose();
         output = null;
     }
     if (stream != null)
     {
         stream.Dispose();
         stream = null;
     }
 }
示例#29
0
文件: Music.cs 项目: eihi/Barricade
 // gebruikte resources opruimen
 public void DisposeMusic()
 {
     if (output != null)
     {
         if (output.PlaybackState == PlaybackState.Playing)
         {
             output.Stop();
         }
         output.Dispose();
         output = null;
     }
     if (stream != null)
     {
         stream.Dispose();
         stream = null;
     }
 }
示例#30
0
        public void PlayMp3FromUrl(string url)
        {
            //stop the song that is currently playing
            if ( this.playback != null) this.StopPlayback();

            new Thread(delegate(object o)
            {
                var response = WebRequest.Create(url).GetResponse();
                using (var stream = response.GetResponseStream())
                {
                    byte[] buffer = new byte[65536]; // 64KB chunks
                    int read;
                    while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        var pos = ms.Position;
                        ms.Position = ms.Length;
                        ms.Write(buffer, 0, read);
                        ms.Position = pos;
                    }
                }
            }).Start();

            // Pre-buffering some data to allow NAudio to start playing
            while (ms.Length < 65536 * 10)
                Thread.Sleep(1000);

            ms.Position = 0;
            using (WaveStream blockAlignedStream = new BlockAlignReductionStream(WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(ms))))
            {
                using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
                {
                    waveOut.Init(blockAlignedStream);
                    waveOut.Play();

                    //set currently playing song
                    Properties.Settings.Default.Playback = waveOut;

                    while (waveOut.PlaybackState == PlaybackState.Playing)
                    {
                        System.Threading.Thread.Sleep(10);
                        Application.DoEvents();
                    }
                }
            }
        }
示例#31
0
 private void bwMp3Player_DoWork(object sender, DoWorkEventArgs e)
 {
     using (WaveStream blockAlignedStream =
         new BlockAlignReductionStream(
             WaveFormatConversionStream.CreatePcmStream(
                 new Mp3FileReader(mp3FileName))))
     {
         using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
         {
             waveOut.Init(blockAlignedStream);
             waveOut.Play();
             while (waveOut.PlaybackState == PlaybackState.Playing)
             {
                 System.Threading.Thread.Sleep(100);
             }
         }
     }
 }
示例#32
0
 private static WaveChannel32 OpenWavStream(string fileName)
 {
     WaveChannel32 inputStream;
     WaveStream readerStream = new WaveFileReader(fileName);
     if (readerStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm)
     {
         readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream);
         readerStream = new BlockAlignReductionStream(readerStream);
     }
     if (readerStream.WaveFormat.BitsPerSample != 16)
     {
         var format = new WaveFormat(readerStream.WaveFormat.SampleRate,
             16, readerStream.WaveFormat.Channels);
         readerStream = new WaveFormatConversionStream(format, readerStream);
     }
     inputStream = new WaveChannel32(readerStream);
     return inputStream;
 }
示例#33
0
        private void setButtons(object sender, EventArgs e)
        {
            if (isPlaying == true)
            {
                output.Stop();
            }
            string     s   = (sender as Button).Text;
            WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(songsAdded[findClickedSong(s)].path));

            stream = new BlockAlignReductionStream(pcm);
            output = new DirectSoundOut();
            output.Init(stream);
            output.Play();
            if (!isPlaying)
            {
                isPlaying = true;
            }
        }
示例#34
0
 public IWaveProvider Load(string fileName)
 {
     WaveStream readerStream = null;
     if (fileName.EndsWith(".wav", StringComparison.OrdinalIgnoreCase)){
         readerStream = new WaveFileReader(fileName);
         if (readerStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm && readerStream.WaveFormat.Encoding != WaveFormatEncoding.IeeeFloat)
         {
             readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream);
             readerStream = new BlockAlignReductionStream(readerStream);
         }
     }else if (fileName.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase)){
         readerStream = new Mp3FileReader(fileName);
     }else if (fileName.EndsWith(".aiff")){
         readerStream = new AiffFileReader(fileName);
     }else{
         readerStream = new MediaFoundationReader(fileName);
     }
     return readerStream;
 }
示例#35
0
        public void DisposeWave()
        {
            try
            {
                if (output != null)
                {
                    if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
                    {
                        output.Stop();
                        output.Dispose();
                        output = null;
                    }
                }

                if (stream != null)
                {
                    stream.Dispose();
                    stream = null;
                }

                if (outputLocal != null)
                {
                    if (outputLocal.PlaybackState == NAudio.Wave.PlaybackState.Playing)
                    {
                        outputLocal.Stop();
                        outputLocal.Dispose();
                        outputLocal = null;
                    }
                }

                if (stream2 != null)
                {
                    stream2.Dispose();
                    stream2 = null;
                }
            }

            catch (NAudio.MmException)
            {
                throw;
            }
        }
示例#36
0
        public void SoundOutput(string header, bool IsWin8)
        {
            try
            {
                DisposeWave();//알림이 동시에 여러개가 울릴 경우 소리가 겹치는 문제를 방지
                if (!Directory.Exists(Path.Combine(Main_folder, "Sounds")))
                    Directory.CreateDirectory(Path.Combine(Main_folder, "Sounds"));
                List<string> FileList = Directory.GetFiles(Path.Combine(Main_folder, "Sounds"), "*.wav", SearchOption.AllDirectories)
                    .Concat(Directory.GetFiles(Path.Combine(Main_folder, "Sounds"), "*.mp3", SearchOption.AllDirectories)).ToList();//mp3와 wav를 검색하여 추가
                string Audiofile = string.Empty;
                if (FileList.Count > 0)
                {
                    Random Rnd = new Random();
                    Audiofile = FileList[Rnd.Next(0, FileList.Count)];

                    float Volume = AppSettings.Default.CustomSoundVolume > 0 ? (float)AppSettings.Default.CustomSoundVolume / 100 : 0;
                    if (Path.GetExtension(Audiofile).ToLower() == ".wav")//wav인지 채크
                    {
                        WaveStream pcm = new WaveChannel32(new WaveFileReader(Audiofile), Volume, 0);
                        BlockStream = new BlockAlignReductionStream(pcm);
                    }
                    else if (Path.GetExtension(Audiofile).ToLower() == ".mp3")//mp3인 경우
                    {
                        WaveStream pcm = new WaveChannel32(new Mp3FileReader(Audiofile), Volume, 0);
                        BlockStream = new BlockAlignReductionStream(pcm);
                    }
                    SoundOut = new DirectSoundOut();
                    SoundOut.Init(BlockStream);
                    SoundOut.Play();
                }
                else
                {
                    System.Media.SystemSounds.Beep.Play();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
                System.Media.SystemSounds.Beep.Play();
            }
        }
示例#37
0
 public void SoundOutput(string header, bool IsWin8)
 {
     try
     {
         /**
      *
      * 출력할 소리가 wav인지 mp3인지 비프음인지 채크합니다.
      * windows8 이상의 경우에는 비프음보다 윈도우8 기본 알림음이 더 알맞다고 생각하기에 IsWin8이 True면 아무 소리도 내보내지 않습니다.
      *
     **/
         DisposeWave();//알림이 동시에 여러개가 울릴 경우 소리가 겹치는 문제를 방지
         string Audiofile = FileCheck(header);
         if (string.IsNullOrEmpty(Audiofile) && !IsWin8)
         {
             System.Media.SystemSounds.Beep.Play();
         }
         else if (!string.IsNullOrEmpty(Audiofile))
         {
             float Volume = Settings.Current.CustomSoundVolume > 0 ? (float)Settings.Current.CustomSoundVolume / 100 : 0;
             if (Path.GetExtension(Audiofile).ToLower() == ".wav")//wav인지 채크
             {
                 WaveStream pcm = new WaveChannel32(new WaveFileReader(Audiofile), Volume, 0);
                 BlockStream = new BlockAlignReductionStream(pcm);
             }
             else if (Path.GetExtension(Audiofile).ToLower() == ".mp3")//mp3인 경우
             {
                 WaveStream pcm = new WaveChannel32(new Mp3FileReader(Audiofile), Volume, 0);
                 BlockStream = new BlockAlignReductionStream(pcm);
             }
             SoundOut = new DirectSoundOut();
             SoundOut.Init(BlockStream);
             SoundOut.Play();
         }
     }
     catch(Exception ex)
     {
         System.Diagnostics.Debug.WriteLine(ex);
         KanColleClient.Current.CatchedErrorLogWriter.ReportException(ex.Source, ex);
         System.Media.SystemSounds.Beep.Play();
     }
 }
示例#38
0
 private void PlayMusicaSelected()
 {
     try
     {// ve a musica selecionada e pega o index dela que automaticamente é a posiçao dela na lista e toca ela.
         NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(TreeMostra.SelectedNode.Text));
         stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
         output = new NAudio.Wave.DirectSoundOut();
         output.Init(stream);
         output.Play();
         BtnPause.Enabled     = true;
         BtnPlaySelec.Enabled = false;
         BtnStop.Enabled      = true;
         BtnAleatório.Enabled = true;
         BtnProximo.Enabled   = true;
         musicatoc            = TreeMostra.SelectedNode.Index;
     }
     catch
     {
         MessageBox.Show("Não tem nenhuma música selecionada");
     }
 }
示例#39
0
 /// <summary>
 /// Releases unmanaged and - optionally - managed resources.
 /// </summary>
 /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
 protected virtual void Dispose(bool disposing)
 {
     if (!_disposed)
     {
         if (disposing)
         {
             if (output != null)
             {
                 output.Stop();
                 output.Dispose();
                 output = null;
             }
             if (reduce != null)
             {
                 reduce.Dispose();
                 reduce = null;
             }
         }
         _disposed = true;
     }
 }
        public void AddSound(string FileName)
        {
            FileInfo file = new FileInfo (Path.Combine(Environment.CurrentDirectory,
                Path.Combine(this.context.Configuration[EngineConfigurationName.SoundsRoot], FileName)));

            if(!file.Exists)
                return;

            WaveStream readerstream = new WaveFileReader (file.FullName);

            readerstream = new BlockAlignReductionStream (readerstream);

            if(readerstream.WaveFormat.Encoding != WaveFormatEncoding.Pcm)
            {
                readerstream = WaveFormatConversionStream.CreatePcmStream (readerstream);
            }

            if(readerstream.WaveFormat.BitsPerSample != 16)
            {
                var format = new WaveFormat (readerstream.WaveFormat.SampleRate, 16,
                    readerstream.WaveFormat.Channels);

                readerstream = new WaveFormatConversionStream (format, readerstream);
            }

            byte[] data = new byte[readerstream.Length];

            int position = 0;
            while(true)
            {
                int result = readerstream.ReadByte ();
                if(result == -1)
                    break;

                data[position] = Convert.ToByte (result);
                position++;
            }

            this.AddSound (file.Name, new AudioSource(data, (uint)readerstream.WaveFormat.SampleRate, 1.0f, readerstream.WaveFormat.Channels));
        }
示例#41
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");
        }
示例#42
0
        public void loopMp3()
        {
            try
            {
                using (var ms = File.OpenRead(playerSong))
                using (var rdr = new Mp3FileReader(ms))
                using (var wavStream = WaveFormatConversionStream.CreatePcmStream(rdr))
                using (var baStream = new BlockAlignReductionStream(wavStream))
                using (var waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
                {
                    //rdr.Skip();
                    wavStream.Skip(playerPreviewTime);
                    waveOut.Init(baStream);
                    waveOut.Play();
                    while (waveOut.PlaybackState == PlaybackState.Playing && !closing)
                    {
                        Thread.Sleep(10);

                    }
                }
            }
            catch (Exception) { }
        }
示例#43
0
文件: SpeechLib.cs 项目: radtek/DCEC
 public void MP3PlayFile(string fileName)
 {
     this.fileName = fileName;
     if (fileName.EndsWith(".mp3"))
     {
         NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(fileName));
         stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
     }
     else if (fileName.EndsWith(".wav"))
     {
         NAudio.Wave.WaveStream pcm = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(fileName));
         stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
     }
     else
     {
         throw new InvalidOperationException("Not a correct audio file type.");
     }
     output = new NAudio.Wave.DirectSoundOut();
     //output = new WaveOut();
     output.Init(stream);
     output.Play();
     //output.Volume = 1.0f;
 }
示例#44
0
        public void PlayMp3FromUrl(string url)
        {
            using (Stream ms = new MemoryStream())
            {
                using (Stream stream = WebRequest.Create(url)
                    .GetResponse().GetResponseStream())
                {
                    byte[] buffer = new byte[32768];
                    int read;
                    while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ms.Write(buffer, 0, read);
                    }
                }

                ms.Position = 0;
                using (WaveStream blockAlignedStream =
                    new BlockAlignReductionStream(
                        WaveFormatConversionStream.CreatePcmStream(
                            new Mp3FileReader(ms))))
                {
                    using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
                    {
                        waveOut.Init(blockAlignedStream);
                        waveOut.PlaybackStopped += (sender, e) =>
                        {
                            waveOut.Stop();
                        };

                        waveOut.Play();
                        waiting = true;
                        stop.WaitOne(TimeWait);
                        waiting = false;
                    }
                }
            }
        }
        private static WaveStream CreateInputStream(string fileName)
        {
            WaveChannel32 inputStream;
            WaveStream readerStream = null;

            if (fileName.EndsWith(".wav"))
            {
                readerStream = new WaveFileReader(fileName);
            }
            else if (fileName.EndsWith(".flac"))
            {
                readerStream = new FLACFileReader(fileName);
            }
            else
            {
                throw new InvalidOperationException("Unsupported extension");
            }

            // Provide PCM conversion if needed
            if (readerStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm)
            {
                readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream);
                readerStream = new BlockAlignReductionStream(readerStream);
            }

            // Provide conversion to 16 bits if needed
            if (readerStream.WaveFormat.BitsPerSample != 16)
            {
                var format = new WaveFormat(readerStream.WaveFormat.SampleRate,
                16, readerStream.WaveFormat.Channels);
                readerStream = new WaveFormatConversionStream(format, readerStream);
            }

            inputStream = new WaveChannel32(readerStream);

            return inputStream;
        }
示例#46
0
 /// <summary>
 /// Stops play back and relise all resorces.
 /// </summary>
 public void stop()
 {
     try
     {
         if (output != null)
         {
             if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
             {
                 output.Stop();
             }
             output.Dispose();
             output = null;
         }
         if (stream != null)
         {
             stream.Dispose();
             stream = null;
         }
     }
     catch (Exception)
     {
         stream = null;
     }
 }
示例#47
0
        private void PlayMp3(string url)
        {
            try
            {
                Stream ms = new MemoryStream();
                // 设置参数
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                //发送请求并获取相应回应数据
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                Stream responseStream = response.GetResponseStream();
                byte[] buffer = new byte[1024];
                int size = 0;
                //size是读入缓冲区中的总字节数。 如果当前可用的字节数没有请求的字节数那么多,则总字节数可能小于请求的字节数,或者如果已到达流的末尾,则为零 (0)。
                while ((size = responseStream.Read(buffer, 0, buffer.Length)) != 0)//将responseStream的内容读入buffer数组
                {
                    ms.Write(buffer, 0, size);//将buffer数组的内容写入内存流ms
                }
                responseStream.Close();//关闭流并释放连接以供重用
                ms.Position = 0;//将内存流数据读取位置归零
                WaveStream blockAlignedStream = new BlockAlignReductionStream(WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(ms)));
                WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback());
                waveOut.Init(blockAlignedStream);
                //waveOut.PlaybackStopped += (sender, e) => { waveOut.Stop(); };
                waveOut.Play();
                while (waveOut.PlaybackState == PlaybackState.Playing)
                {
                    Thread.Sleep(100);
                }

            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
        }
示例#48
0
        private static WaveStream CreateReaderStream(string fileName)
        {
            WaveStream readerStream = null;
            if (fileName.EndsWith(".wav", StringComparison.OrdinalIgnoreCase))
            {
                readerStream = new WaveFileReader(fileName);
                if (readerStream.WaveFormat.Encoding == WaveFormatEncoding.Pcm ||
                    readerStream.WaveFormat.Encoding == WaveFormatEncoding.IeeeFloat) return readerStream;
                readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream);
                readerStream = new BlockAlignReductionStream(readerStream);
            }
            else if (fileName.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase))
                readerStream = new Mp3FileReader(fileName);

            else if (fileName.EndsWith(".aiff"))
                readerStream = new AiffFileReader(fileName);

            return readerStream;
        }
示例#49
0
        private void PlayNotificationSound()
        {
            if (DateTime.UtcNow >= nextAudioAlertPlay)
            {
                DisableAudioAlertForDuration();
                try
                {
                    System.Windows.Resources.StreamResourceInfo sri = Application.GetResourceStream(new Uri("WPFApp/Resources/audio/FeenPhoneDJAlert.wav", UriKind.Relative));

                    using (WaveStream ws =
                       new BlockAlignReductionStream(
                           WaveFormatConversionStream.CreatePcmStream(
                               new WaveFileReader(sri.Stream))))
                    {
                        var length = ws.Length;
                        if (length < int.MaxValue)
                        {
                            byte[] data = new byte[length];
                            var format = ws.WaveFormat;
                            int read = ws.Read(data, 0, (int)length);
                            EventSource.InvokePlaySoundEffect(this, format, data);
                        }
                    }
                }
                catch { }
            }
        }
示例#50
0
 //전화 왔을 때의 벨소리 처리 부분
 private void PlayMP3()
 {
     using (var ms = File.OpenRead("HigherPlace.mp3"))
     using (var rdr = new Mp3FileReader(ms))
     using (var wavStream = WaveFormatConversionStream.CreatePcmStream(rdr))
     using (var baStream = new BlockAlignReductionStream(wavStream))
     {
         //설정해 놓은 mp3 음성파일을 PC에 재생
         waveOut.Init(baStream);
         waveOut.Play();
         while (waveOut.PlaybackState == PlaybackState.Playing)
         {
             Thread.Sleep(100);
         }
     }
 }
示例#51
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();
            }
        }
示例#52
0
 public static double GetMs(this NAudio.Wave.BlockAlignReductionStream stream, WaveOut output)
 {
     return(stream.Position * 1000.0 / output.OutputWaveFormat.BitsPerSample / output.OutputWaveFormat.Channels * 8.0 / output.OutputWaveFormat.SampleRate);
 }