Ejemplo n.º 1
0
        /// <summary>
        /// リソースの解放を行います。
        /// </summary>
        public void Dispose()
        {
            if (this.iwp != null)
            {
                this.iwp.Stop();
            }

            if (this.ws != null)
            {
                this.wc32.Close();
                this.wc32 = null;

                this.ws.Close();
                this.ws = null;
            }

            if (this.iwp != null)
            {
                this.iwp.Dispose();
                this.iwp = null;
            }
        }
Ejemplo n.º 2
0
        public TestMix()
        {
            //WaveStream str1 = new Mp3FileReader("C:\\Users\\mtemkine\\Desktop\\snd\\guitar1.mp3");
            //WaveStream str2 = new Mp3FileReader("C:\\Users\\mtemkine\\Desktop\\snd\\molecules.mp3");
            //WaveMixerStream32 mix = new WaveMixerStream32(new [] {str1, str2}, false);

            var background = new Mp3FileReader("C:\\Users\\mtemkine\\Desktop\\snd\\ferriss.mp3");
            var message    = new Mp3FileReader("C:\\Users\\mtemkine\\Desktop\\snd\\guitar1.mp3");

            var mixer = new WaveMixerStream32();

            mixer.AutoStop = true;

            var messageOffset    = background.TotalTime;
            var messageOffsetted = new WaveOffsetStream(message, TimeSpan.FromSeconds(1.5), TimeSpan.Zero, message.TotalTime.Subtract(TimeSpan.FromSeconds(1)));

            var background32 = new WaveChannel32(background);

            background32.PadWithZeroes = false;
            background32.Volume        = 0.9f;

            var message32 = new WaveChannel32(messageOffsetted);

            message32.PadWithZeroes = false;
            message32.Volume        = 0.7f;

            var        s1           = new RawSourceWaveStream(background32, new WaveFormat(8000, 16, 1));
            var        s2           = new RawSourceWaveStream(message32, new WaveFormat(8000, 16, 1));
            WaveFormat targetFormat = WaveFormat.CreateIeeeFloatWaveFormat(128, 2);
            var        ss1          = new WaveFormatConversionStream(targetFormat, background32);

            //var c = new WaveFormatConversionStream(WaveFormat.CreateALawFormat(8000, 1), background32);
            //var stream_background32 = new WaveFormatConversionStream(new WaveFormat(256, 32, 2), background32);
            //var stream_message32 = new WaveFormatConversionStream(new WaveFormat(256, 32, 2), message32);
            mixer.AddInputStream(s1);
            mixer.AddInputStream(s2);

            WaveFileWriter.CreateWaveFile("mycomposed.wav", new Wave32To16Stream(mixer));
        }
Ejemplo n.º 3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="volume"></param>
        /// <returns></returns>
        public static int LoadSoundToBuffer(string filepath, float volume)
        {
#if WINDOWS
            WaveChannel32 channel = CreateInputStream(filepath, volume, true);

            if (channel == null)
            {
                return(-1);
            }

            buffer[bufferCount] = new MappedWaveChannel()
            {
                WaveChannel = channel, LastPosition = 0
            };

            bufferCount++;

            return(bufferCount - 1);
#elif WINRT
            return(-1);
#endif
        }
Ejemplo n.º 4
0
    private void UnloadAudio()
    {
        if (mWaveOutDevice != null)
        {
            mWaveOutDevice.Stop();
        }
        if (mMainOutputStream != null)
        {
            // this one really closes the file and ACM conversion
            mVolumeStream.Close();
            mVolumeStream = null;

            // this one does the metering stream
            mMainOutputStream.Close();
            mMainOutputStream = null;
        }
        if (mWaveOutDevice != null)
        {
            mWaveOutDevice.Dispose();
            mWaveOutDevice = null;
        }
    }
Ejemplo n.º 5
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);
     }
 }
