Base class for all WaveStream classes. Derives from stream.
Inheritance: Stream, IWaveProvider
Beispiel #1
0
 /// <summary>
 /// Lejátszik egy .mp3 fájlt
 /// </summary>
 /// <param name="audioFile">.mp3 fájl</param>
 public static void playWave(string audioFile)
 {
     thread = new WaveOut();
     stream = CreateInputStream(audioFile);
     thread.Init(stream);
     thread.Play();
 }
Beispiel #2
0
 public int PlaySong(string path)
 {
     int result = 0;
     sync.InvokeIfRequired((Action)delegate
     {
         CleanPlayerAndStream();
         result = -1;
         if (!string.IsNullOrEmpty(path))
         {
             try
             {
                 MakePlayerInternal();
                 stream = CreateStream(path);
                 player.Init(stream);
                 player.Play();
                 result = (int)(stream.Length / stream.WaveFormat.AverageBytesPerSecond);
             }
             catch (Exception)
             {
                 CleanPlayerAndStream();
             }
         }
     });
     return result;
 }
Beispiel #3
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;
        }
Beispiel #4
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 ");
     }
 }
        /// <summary>
        /// Add a new input to the mixer
        /// </summary>
        /// <param name="waveStream">The wave input to add</param>
        public void AddInputStream(WaveStream waveStream)
        {
            if (waveStream.WaveFormat.Encoding != WaveFormatEncoding.IeeeFloat)
                throw new ArgumentException("Must be IEEE floating point", "waveStream");
            if (waveStream.WaveFormat.BitsPerSample != 32)
                throw new ArgumentException("Only 32 bit audio currently supported", "waveStream");

            if (inputStreams.Count == 0)
            {
                // first one - set the format
                int sampleRate = waveStream.WaveFormat.SampleRate;
                int channels = waveStream.WaveFormat.Channels;
                this.waveFormat = WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, channels);
            }
            else
            {
                if (!waveStream.WaveFormat.Equals(waveFormat))
                    throw new ArgumentException("All incoming channels must have the same format", "waveStream");
            }

            lock (inputsLock)
            {
                this.inputStreams.Add(waveStream);
                this.length = Math.Max(this.length, waveStream.Length);
                // get to the right point in this input file
                waveStream.Position = Position;
            }
        }
Beispiel #6
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();
        }
        /// <summary>
        /// WaveStream to resample using the DMO Resampler
        /// </summary>
        /// <param name="inputProvider">Input Stream</param>
        /// <param name="outputFormat">Desired Output Format</param>
        public ResamplerDmoStream(IWaveProvider inputProvider, WaveFormat outputFormat)
        {
            this.inputProvider = inputProvider;
            this.inputStream = inputProvider as WaveStream;
            this.outputFormat = outputFormat;
            this.resampler = new Resampler();
            if (!resampler.MediaObject.SupportsInputWaveFormat(0, inputProvider.WaveFormat))
            {
                throw new ArgumentException("Unsupported Input Stream format", "inputStream");
            }

            resampler.MediaObject.SetInputWaveFormat(0, inputProvider.WaveFormat);
            if (!resampler.MediaObject.SupportsOutputWaveFormat(0, outputFormat))
            {
                throw new ArgumentException("Unsupported Output Stream format", "outputStream");
            }

            resampler.MediaObject.SetOutputWaveFormat(0, outputFormat);
            if (inputStream != null)
            {
                position = InputToOutputPosition(inputStream.Position);
            }
            this.inputMediaBuffer = new MediaBuffer(inputProvider.WaveFormat.AverageBytesPerSecond);
            this.outputBuffer = new DmoOutputDataBuffer(outputFormat.AverageBytesPerSecond);
        }
 /// <summary>
 /// Creates the reader stream, supporting all filetypes in the core NAudio library,
 /// and ensuring we are in PCM format
 /// </summary>
 /// <param name="fileName">File Name</param>
 private void CreateReaderStream(string fileName)
 {
     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
     {
         // fall back to media foundation reader, see if that can play it
         readerStream = new MediaFoundationReader(fileName);
     }
 }
