コード例 #1
0
        public int LoadWave(String fileName, bool needclose) // метод получения заголовка
        {
            StopPlayback();
            int result = 1;

            if (System.IO.File.Exists(fileName))
            {
                String extension = System.IO.Path.GetExtension(fileName).ToLower();                // получение пути к файлу

                switch (extension)                                                                 // чтение файла в зависимости от расширения
                {
                case ".mp3": reader = new NAudio.Wave.Mp3FileReader(fileName); result = 0; break;  // чтение mp3 файла

                case ".wav": reader = new NAudio.Wave.WaveFileReader(fileName); result = 0; break; // чтение wav файла

                default: break;
                }
            }
            if (reader != null)
            {
                waveFormat    = reader.WaveFormat.ToString();    // получение формата файла
                blockAlign    = reader.BlockAlign;               // получение размера блока выравнивания
                totalTime     = reader.TotalTime.TotalSeconds;   // получение длительности файла в секундах
                sampleRate    = reader.WaveFormat.SampleRate;    // получение частоты дискретизации
                bitsPerSample = reader.WaveFormat.BitsPerSample; // получение битового разрешения
                channels      = reader.WaveFormat.Channels;      // получение числа каналов

                if (needclose)
                {
                    reader.Close(); reader.Dispose();
                }                                                    // завершение чтение и освобождение памяти
            }
            return(result);
        }
コード例 #2
0
        private static void mp3izza(string nomefile, string nomefilemp3)
        {
            WaveStream filewav = new WaveStream(nomefile);
            //      try
            //      {
            Mp3Writer salvamp3 = new Mp3Writer(new FileStream(nomefilemp3,
                                                              FileMode.Create), filewav.Format);

            //          try
            //          {
            byte[] buff = new byte[salvamp3.OptimalBufferSize];
            int    read = 0;

            while ((read = filewav.Read(buff, 0, buff.Length)) > 0)
            {
                salvamp3.Write(buff, 0, read);
            }
            //         }
            //         finally
            //         {
            salvamp3.Close();
            //         }
            //     }
            //     finally
            //     {
            filewav.Close();
            //     }
            File.Delete(nomefile);
        }
コード例 #3
0
 private void StopAndCloseStream()
 {
     if (waveOutDevice != null)
     {
         waveOutDevice.Stop();
         waveOutDevice.Dispose();
     }
     if (activeStream != null)
     {
         ActiveStream.Close();
         ActiveStream.Dispose();
         ActiveStream = null;
     }
     if (waveOutDevice != null)
     {
         waveOutDevice.Dispose();
         waveOutDevice = null;
     }
     if (inputStream != null)
     {
         inputStream.Close();
         inputStream.Dispose();
         inputStream = null;
     }
 }
コード例 #4
0
        /// <summary>
        /// Unloads the sound
        /// </summary>
        /// <returns></returns>
        public override bool Unload()
        {
            if (Filename == "")
            {
                return(true);
            }

            if (mWaveOut != null)
            {
                mWaveOut.Stop();
            }

            if (mWaveStream != null)
            {
                mWaveStream.Close();
                mWaveStream = null;
            }

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

            return(true);
        }
コード例 #5
0
 void DestroyReader()
 {
     if (HasReader)
     {
         reader.Close(); reader.Dispose(); reader = null;
     }
 }
コード例 #6
0
 private void Dispose()
 {
     waveOut.Pause();
     waveOut.Dispose();
     blockAlignedStream.Close();
     blockAlignedStream.Dispose();
 }
コード例 #7
0
ファイル: WaveformService.cs プロジェクト: jrocket/MOG
        public Bitmap GetWaveform(string filename, Stream inputStream)
        {
            WaveStream reader = getReader(filename, inputStream);

            List <float> data = null;


            if (reader is Mp3FileReader)
            {
                long   sizeOfStream = reader.Length;
                byte[] stream       = new byte[sizeOfStream];
                reader.Read(stream, 0, (int)sizeOfStream);
                data = getMp3WaveForm(stream, sizeOfStream);
                reader.Close();
            }
            else
            {// we have a wav file reader
                data = getWavWaveForm(reader as WaveFileReader);
            }



            Bitmap image = DrawNormalizedAudio(data, this.ForegroundColor, this.BackgroundColor, new Size(this.Width, this.Height));

            return(image);
        }
