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); }
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); }
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; } }
/// <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); }
void DestroyReader() { if (HasReader) { reader.Close(); reader.Dispose(); reader = null; } }
private void Dispose() { waveOut.Pause(); waveOut.Dispose(); blockAlignedStream.Close(); blockAlignedStream.Dispose(); }
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); }
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 = ""; } } }
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; }
/// <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; } }
private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { if (audioStream != null) { audioStream.Close(); } }
/// ------------------------------------------------------------------------------------ private void CloseAndDisposeWaveStreamIfNeeded() { if (WaveStream != null) { WaveStream.Close(); WaveStream.Dispose(); } }
private void DisposeReader() { if (reader != null) { reader.Close(); reader.Dispose(); reader = null; } }
public void Stop() { Output.Stop(); Stream.Close(); Stream.Dispose(); Stream = null; Output = new WaveOut(); timer1.Stop(); timer1.Enabled = false; }
private void DJDemo_FormClosing(object sender, FormClosingEventArgs e) { sensors.Disconnect(); music.Volume = 1; music.Stop(); music.Dispose(); baStream.Dispose(); wavStream.Close(); song.Close(); }
private void Close(object sender, EventArgs e) { _trayIcon.Visible = false; _trayIcon.Dispose(); Application.ExitThread(); Application.Exit(); _waveStream.Close(); _soundPlayer.Dispose(); }
/// <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; } }
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(); } } }
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(); } } }
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(); } }
/// <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); }
/// <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; }
/// <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); }
public void Dispose(bool disposing) { if (!hasDisposed) { if (reader != null) { reader.Close(); reader.Dispose(); } } hasDisposed = disposing; }
// 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(); }
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(); } } }
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; } }
/// <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; } }
public void Dispose() { if (_device != null) { _device.Stop(); _device.Dispose(); _device = null; } if (_waveStream != null) { _waveStream.Close(); _waveStream = null; } GC.Collect(); }
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; } }
/// <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) { } } }
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"); } }
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 ""; } }