Beispiel #9
0
 public bool Load(string path, Guid device)
 {
     var cext = path.GetExt();
     _myWaveOut = new DirectSoundOut(device);
     try
     {
         _myWaveStream = _codecs.First(v => v.Extensions.Contains(cext)).CreateWaveStream(path);
     }
     catch
     {
         return false;
     }
     if (_myWaveStream == null) return false;
     if (_myWaveStream.WaveFormat.Channels == 2)
     {
         _myBalanceSampleProvider = new BalanceSampleProvider(_myWaveStream.ToSampleProvider());
         _myVolumeSampleProvider = new VolumeSampleProvider(_myBalanceSampleProvider);
         _myBalanceSampleProvider.Pan = (float)Balance;
     }
     else _myVolumeSampleProvider = new VolumeSampleProvider(_myWaveStream.ToSampleProvider());
     _myEqualizer = new Equalizer(_myVolumeSampleProvider, _equalizerBands) { Enabled = _enableEqualizer };
     _myWaveOut.Init(_myEqualizer);
     _myWaveOut.PlaybackStopped += MyWaveOutOnPlaybackStopped;
     _myVolumeSampleProvider.Volume = (float)Volume;
     return true;
 }
Beispiel #10
0
        public NAudioDecoder(string file)
        {
            extension = Path.GetExtension(file).ToLowerInvariant();

            ready = false;

            if (extension.Equals(".wav"))
            {
                reader = new WaveFileReader(file);
            }
            else
            {
                reader = new Mp3FileReader(file);
            }

            var format = reader.WaveFormat;

            bitsPerSample = format.BitsPerSample;
            sampleRate = format.SampleRate;
            channels = format.Channels;
            
            duration = (int)reader.TotalTime.TotalSeconds;

            ready = (format.BitsPerSample == 16);
        }
Beispiel #11
0
        public SoundResource(ResourceManager mgr, string fullName, Stream stream, Format fmt)
        {
            _manager = mgr;
            FullName = fullName;

            switch (fmt)
            {
                case Format.MP3:
                {
                    Mp3FileReader mp3 = new Mp3FileReader(stream);
                    _reader = mp3;
                    break;
                }
                case Format.WAV:
                {
                    WaveFileReader wav = new WaveFileReader(stream);
                    _reader = wav;
                    break;
                }
                default:
                    throw new InvalidOperationException("Unsupported extension.");
            }

            _stream = new WaveChannel32(_reader);
            _stream.PadWithZeroes = false;

            _wavDevice.PlaybackStopped += _wavDevice_PlaybackStopped;
        }
Beispiel #12
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);
            }
        }
Beispiel #13
0
 public MainForm()
 {
     waveOutDevice = null;
     mainOutputStream = null;
     volumeStream = null;
     InitializeComponent();
 }
Beispiel #14
0
        public override void Load(string file)
        {
            // Dispose on every new load
            Dispose(false);

            ready = false;

            extension = Path.GetExtension(file).ToLowerInvariant();

            if (extension.Equals(".wav"))
            {
                reader = new WaveFileReader(file);
            }
            else
            {
                reader = new Mp3FileReader(file);
            }

            var format = reader.WaveFormat;

            this.sampleRate = format.SampleRate;
            this.channels = format.Channels;

            this.sourceSampleRate = format.SampleRate;
            this.sourceBitDepth = format.BitsPerSample;
            this.sourceChannels = format.Channels;
            this.duration = (int)reader.TotalTime.TotalSeconds;
            this.ready = (format.BitsPerSample == 16);
        }
Beispiel #15
0
 /// <summary>
 /// Charge le flux du morceau en mémoire
 /// </summary>
 /// <param name="play">si play est vrai, joue le morceau à la fin du chargement</param>
 /// <returns>faux si échec du chargement</returns>
 public bool load(bool play = false)
 {
     if (stream_url.Length > 0 && streamable == true)
     {
         terminated = false;
         var response = WebRequest.Create(stream_url + "?client_id=" + client_id).GetResponse();
         MemoryStream ms = new MemoryStream();
         Stream 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;
         }
         this.data = new BlockAlignReductionStream(WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(ms)));
         if (play)
             this.play();
         return true;
     }
     else
         return false;
 }