コード例 #8
0
ファイル: Form1.cs プロジェクト: 4dvn/yeti
 private void buttonInFile_Click(object sender, System.EventArgs e)
 {
     if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
     {
         try
         {
             WaveStream s = new WaveStream(openFileDialog1.FileName);
             try
             {
                 m_Config            = new Mp3WriterConfig(s.Format);
                 textBoxInFile.Text  = openFileDialog1.FileName;
                 textBoxOutFile.Text = System.IO.Path.ChangeExtension(textBoxInFile.Text, ".mp3");
             }
             finally
             {
                 s.Close();
             }
         }
         catch
         {
             MessageBox.Show(this, "Invalid wave file or format", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
             textBoxInFile.Text  = "";
             textBoxOutFile.Text = "";
         }
     }
 }
コード例 #9
0
        protected override void Dispose(bool disposing)
        {
            if (Disposed)
            {
                return;
            }

            if (IsPlaying)
            {
                Stop();
            }

            if (disposing)
            {
                if (_player != null)
                {
                    _player.PlaybackStopped -= PlaybackStopped;
                    _player?.Dispose();
                    _player = null;
                }

                if (_reader != null)
                {
                    _reader?.Close();
                    _reader?.Dispose();
                    _reader = null;
                }
                // Free any other managed objects here.
            }

            // Free any unmanaged objects here.
            Disposed = true;
        }
コード例 #10
0
ファイル: FormMain.cs プロジェクト: VPKSoft/amp
    /// <summary>
    /// Stops the playback, cleans and disposes of the objects used for the playback.
    /// </summary>
    private void CloseWaveOut()
    {
        waveOutDevice?.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();

            // dispose the main memory stream in case one is assigned..
            mainMemoryStream?.Dispose();

            mainMemoryStream = null;
            mainOutputStream = null;
        }

        if (waveOutDevice != null)
        {
            waveOutDevice.Dispose();
            waveOutDevice = null;
        }
    }
コード例 #11
0
 private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
 {
     if (audioStream != null)
     {
         audioStream.Close();
     }
 }
コード例 #12
0
 /// ------------------------------------------------------------------------------------
 private void CloseAndDisposeWaveStreamIfNeeded()
 {
     if (WaveStream != null)
     {
         WaveStream.Close();
         WaveStream.Dispose();
     }
 }
コード例 #13
0
 private void DisposeReader()
 {
     if (reader != null)
     {
         reader.Close();
         reader.Dispose();
         reader = null;
     }
 }
コード例 #14
0
 public void Stop()
 {
     Output.Stop();
     Stream.Close();
     Stream.Dispose();
     Stream = null;
     Output = new WaveOut();
     timer1.Stop();
     timer1.Enabled = false;
 }
コード例 #15
0
 private void DJDemo_FormClosing(object sender, FormClosingEventArgs e)
 {
     sensors.Disconnect();
     music.Volume = 1;
     music.Stop();
     music.Dispose();
     baStream.Dispose();
     wavStream.Close();
     song.Close();
 }
コード例 #16
0
        private void Close(object sender, EventArgs e)
        {
            _trayIcon.Visible = false;
            _trayIcon.Dispose();

            Application.ExitThread();
            Application.Exit();

            _waveStream.Close();
            _soundPlayer.Dispose();
        }
コード例 #17
0
ファイル: WaveFileAudioSource.cs プロジェクト: s76/Accord.NET
        /// <summary>
        ///   Worker thread.
        /// </summary>
        ///
        private void WorkerThread()
        {
            WaveStream waveStream = null;

            try
            {
                waveStream = (stream != null) ?
                             new WaveStream(stream) : new WaveStream(fileName);

                // Open the Wave stream
                decoder.Open(waveStream);

                while (stopEvent.WaitOne(0, false))
                {
                    // get next frame
                    Signal s = decoder.Decode(frameSize);
                    framesReceived += s.Length;
                    bytesReceived  += decoder.Bytes;

                    if (NewFrame != null)
                    {
                        NewFrame(this, new NewFrameEventArgs(s));
                    }

                    // check current position
                    if (waveStream.Position >= waveStream.Length)
                    {
                        break;
                    }

                    // sleeping ...
                    Thread.Sleep(100);
                }
            }
            catch (Exception exception)
            {
                // provide information to clients
                if (AudioSourceError != null)
                {
                    AudioSourceError(this, new AudioSourceErrorEventArgs(exception.Message));
                }
                else
                {
                    throw;
                }
            }

            if (waveStream != null)
            {
                waveStream.Close();
                waveStream.Dispose();
                waveStream = null;
            }
        }
コード例 #18
0
 public static void ConvertA4MToWav(string inPath, string outPath)
 {
     using (var mm = new MediaFoundationReader(inPath))
     {
         using (WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(mm))
         {
             WaveFileWriter.CreateWaveFile(outPath, pcm);
             pcm.Close();
         }
     }
 }