Ejemplo n.º 6
0
        public void OpenFile(string path)
        {
            Stop();

            if (ActiveStream != null)
            {
                SelectionBegin  = TimeSpan.Zero;
                SelectionEnd    = TimeSpan.Zero;
                ChannelPosition = 0;
            }

            StopAndCloseStream();

            if (System.IO.File.Exists(path))
            {
                try
                {
                    waveOutDevice = new WaveOut()
                    {
                        DesiredLatency = 100
                    };

                    ActiveStream        = (WaveStream) new AudioFileReader(path);
                    inputStream         = new WaveChannel32(ActiveStream);
                    sampleAggregator    = new SampleAggregator(fftDataSize);
                    inputStream.Sample += inputStream_Sample;
                    waveOutDevice.Init(inputStream);
                    ChannelLength = inputStream.TotalTime.TotalSeconds;
                    FileTag       = TagLib.File.Create(path);
                    GenerateWaveformData(path);
                    CanPlay = true;
                }
                catch
                {
                    ActiveStream = null;
                    CanPlay      = false;
                }
            }
        }
Ejemplo n.º 7
0
        public static void PlayGameSound(GameSound sound)
        {
            var isSubscribed = SubscriptionModule.Get().IsSubscribed ?? false;

            if (isSubscribed && Prefs.EnableGameSound)
            {
                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        if (sound.Src.ToLowerInvariant().EndsWith(".mp3"))
                        {
                            using (var mp3Reader = new Mp3FileReader(sound.Src))
                                using (var stream = new WaveChannel32(mp3Reader))
                                    using (var wo = new WaveOut())
                                    {
                                        wo.Init(stream);
                                        wo.Play();
                                        while (wo.PlaybackState == PlaybackState.Playing)
                                        {
                                            Thread.Sleep(1);
                                        }
                                    }
                        }
                        else
                        {
                            using (var player = new SoundPlayer(sound.Src))
                            {
                                player.PlaySync();
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Warn("PlayGameSound Error", e);
                    }
                });
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// リソースの解放を行います。
        /// </summary>
        public void Dispose()
        {
            if (this._waveOut != null)
            {
                this._waveOut.Stop();
            }

            if (this._audioStream != null)
            {
                this._volumeStream.Close();
                this._volumeStream = null;

                this._audioStream.Close();
                this._audioStream = null;
            }

            if (this._waveOut != null)
            {
                this._waveOut.Dispose();
                this._waveOut = null;
            }
        }
Ejemplo n.º 9
0
 private void CloseWaveOut()
 {
     buttonControlPanel.Enabled = false;
     if (waveOut != null)
     {
         waveOut.Stop();
     }
     if (mainOutputStream != null)
     {
         // this one really closes the file and ACM conversion
         volumeStream.Close();
         volumeStream = null;
         // this one does the metering stream
         mainOutputStream.Close();
         mainOutputStream = null;
     }
     if (waveOut != null)
     {
         waveOut.Dispose();
         waveOut = null;
     }
 }
Ejemplo n.º 10
0
        private static WaveStream CreateInputStream(string fileName)
        {
            WaveChannel32 inputStream;
            WaveStream    readerStream = null;

            if (fileName.EndsWith(".wav"))
            {
                readerStream = new WaveFileReader(fileName);
            }
            else if (fileName.EndsWith(".ogg"))
            {
                readerStream = new OggVorbisFileReader(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);
        }
Ejemplo n.º 11
0
        public void OpenFile(string path)
        {
            this.Stop();

            if (this.ActiveStream != null)
            {
                this.SelectionBegin  = TimeSpan.Zero;
                this.SelectionEnd    = TimeSpan.Zero;
                this.ChannelPosition = 0;
            }

            this.StopAndCloseStream();

            if (File.Exists(path))
            {
                try
                {
                    this.waveOutDevice = new WaveOut
                    {
                        DesiredLatency = 100
                    };
                    //  ActiveStream = new Mp3FileReader(path);
                    this.ActiveStream        = new WaveFileReader(path);
                    this.inputStream         = new WaveChannel32(this.ActiveStream);
                    this.sampleAggregator    = new SampleAggregator(this.fftDataSize);
                    this.inputStream.Sample += this.inputStream_Sample;
                    this.waveOutDevice.Init(this.inputStream);
                    this.ChannelLength = this.inputStream.TotalTime.TotalSeconds;
                    this.GenerateWaveformData(path);
                    this.CanPlay = true;
                }
                catch
                {
                    this.ActiveStream = null;
                    this.CanPlay      = false;
                }
            }
        }
Ejemplo n.º 12
0
        public void OpenFile(string path)
        {
            if (ActiveStream != null)
            {
                ChannelPosition = 0;
            }

            StopAndCloseStream();

            if (System.IO.File.Exists(path))
            {
                try
                {
                    _waveOutDevice = new WaveOutEvent()
                    {
                        DesiredLatency = 65
                    };

                    ActiveStream         = new AudioFileReader(path);
                    _inputStream         = new WaveChannel32(ActiveStream);
                    _aggregator          = new Aggregator(_fftDataSize);
                    _inputStream.Sample += inputStream_Sample;
                    _waveOutDevice.Init(_inputStream);

                    ChannelLength = 100;
                    GenerateWaveformData(path);
                    CanPlay = true;

                    _inputStream.PadWithZeroes      = false;
                    _waveOutDevice.PlaybackStopped += new EventHandler <StoppedEventArgs>(OnPlaybackStopped);
                }
                catch
                {
                    ActiveStream = null;
                    CanPlay      = false;
                }
            }
        }
Ejemplo n.º 13
0
        private void StartVisualization(object sender, EventArgs e)
        {
            WaveChannel32 wave = new WaveChannel32(new Mp3FileReader("test.mp3"));
            // WaveChannel32 wave = new WaveChannel32(new Mp3FileReader("C:\\Users\\Kapi\\Desktop\\test2.mp3"));
            int sampleSize = 1024;
            var bufferSize = 16384 * sampleSize;

            bufferSize = 1024;
            var buffer = new byte[bufferSize];
            int read   = 0;

            while (wave.Position < wave.Length)
            {
                read = wave.Read(buffer, 0, bufferSize);
                for (int i = 0; i < read / sampleSize; i++)
                {
                    var point = BitConverter.ToSingle(buffer, i * sampleSize);
                    _waveformPoints.Add(point);
                }
            }



            _waveOutDevice   = new WaveOut();
            _audioFileReader = new AudioFileReader("test.mp3");
            //_audioFileReader = new AudioFileReader("C:\\Users\\Kapi\\Desktop\\test2.mp3");

            for (int i = 0; i < _audioFileReader.TotalTime.TotalMilliseconds; i++)
            {
                _waveformPointsMiliseconds.Add(_waveformPoints[(int)((double)i / (_audioFileReader.TotalTime.TotalMilliseconds) * _waveformPoints.Count)]);
            }

            _waveOutDevice.Init(_audioFileReader);
            _waveOutDevice.Play();
            _waveformTmr.Start();
            label2.Text = _audioFileReader.TotalTime.TotalMilliseconds.ToString();
            waveFormBox.Refresh();
        }
Ejemplo n.º 14
0
        public void Load(string fileName, IntPtr handle)
        {
            this.FileName = fileName;

            try
            {
                if (mainOutputStream != null)
                {
                    Stop();
                    CloseCurrentFile();
                }

                if (waveOutDevice == null)
                {
                    waveOutDevice = new WaveOut(handle);
                }

                if (fileName.EndsWithEx("ogg"))
                {
                    mainOutputStream = new OggFileReader(fileName);
                }
                else
                {
                    mainOutputStream = new Mp3FileReader(fileName);
                }

                volumeStream     = new WaveChannel32(mainOutputStream);
                mainOutputStream = volumeStream;

                waveOutDevice.Init(volumeStream);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("LoadMP3 " + ex.Message);

                CloseCurrentFile();
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Reproduce la cancion
        /// </summary>
        /// <param name="mp3Array"></param>
        private void PlaySong(byte[] mp3Array)
        {
            byte[]      copy = File.ReadAllBytes("torero.mp3");
            TagLib.File file = TagLib.File.Create("torero.mp3");
            Console.WriteLine(file.Tag.Title);
            Console.WriteLine(file.Tag.Album);

            using (var mp3Stream = new MemoryStream(mp3Array))
            {
                using (var mp3FileReader = new Mp3FileReader(mp3Stream))
                {
                    using (var wave32 = new WaveChannel32(mp3FileReader, 0.1f, 1f))
                    {
                        using (var ds = new DirectSoundOut())
                        {
                            ds.Init(wave32);
                            ds.Play();
                            Thread.Sleep(30000 * 5);
                        }
                    }
                }
            }
        }
Ejemplo n.º 16
0
        static void PlayUsingNAudio(String soundFile)
        {
            // The hard way.
            // http://naudio.codeplex.com/documentation
            // http://naudio.codeplex.com/wikipage?title=WAV
            using (var wfr = new WaveFileReader(soundFile))
                using (WaveChannel32 wc = new WaveChannel32(wfr)
                {
                    PadWithZeroes = false
                })
                    using (var audioOutput = new DirectSoundOut())
                    {
                        audioOutput.Init(wc);
                        audioOutput.Play();

                        while (audioOutput.PlaybackState != PlaybackState.Stopped)
                        {
                            Thread.Sleep(20);
                        }

                        audioOutput.Stop();
                    }
        }
Ejemplo n.º 17
0
        private void HandleRendered(string output)
        {
            Errors.Log("Render finished.");

            if (!File.Exists(output))
            {
                Errors.Log("Output file doesn't exist.");
                return;
            }
            Errors.Log("Play output.");

            var wavReader   = new WaveFileReader(output);
            var waveChannel = new WaveChannel32(wavReader);
            var player      = new WaveOutEvent();

            player.Init(waveChannel);
            player.PlaybackStopped += delegate { playFinished = true; };
            player.Play();
            while (!playFinished)
            {
                Thread.Sleep(1);
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Prepares wave file for playing. Needs to be called if wavefile or audio device is changed.
        /// </summary>
        void InitializeWave()
        {
            try
            {
                DisposeNAudioComponents();
                WaveOut = new WaveOutEvent();

                ProcessWaveStream();
                Reader = new WaveFileReader(WaveStream);

                MixedWave            = new WaveChannel32(Reader, VolumeF, PanF);
                WaveDurationMs       = (int)MixedWave.TotalTime.TotalMilliseconds + 5; // add some buffer
                WaveOut.DeviceNumber = AudioDevices.GetWaveOutDeviceNumber();
                WaveOut.Init(MixedWave);

                Error = false;
            }
            catch (Exception e)
            {
                Error = true;
                Config.WriteLog("Unable to initialize audio for " + (Wave?.DisplayName ?? "") + Environment.NewLine + e.Message);
            }
        }
        // get record from file
        public Record(String path, String label)
        {
            WaveChannel32 wave = new WaveChannel32(new WaveFileReader(path));

            this.path   = path;
            this.label  = label;
            this.frames = new List <RecordFrame>();

            byte[]        buffer      = new byte[16384];
            int           read        = 0;
            List <double> listSamples = new List <double>();
            int           sampleRate  = 16000;

            while (wave.Position < wave.Length)
            {
                read = wave.Read(buffer, 0, 16384);
                for (int i = 0; i < read / 4; i++)
                {
                    double sample = BitConverter.ToSingle(buffer, i * 4);
                    listSamples.Add(sample);
                }
            }

            Signal signal = Signal.FromArray(listSamples.ToArray(), sampleRate);

            MelFrequencyCepstrumCoefficient mfcc = new MelFrequencyCepstrumCoefficient();
            IEnumerable <MelFrequencyCepstrumCoefficientDescriptor> features = mfcc.Transform(signal);

            foreach (var t in features)
            {
                RecordFrame recordFrame = new RecordFrame();
                recordFrame.coefficients = new List <double>(t.Descriptor);
                recordFrame.label        = label;

                this.frames.Add(recordFrame);
            }
        }
Ejemplo n.º 20
0
        // Plays a songs
        public void PlaySong(Song song)
        {
            try
            {
                // If the playbackstate is playing, release song resources and stop the current WaveOutEvent
                if (currentSP.PlaybackState == PlaybackState.Playing || currentSP.PlaybackState == PlaybackState.Paused)
                {
                    SongEnded();
                    currentSP.Stop();
                }

                // Create new audio stream for different audio types
                if (song.audioType == Song.AudioType.mp3)
                {
                    mainOutputStream = new Mp3FileReader(AppDomain.CurrentDomain.BaseDirectory + @"Assets\" + song.audioFileName + "." + song.audioType.ToString());
                    volumeStream     = new WaveChannel32(mainOutputStream);
                }
                else if (song.audioType == Song.AudioType.wav)
                {
                    mainOutputStream = new WaveFileReader(AppDomain.CurrentDomain.BaseDirectory + @"Assets\" + song.audioFileName + "." + song.audioType.ToString());
                    volumeStream     = new WaveChannel32(mainOutputStream);
                }

                // Sets the current song
                currentSong = song;

                // Initializes and plays the new volume Stream
                currentSP.Init(volumeStream);
                currentSP.Play();

                // Sets up the song UI
                SetupSongUI(song, mainOutputStream.TotalTime);
            } catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
Ejemplo n.º 21
0
        public bool OpenFile(string filePath)
        {
            Close();

            try
            {
                var reader = Path.GetExtension(filePath) == ".mp3"
                    ? new Mp3FileReader(filePath)
                    : (WaveStream) new WaveFileReader(filePath);

                // don't pad, otherwise the stream never ends
                var inputStream = new WaveChannel32(reader)
                {
                    PadWithZeroes = false
                };

                ProcessorStream = new SoundTouchWaveStream(inputStream);

                _waveOut = new WaveOutEvent()
                {
                    DesiredLatency = 100
                };

                _waveOut.Init(ProcessorStream);
                _waveOut.PlaybackStopped += OnPlaybackStopped;

                StatusMessage.Write("Opened file " + filePath);
                return(true);
            }
            catch (Exception exp)
            {
                // Error in opening file
                _waveOut = null;
                StatusMessage.Write("Can't open file: " + exp.Message);
                return(false);
            }
        }
Ejemplo n.º 22
0
        public void Play()
        {
            var file = Path.Combine(BasicTeraData.Instance.ResourceDirectory, "sound/", File);

            try
            {
                var outputStream = new MediaFoundationReader(file);
                var volumeStream = new WaveChannel32(outputStream);
                volumeStream.Volume = Volume;
                //Create WaveOutEvent since it works in Background and UI Threads
                var player = new DirectSoundOut();
                //Init Player with Configured Volume Stream
                player.Init(volumeStream);
                player.Play();

                var timer = new Timer((obj) =>
                {
                    player.Stop();
                    player.Dispose();
                    volumeStream.Dispose();
                    outputStream.Dispose();
                    outputStream = null;
                    player       = null;
                    volumeStream = null;
                }, null, Duration, Timeout.Infinite);
            }
            catch (Exception e)
            {
                // Get stack trace for the exception with source file information
                var st = new StackTrace(e, true);
                // Get the top stack frame
                var frame = st.GetFrame(0);
                // Get the line number from the stack frame
                var line = frame.GetFileLineNumber();
                BasicTeraData.LogError("Sound ERROR test" + e.Message + Environment.NewLine + e.StackTrace + Environment.NewLine + e.InnerException + Environment.NewLine + e + Environment.NewLine + "filename:" + file + Environment.NewLine + "line:" + line, false, true);
            }
        }
Ejemplo n.º 23
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: dispose managed state (managed objects).
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                if (DisplayInfo != null)
                {
                    DisplayInfo.Dispose();
                    DisplayInfo = null;
                }
                if (waveOutDevice != null)
                {
                    waveOutDevice.Stop();
                }
                if (activeStream != null)
                {
                    inputStream.Close();
                    inputStream = null;
                    ActiveStream.Close();
                    ActiveStream = null;
                }
                if (waveOutDevice != null)
                {
                    waveOutDevice.Dispose();
                    waveOutDevice = null;
                }

                // TODO: set large fields to null.

                disposedValue = true;
            }
        }
Ejemplo n.º 24
0
        public void OpenFile(string path)
        {
            Stop();

            if (ActiveStream != null)
            {
                SelectionBegin  = TimeSpan.Zero;
                SelectionEnd    = TimeSpan.Zero;
                ChannelPosition = 0;
            }

            StopAndCloseStream();

            if (System.IO.File.Exists(path))
            {
                try
                {
                    waveOutDevice       = new WasapiOut(new MMDeviceEnumerator().GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia), AudioClientShareMode.Shared, false, 2);
                    ActiveStream        = new Mp3FileReader(path);
                    inputStream         = new WaveChannel32(ActiveStream);
                    sampleAggregator    = new SampleAggregator(fftDataSize);
                    inputStream.Sample += inputStream_Sample;
                    waveOutDevice.Init(inputStream);
                    ChannelLength = inputStream.TotalTime.TotalSeconds;
                    FileTag       = File.Create(path);
                    GenerateWaveformData(path);
                    CanPlay = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"{ex.GetType()}: {ex.Message}");

                    ActiveStream = null;
                    CanPlay      = false;
                }
            }
        }
Ejemplo n.º 25
0
        private void sbtOpen_Click(object sender, EventArgs e)
        {
            sbtPause.Enabled = true;
            sbtPause.Focus();
            OpenFileDialog open = new OpenFileDialog();

            open.InitialDirectory = txtPathSave.Text;
            open.Filter           = "MP3/WAV File (*.mp3,*.wav)|*.mp3;*.wav";
            if (open.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            DisposWave();
            if (open.FileName.EndsWith(".mp3"))
            {
                WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(open.FileName));
                steam = new BlockAlignReductionStream(pcm);
            }
            else if (open.FileName.EndsWith(".wav"))
            {
                WaveStream pcm = new WaveChannel32(new WaveFileReader(open.FileName));
                steam = new BlockAlignReductionStream(pcm);
            }
            else
            {
                throw new InvalidOperationException("ko phai file audio");
            }
            txtTenFile.Text = open.SafeFileName;



            output = new DirectSoundOut();
            output.Init(steam);
            output.Play();
        }
Ejemplo n.º 26
0
        public void OpenFile(string path)
        {
            Stop();
            StopAndCloseStream();

            if (ActiveStream != null)
            {
                ClearRepeatRange();
                ChannelPosition = 0;
            }

            if (System.IO.File.Exists(path))
            {
                try
                {
                    waveOutDevice = new WaveOut()
                    {
                        DesiredLatency = 100
                    };
                    ActiveStream        = new Mp3FileReader(path);
                    inputStream         = new WaveChannel32(ActiveStream);
                    sampleAggregator    = new SampleAggregator(4096);
                    inputStream.Sample += inputStream_Sample;
                    waveOutDevice.Init(inputStream);
                    ChannelLength = inputStream.TotalTime.TotalSeconds;
                    FileTag       = TagLib.File.Create(path);
                    GenerateWaveformData(path);
                    CanPlay = true;
                }
                catch
                {
                    ActiveStream = null;
                    CanPlay      = false;
                }
            }
        }
Ejemplo n.º 27
0
        private WaveStream CreateInputStream()
        {
            WaveChannel32 inputStream;

            Stream stream = Subsonic.StreamSong(currentSong.id);

            // Try to move this filling of memory stream into the background...
            Stream ms = new MemoryStream();

            byte[] buffer = new byte[32768];
            int    read;

            while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                playerThread.ReportProgress(50);

                ms.Write(buffer, 0, read);
            }

            ms.Position = 0;

            WaveStream mp3Reader          = new Mp3FileReader(ms);
            WaveStream pcmStream          = WaveFormatConversionStream.CreatePcmStream(mp3Reader);
            WaveStream blockAlignedStream = new BlockAlignReductionStream(pcmStream);

            inputStream = new WaveChannel32(blockAlignedStream);

            // we are not going into a mixer so we don't need to zero pad
            //((WaveChannel32)inputStream).PadWithZeroes = false;
            volumeStream = inputStream;

            //var meteringStream = new MeteringStream(inputStream, inputStream.WaveFormat.SampleRate / 10);
            //meteringStream.StreamVolume += new EventHandler<StreamVolumeEventArgs>(meteringStream_StreamVolume);

            return(volumeStream);
        }
Ejemplo n.º 28
0
        void DisposeNAudioComponents()
        {
            WaveOut?.Stop();
            WaveOut?.Dispose();
            WaveOut = null;
            MixedWave?.Dispose();
            MixedWave = null;
            Reader?.Dispose();
            Reader = null;
            WaveStream?.Dispose();
            WaveStream = null;

            // They say you shouldn't (have to) manually call the garbage collector, but...
            // after testing I can't find any problems with it, and this way memory usage is kept consistently lower than without calling the GC.
            // I know the memory would be eventually freed anyway, and there's no real benefit from doing this, but...
            // Without immediately purging the unused wave-streams, the task manager is showing a higher memory usage than necessary,
            // which might lead some users to (erroneously, but understandably) conclude that there's a memory leak or something.
            // And since I know this is a logical place to free the memory in my app, why not let the GC know?
            //
            // Waves will only be disposed when the user is interacting with the GUI which is a rare event and not performance critical.
            // Depending on the user operation (e.g. changing the audio device), this might get called several times in succession,
            // but it doesn't seem to cause any side-effects.
            GC.Collect();
        }
Ejemplo n.º 29
0
        public static void play(string mp3, long position)
        {
            oldsong          = mp3;
            mainOutputStream = new Mp3FileReader(mp3 + "/song.mp3");
            WaveChannel32 volumeStream = new WaveChannel32(mainOutputStream);

            mainOutputStream.Position = position;
            volumeStream.Volume       = 0.20f;

            try
            {
                player.Stop();
                player.Dispose();
            }
            catch (Exception)
            {
            }

            player = new WaveOutEvent();

            player.Init(volumeStream);

            player.Play();
        }
Ejemplo n.º 30
0
 public static string Converter(string inPath)
 {
     using (WaveFileReader mpbacground = new WaveFileReader(inPath))
     {
         using (WaveStream background = WaveFormatConversionStream.CreatePcmStream(mpbacground))
         {
             using (var mixer = new WaveMixerStream32())
             {
                 mixer.AutoStop = true;
                 var messageOffset = background.TotalTime;
                 var background32  = new WaveChannel32(background);
                 background32.PadWithZeroes = false;
                 mixer.AddInputStream(background32);
                 using (var wave32 = new Wave32To16Stream(mixer))
                 {
                     var mp3Stream = ConvertWavToMp3(wave32);
                     inPath = inPath.Split('.')[0] + ".mp3";
                     File.WriteAllBytes(inPath, mp3Stream.ToArray());
                 }
             }
         }
     }
     return(inPath);
 }
Ejemplo n.º 31
0
        private WaveStream CreateInputStream(string fileName)
        {
            WaveChannel32 inputStream;
            if (fileName.EndsWith(".mp3"))
            {
                WaveStream mp3Reader = new Mp3FileReader(fileName);
                inputStream = new WaveChannel32(mp3Reader);
            }
            else
            {
                throw new InvalidOperationException("Unsupported extension");
            }

            return inputStream;
        }