Beispiel #16
0
        private void Initialize()
        {
            var extension = Path.GetExtension(file).ToLowerInvariant();

            if (extension.Equals(".wav"))
            {
                reader = new WaveFileReader(file);
            }
            else
            {
                reader = new Mp3FileReader(file);
            }

            var format = reader.WaveFormat;

            this.sampleRate = format.SampleRate;
            this.channels = format.Channels;

            this.Format = new AudioProperties(format.SampleRate, format.BitsPerSample,
                format.Channels, (int)reader.TotalTime.TotalSeconds);

            if (format.BitsPerSample != 16)
            {
                Dispose(true);
            }
        }
Beispiel #17
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();
            }
        }
Beispiel #18
0
        private void buttonPlay_Click(object sender, EventArgs e)
        {
            if (waveOut != null)
            {
                if (waveOut.PlaybackState == PlaybackState.Playing)
                {
                    return;
                }
                else if (waveOut.PlaybackState == PlaybackState.Paused)
                {
                    waveOut.Play();
                    groupBoxDriverModel.Enabled = false;
                    return;
                }
            }
            
            // we are in a stopped state
            // TODO: only re-initialise if necessary

            if (String.IsNullOrEmpty(fileName))
            {
                toolStripButtonOpenFile_Click(sender, e);
            }
            if (String.IsNullOrEmpty(fileName))
            {
                return;
            }

            try
            {
                CreateWaveOut();
            }
            catch (Exception driverCreateException)
            {
                MessageBox.Show(String.Format("{0}", driverCreateException.Message));
                return;
            }

            mainOutputStream = CreateInputStream(fileName);
            trackBarPosition.Maximum = (int)mainOutputStream.TotalTime.TotalSeconds;
            labelTotalTime.Text = String.Format("{0:00}:{1:00}", (int)mainOutputStream.TotalTime.TotalMinutes,
                mainOutputStream.TotalTime.Seconds);
            trackBarPosition.TickFrequency = trackBarPosition.Maximum / 30;

            try
            {
                waveOut.Init(mainOutputStream);
            }
            catch (Exception initException)
            {
                MessageBox.Show(String.Format("{0}", initException.Message), "Error Initializing Output");
                return;
            }

            // not doing Volume on IWavePlayer any more
            volumeStream.Volume = volumeSlider1.Volume; 
            groupBoxDriverModel.Enabled = false;
            waveOut.Play();
        }
 /// <summary>
 /// Create a new WaveFormat conversion stream
 /// </summary>
 /// <param name="targetFormat">Desired output format</param>
 /// <param name="sourceStream">Source stream</param>
 public WaveFormatConversionStream(WaveFormat targetFormat, WaveStream sourceStream)
 {
     this.sourceStream = sourceStream;
     this.targetFormat = targetFormat;
     conversionProvider = new WaveFormatConversionProvider(targetFormat, sourceStream);
     length = EstimateSourceToDest((int)sourceStream.Length);
     position = 0;
 }
Beispiel #20
0
        public WaveListenerProvider(WaveStream sourceStream)
        {
            this.sourceStream = sourceStream;
            waveFormat = WaveFormat.CreateIeeeFloatWaveFormat(sourceStream.WaveFormat.SampleRate, sourceStream.WaveFormat.Channels);

            sampleAggregator.FftCalculated += new EventHandler<FftEventArgs>(FftCalculated);
            sampleAggregator.PerformFFT = true;
        }
Beispiel #21
0
 public Audio(string filename)
 {
     this.fileName = filename;
     waveOutDevice = new DirectSoundOut(50);
     mainOutputStream = CreateInputStream(filename);
     waveOutDevice.Init(mainOutputStream);
     isPlaying = false;
 }
Beispiel #22
0
 private void CloseFile()
 {
     if (fileStream != null)
     {
         fileStream.Dispose();
         fileStream = null;
     }
 }