コード例 #19
0
 public static void ConvertMp3ToWav(Stream audioFromGoogle, string _outPath_)
 {
     using (Mp3FileReader mp3 = new Mp3FileReader(audioFromGoogle))
     {
         using (WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(mp3))
         {
             WaveFileWriter.CreateWaveFile(_outPath_, pcm);
             pcm.Close();
         }
     }
 }
コード例 #20
0
        public static void ConvertWavToMp3(string wav, string mp3)
        {
            Mp3WriterConfig m_Config = null;
            WaveStream      InStr    = new WaveStream(wav);

            m_Config = new Mp3WriterConfig(InStr.Format);
            m_Config.Mp3Config.format.mp3.bOriginal = 80;

            try
            {
                Mp3Writer writer = new Mp3Writer(new FileStream(mp3, FileMode.Create), m_Config);

                try
                {
                    byte[] buff   = new byte[writer.OptimalBufferSize];
                    int    read   = 0;
                    int    actual = 0;
                    long   total  = InStr.Length;

                    try
                    {
                        while ((read = InStr.Read(buff, 0, buff.Length)) > 0)
                        {
                            writer.Write(buff, 0, read);
                            actual += read;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    writer.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                InStr.Close();
            }
        }
コード例 #21
0
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            if (WaveStream != null)
            {
                WaveStream.Close();
            }

            base.Dispose(disposing);
        }
コード例 #22
0
ファイル: AudioManager.cs プロジェクト: Mechanolith/LaP-Test
    /// <summary>
    /// Clears the Wave Stream of all data.
    /// </summary>
    public void UnloadAudio()
    {
        waveOut.Stop();

        volumeStream.Close();
        volumeStream = null;

        waveOutputStream.Close();
        waveOutputStream = null;

        waveOut.Dispose();
        waveOut = null;
    }
コード例 #23
0
 /// <summary>
 /// Disposes this AudioFileReader
 /// </summary>
 /// <param name="disposing">True if called from Dispose</param>
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (readerStream != null)
         {
             readerStream.Close();
             readerStream.Dispose();
             readerStream = null;
         }
     }
     base.Dispose(disposing);
 }
コード例 #24
0
        public void Dispose(bool disposing)
        {
            if (!hasDisposed)
            {
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }
            }

            hasDisposed = disposing;
        }
コード例 #25
0
 // When soundboard sound stops. Cleans up memory.
 private void WaveOut_PlaybackStopped(object sender, StoppedEventArgs e)
 {
     if (waveStream != null)
     {
         waveStream.Close();
         waveStream.Dispose();
     }
     if (waveOut != null)
     {
         waveOut.Dispose();
     }
     GC.Collect();
 }
コード例 #26
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        string     SavePath     = HttpContext.Current.Server.MapPath(string.Format("~/App_Data/"));
        Stream     sourceStream = null;
        WaveStream audioStream  = null;
        //create an empty stream to receive the extracted message
        MemoryStream messageStream = new MemoryStream();
        //open the key file
        Stream keyStream = new FileStream(SavePath + "hash.txt", FileMode.Open);

        try
        {
            //open the carrier file
            sourceStream = FileUpload1.PostedFile.InputStream;
            audioStream  = new WaveStream(sourceStream);
            WaveUtility utility = new WaveUtility(audioStream);

            //exctract the message from the carrier wave
            utility.Extract(messageStream, keyStream);

            messageStream.Seek(0, SeekOrigin.Begin);

            { //display result
                Label1.Text = new StreamReader(messageStream).ReadToEnd();
            }
        }
        catch (Exception ex)
        {
        }
        finally
        {
            if (keyStream != null)
            {
                keyStream.Close();
            }
            if (messageStream != null)
            {
                messageStream.Close();
            }
            if (audioStream != null)
            {
                audioStream.Close();
            }
            if (sourceStream != null)
            {
                sourceStream.Close();
            }
        }
    }
コード例 #27
0
ファイル: AudioPlayer.cs プロジェクト: imaGuru/music_player
 private void CloseTrack()
 {
     if (waveOutDevice != null)
     {
         waveOutDevice.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;
     }
 }
コード例 #28
0
 /// <summary>
 /// dispose the waveout and audiofilereader
 /// </summary>
 private void DisposeEvent()
 {
     Stop();
     if (waveStream != null)
     {
         inputStream.Close();
         inputStream = null;
         waveStream.Close();
         waveStream = null;
     }
     if (waveoutPlayer != null)
     {
         waveoutPlayer.Dispose();
         waveoutPlayer = null;
     }
 }