Beispiel #23
0
 public MeteringStream(WaveStream sourceStream, int samplesPerNotification)
 {
     SourceStream = sourceStream;
     if (sourceStream.WaveFormat.BitsPerSample != 32)
         throw new ArgumentException("Metering Stream expects 32 bit floating point audio", "sourceStream");
     maxSamples = new float[sourceStream.WaveFormat.Channels];
     this.SamplesPerNotification = samplesPerNotification;
 }
Beispiel #24
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);
 }
 /// <summary>
 /// Creates a stream that can convert to PCM
 /// </summary>
 /// <param name="sourceStream">The source stream</param>
 /// <returns>A PCM stream</returns>
 public static WaveStream CreatePcmStream(WaveStream sourceStream)
 {
     if (sourceStream.WaveFormat.Encoding == WaveFormatEncoding.Pcm)
     {
         return sourceStream;
     }
     WaveFormat pcmFormat = AcmStream.SuggestPcmFormat(sourceStream.WaveFormat);
     return new WaveFormatConversionStream(pcmFormat, sourceStream);
 }
Beispiel #26
0
 public AudioPlaya(string filename) {
     waveOutDevice = new WaveOut();
     waveOutDevice.Init(stream = loadFromFile(filename));
     waveOutDevice.PlaybackStopped += (object sender, StoppedEventArgs e) =>
     {
         if (Finished != null)
             Finished(this);
     };
 }
 private void CreateReaderStream(Stream WavStream)
 {
     readerStream = new WaveFileReader(WavStream);
     if (readerStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm && readerStream.WaveFormat.Encoding != WaveFormatEncoding.IeeeFloat)
     {
         readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream);
         readerStream = new BlockAlignReductionStream(readerStream);
     }
 }
Beispiel #28
0
 public EffectStream(EffectChain effects, WaveStream sourceStream)
 {
     this.effects = effects;
     this.source = sourceStream;
     foreach (Effect effect in effects)
     {
         InitialiseEffect(effect);
     }
 }
 public void Stop()
 {
     Output.Stop();
     Stream.Close();
     Stream.Dispose();
     Stream = null;
     Output = new WaveOut();
     timer1.Stop();
     timer1.Enabled = false;
 }
Beispiel #30
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);
        }
 /// <summary>
 /// Create a new simple compressor stream
 /// </summary>
 /// <param name="sourceStream">Source stream</param>
 public SimpleCompressorStream(WaveStream sourceStream)
 {
     this.sourceStream = sourceStream;
     this.channels = sourceStream.WaveFormat.Channels;
     this.bytesPerSample = sourceStream.WaveFormat.BitsPerSample / 8;
     simpleCompressor = new SimpleCompressor(5.0, 10.0, sourceStream.WaveFormat.SampleRate);
     simpleCompressor.Threshold = 16;
     simpleCompressor.Ratio = 6;
     simpleCompressor.MakeUpGain = 16;
 }
Beispiel #32
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();
        }
 private IWaveProvider CreateReader()
 {
     if (reader is RawSourceWaveStream)
     {
         reader.Position = 0;
         return reader;
     }
     reader = new MediaFoundationReaderRT(selectedStream);
     return reader;
 }        
Beispiel #34
0
 private void proPlayMusic(string musica)
 {
     /* Toca a musica em si e aciona o evento para já tocar a próxima */
     NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(musica));
     stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
     _rPodeEntrarTrocaMusic = true;
     output.Init(stream);
     output.PlaybackStopped += player_PlaybackStopped;
     output.Play();
 }
Beispiel #35
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;
            }
        }
        /// <summary>
        /// Create a new WaveFormat conversion stream
        /// </summary>
        /// <param name="targetFormat">Desired output format</param>
        /// <param name="sourceStream">Source stream</param>
        public WaveFormatConversionStream(WaveFormat targetFormat, WaveStream sourceStream)
        {
            this.sourceStream = sourceStream;
            this.targetFormat = targetFormat;

            conversionStream = new AcmStream(sourceStream.WaveFormat, targetFormat);
            // work out how many bytes the entire input stream will convert to
            length = SourceToDest((int)sourceStream.Length);
            blockAlign = SourceToDest(sourceStream.BlockAlign);
            position = 0;
        }
        private static void Extract(Stream output, WaveStream waveStream, byte[] buffer)
        {
            if (waveStream == null)
                return;

            using (WaveFileWriter writer = new WaveFileWriter(output, waveStream.WaveFormat))
            {
                int count;
                while ((count = waveStream.Read(buffer, 0, buffer.Length)) != 0)
                    writer.Write(buffer, 0, count);
            }
        }