コード例 #29
0
        public void Dispose()
        {
            if (_device != null)
            {
                _device.Stop();
                _device.Dispose();
                _device = null;
            }
            if (_waveStream != null)
            {
                _waveStream.Close();
                _waveStream = null;
            }

            GC.Collect();
        }
コード例 #30
0
 private void CloseCurrentFile()
 {
     try
     {
         // this one really closes the file and ACM conversion
         volumeStream.Close();
         volumeStream.Dispose();
     }
     finally { volumeStream = null; }
     try
     {
         // this one does the metering stream
         mainOutputStream.Close();
         mainOutputStream.Dispose();
     }
     finally { mainOutputStream = null; }
 }
コード例 #31
0
        /// <summary>
        /// Initializes a new WaveOutAudioSource class.
        /// </summary>
        /// <param name="waveStream">The WaveStream.</param>
        internal WaveOutAudioSource(WaveStream waveStream)
        {
            waveStream.Seek(0, SeekOrigin.Begin);
            WaveData = new byte[waveStream.Length];
            waveStream.Read(WaveData, 0, WaveData.Length);
            waveStream.Close();
            WaveFormat = waveStream.Format;

            if (WaveFormat.Channels == 1) //try to convert to stereo for full audiomixer support
            {
                try
                {
                    new MonoToStereoConverter().ConvertAudioData(WaveData, ref WaveFormat);
                }
                catch (NotSupportedException)
                {
                }
            }
        }
コード例 #32
0
        private void DoAnalysis()
        {
            WaveStream stream;
            Exception exception;
            try
            {
                stream = new WaveStream(File.Open(fileName, FileMode.Open, FileAccess.Read));
            }
            catch (Exception exception1)
            {
                exception = exception1;
                ui.ShowMessage(exception.Message);
                return;
            }
            try
            {
                try
                {
                    ResetStatistics();

                    onlineFlag = onlineFlag = "---";

                    int cStartPosSec = 0;
                    int cEndPosSec = 0;
                    int segmentID = 0;
                    Array inpBuf = new short[bufferSize];

                    DateTime startProcessingTime = DateTime.Now;

                    while (ReadBuffer(stream, (short[]) inpBuf) > 0)
                    {

                        ProcessBuffer(ref inpBuf, ref segmentID, ref cEndPosSec, ref cStartPosSec);
                    }

                    DateTime endProcessingTime = DateTime.Now;

                    TimeSpan processingTime = endProcessingTime - startProcessingTime;

                    UpdateCallProfile(segmentID, processingTime);
                    AnalyzeConversationBorders();
                    UpdateTestsDatabase(processingTime, segmentID, (double)avgVoiceEnergy / segmentID);
                }
                catch (Exception exception2)
                {
                    exception = exception2;
                    ui.ShowMessage(exception.Message + Environment.NewLine + exception.StackTrace);
                }
            }
            finally
            {
                stream.Close();
                ui.UnFreezTables();

                if (!processingBatch)
                    ui.ShowMessage("Done");
            }
        }
コード例 #33
0
ファイル: WaveForm.cs プロジェクト: litdev1/LitDev
        private static string _PlayWavFile(string fileName, double duration)
        {
            try
            {
                Initialise();

                WaveStream waveFile = new WaveStream(fileName);
                SoundBufferDescription soundBufferDescription = new SoundBufferDescription();
                soundBufferDescription.Format = waveFile.Format;
                soundBufferDescription.Flags = BufferFlags.Defer | BufferFlags.ControlVolume | BufferFlags.ControlPan;
                soundBufferDescription.SizeInBytes = (int)waveFile.Length;

                SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(directSound, soundBufferDescription);
                secondarySoundBuffer.Pan = pan;
                secondarySoundBuffer.Volume = volume;

                byte[] rawsamples = new byte[soundBufferDescription.SizeInBytes];
                waveFile.Read(rawsamples, 0, soundBufferDescription.SizeInBytes);
                waveFile.Close();
                secondarySoundBuffer.Write(rawsamples, 0, LockFlags.EntireBuffer);

                string name = NextName();
                Buffer buffer = new Buffer(name, secondarySoundBuffer, 0, duration);
                buffers.Add(buffer);

                Thread thread = new Thread(new ParameterizedThreadStart(DoPlay));
                thread.Start(buffer);
                if (!bAsync) thread.Join();
                return name;
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                return "";
            }
        }