Beispiel #38
0
        private static void TestSeekPosition(WaveStream mainOutputStream, TimeSpan timeSpan)
        {
            Console.WriteLine("Hit key to reposition..");
            Console.ReadKey();

            Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine("Seeking to new time: {0}...", timeSpan);
            (mainOutputStream as WaveChannel32).CurrentTime = timeSpan;
            Console.WriteLine("New position after seek: " + (mainOutputStream as WaveChannel32).CurrentTime);

            Console.ResetColor();
        }
Beispiel #39
0
		private float[] bufferFloat; // 32bit float audio
		
		/// <summary>
		/// Creates a new delay effect
		/// </summary>
		/// <param name="inStream">The incoming audio data</param>
		/// <param name="length">The delay length in milliseconds</param>
		/// <param name="wetPercent">Percentage of output delay</param>
		/// <param name="feedbackPercent">Percentage feedback</param>
		public Delay(WaveStream inStream, int length, float wetPercent, float feedbackPercent) 
		{
			this.inStream = inStream;
			if(inStream.WaveFormat.Encoding == WaveFormatEncoding.IeeeFloat) 
			{
				bufferFloat = new float[(inStream.WaveFormat.AverageBytesPerSecond * length)/ 1000];
			}
			else if(inStream.WaveFormat.Encoding == WaveFormatEncoding.Pcm)
			{
				buffer16 = new short[(inStream.WaveFormat.AverageBytesPerSecond * length)/ 1000];
			}
		}
Beispiel #40
0
        static void Main(string[] args)
        {
            var A          = generateSound(440, 48000, 5);
            var waveFormat = new WaveFormat(8000, 16, 1);

            using (WaveFileWriter writer = new WaveFileWriter("OLOLO.wav", waveFormat))
            {
                writer.WriteData(A, 0, A.Length);
            }


            return;

            NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.WaveFileReader(WavFilePath));

            if (pcm.WaveFormat.Channels != 2)
            {
                return;
            }

            int someInterval = pcm.WaveFormat.Channels * pcm.WaveFormat.SampleRate * pcm.WaveFormat.BitsPerSample / 8;

            float time         = 10; // 10 secs
            float samplingRate = pcm.WaveFormat.SampleRate;
            int   index        = (int)(time / samplingRate);

            byte[] buffer  = new byte[someInterval];
            int    current = 0;
            int    ret     = 0;

            do
            {
                ret = pcm.Read(buffer, current, someInterval);

                float[] res = new float[buffer.Length / 2];

                for (int i = 0; i < res.Length; i += 2)
                {
                    res[i] = (buffer[i] + buffer[i + 1]) / 2 / 32768.0f;
                }


                current += someInterval;
            } while (ret != -1);

            PlayPCM(pcm);
        }
Beispiel #41
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");
     }
 }
Beispiel #42
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");
        }
Beispiel #43
0
 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;
 }
 /// <summary>
 /// Creates a new BlockAlignReductionStream
 /// </summary>
 /// <param name="sourceStream">the input stream</param>
 public BlockAlignReductionStream(WaveStream sourceStream)
 {
     this.sourceStream = sourceStream;
     circularBuffer    = new CircularBuffer(sourceStream.WaveFormat.AverageBytesPerSecond * 4);
 }
Beispiel #45
0
 public WaveOffsetStream(WaveStream sourceStream) : this(sourceStream, TimeSpan.Zero, TimeSpan.Zero, sourceStream.TotalTime)
 {
 }
Beispiel #46
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();
            }
        }
 /// <summary>
 /// Creates a WaveChannel32 with default settings
 /// </summary>
 /// <param name="sourceStream">The source stream</param>
 public WaveChannel32(WaveStream sourceStream)
     :
     this(sourceStream, 1.0f, 0.0f)
 {
 }