//########################################################################################################################################################################################################## /// <summary> /// Save all samples to a new WAV file /// </summary> /// <param name="filepath">filepath of the new WAV file</param> public void SaveFile(string filepath) { if (Samples == null || format == null) { return; } if (!File.Exists(filepath)) { FileStream stream = File.Create(filepath); stream.Close(); } else { File.Delete(filepath); } WaveWriter writer = new WaveWriter(filepath, format); foreach (AudioSample s in Samples) { writer.WriteSample(s.Value); } writer.Dispose(); }
private void PhotonVoiceCreated(PhotonVoiceCreatedParams photonVoiceCreatedParams) { VoiceInfo voiceInfo = photonVoiceCreatedParams.Voice.Info; int bitsPerSample = 32; if (photonVoiceCreatedParams.Voice is LocalVoiceAudioShort) { bitsPerSample = 16; } string filePath = this.GetFilePath(); this.wavWriter = new WaveWriter(filePath, new WaveFormat(voiceInfo.SamplingRate, bitsPerSample, voiceInfo.Channels)); if (this.Logger.IsInfoEnabled) { this.Logger.LogInfo("Outgoing stream, output file path: {0}", filePath); } if (photonVoiceCreatedParams.Voice is LocalVoiceAudioFloat) { LocalVoiceAudioFloat localVoiceAudioFloat = photonVoiceCreatedParams.Voice as LocalVoiceAudioFloat; localVoiceAudioFloat.AddPreProcessor(new OutgoingStreamSaverFloat(this.wavWriter)); } else if (photonVoiceCreatedParams.Voice is LocalVoiceAudioShort) { LocalVoiceAudioShort localVoiceAudioShort = photonVoiceCreatedParams.Voice as LocalVoiceAudioShort; localVoiceAudioShort.AddPreProcessor(new OutgoingStreamSaverShort(this.wavWriter)); } }
public void Test16BitSingleChannelRoundTrip() { const int samplesPerSecond = 44_100; const double delta = 1.0 / samplesPerSecond; Func <double, double> func = (double t) => Math.Cos(2.0 * Math.PI * t); short[] data = new short[samplesPerSecond]; for (int i = 0; i < samplesPerSecond; ++i) { data[i] = (short)(short.MaxValue * func(i * delta)); } using var ms = new MemoryStream(); var writer = new WaveWriter(ms, samplesPerSecond); writer.Write(data.Length, data); ms.Position = 0; var reader = new WaveReader(ms); Assert.AreEqual(reader.Format.Channels, 1); Assert.AreEqual(reader.Format.SamplesPerSecond, samplesPerSecond); Assert.AreEqual(reader.Format.BitsPerSample, 16); var channel = reader.GetChannelInt16(0); int h = 0; var e = channel.GetEnumerator(); while (e.MoveNext()) { Assert.AreEqual(data[h++], e.Current, $"Index: {h}"); } }
private void btnStartStop_Click(object sender, EventArgs e) { if (!recording) { btnStartStop.Text = "Stop"; writer = new WaveWriter(textOutputFile.Text, capture.WaveFormat); capture.Start(); recording = true; recordTime = new TimeSpan(); recordTimer.Enabled = true; btnSelectDevice.Enabled = false; Console.WriteLine("Started recording"); } else { btnStartStop.Text = "Start!"; capture.Stop(); writer.Dispose(); recording = false; recordTimer.Enabled = false; btnSelectDevice.Enabled = true; Console.WriteLine("Stopped recording"); } }
public void LoadFile(AudioData audioData, IFileFormat fileFormat) { AudioFileFormats.Add(fileFormat); //Load Channel Info AudioFile file = new AudioFile(); file.Title = fileFormat.FileName; if (fileFormat is VGAdudioFile) { file.vgAdudioFile = (VGAdudioFile)fileFormat; } //Loop through each channel and set it's own var format = audioData.GetAllFormats().ToArray()[0]; for (int c = 0; c < format.ChannelCount; c++) { using (var memWav = new MemoryStream()) { AudioChannel audioChannel = new AudioChannel(); audioChannel.Name = $"Channel [{c}]"; file.Channels.Add(audioChannel); //Load data and write to stream var audio = format.GetChannels(c).ToPcm16(); var writer = new WaveWriter(); writer.WriteToStream(audio, memWav); audioChannel.Data = memWav.ToArray(); memWav.Position = 0; //Load the player audioChannel.audioPlayer.Open(new MemoryStream(audioChannel.Data), "wav", activeDevice); /* OpenFileDialog openFileDialog = new OpenFileDialog(); * if (openFileDialog.ShowDialog() == DialogResult.OK) * { * audioChannel.audioPlayer.Open(openFileDialog.FileName, activeDevice); * }*/ audioChannel.audioPlayer.PlaybackStopped += (s, args) => { //WasapiOut uses SynchronizationContext.Post to raise the event //There might be already a new WasapiOut-instance in the background when the async Post method brings the PlaybackStopped-Event to us. if (audioChannel.audioPlayer.PlaybackState != PlaybackState.Stopped) { } }; } } audioListView.AddObject(file); if (audioListView.Items.Count != 0) { audioListView.SelectedIndex = 0; } }
public void WriteSamplesToFile(float[] samples, int sampleRate, string destination) { var waveWriter = new WaveWriter(destination, BassConstants.NumberOfChannels, sampleRate, BitsPerSample, true); waveWriter.Write(samples, samples.Length * FloatLength); waveWriter.Close(); }
/// <summary> /// Stop Recording /// </summary> /// <returns>Successful</returns> public bool Stop() { if (!isRecording) { return(false); } // Stop Capturing Audio if (recordAudio) { audioSource.Stop(); if (audioSource != null) { audioSource.Dispose(); audioSource = null; } if (audioFile != null) { audioFile.Dispose(); audioFile = null; } } // Kill Timers StopTimers(); status = "Idle"; isRecording = false; return(isRecording); }
public void WriteSamplesToFile(float[] samples, int sampleRate, string destination) { var waveWriter = new WaveWriter( destination, BassConstants.NumberOfChannels, sampleRate, BitsPerSample, true); waveWriter.Write(samples, samples.Length * FloatLength); waveWriter.Close(); }
internal static void RecordToWav(string fileName) { using (WasapiCapture capture = new WasapiLoopbackCapture()) { //if nessesary, you can choose a device here //to do so, simply set the device property of the capture to any MMDevice //to choose a device, take a look at the sample here: http://cscore.codeplex.com/ //initialize the selected device for recording capture.Initialize(); //create a wavewriter to write the data to using (WaveWriter w = new WaveWriter(fileName, capture.WaveFormat)) { //setup an eventhandler to receive the recorded data capture.DataAvailable += (s, e) => { //save the recorded audio w.Write(e.Data, e.Offset, e.ByteCount); Console.Write("."); }; //start recording capture.Start(); Console.ReadKey(); //stop recording capture.Stop(); } } }
/// <summary> /// Recode the file /// </summary> /// <param name = "fileName">Initial file</param> /// <param name = "outFileName">Target file</param> /// <param name = "targetSampleRate">Target sample rate</param> public void RecodeTheFile(string fileName, string outFileName, int targetSampleRate) { int stream = Un4seen.Bass.Bass.BASS_StreamCreateFile(fileName, 0, 0, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT); TAG_INFO tags = new TAG_INFO(); BassTags.BASS_TAG_GetFromFile(stream, tags); int mixerStream = BassMix.BASS_Mixer_StreamCreate(targetSampleRate, 1, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT); if (BassMix.BASS_Mixer_StreamAddChannel(mixerStream, stream, BASSFlag.BASS_MIXER_FILTER)) { WaveWriter waveWriter = new WaveWriter(outFileName, mixerStream, true); const int length = 5512 * 10 * 4; float[] buffer = new float[length]; while (true) { int bytesRead = Un4seen.Bass.Bass.BASS_ChannelGetData(mixerStream, buffer, length); if (bytesRead == 0) { break; } waveWriter.Write(buffer, bytesRead); } waveWriter.Close(); } else { throw new Exception(Un4seen.Bass.Bass.BASS_ErrorGetCode().ToString()); } }
/// <summary> /// Save float buffer as ieefloat wave file /// </summary> /// <param name="buffer">float array</param> /// <param name="outFileName">filename</param> /// <param name="targetSampleRate">target samplerate </param> public void SaveFile(float[] buffer, string outFileName, int targetSampleRate) { WaveWriter writer = new WaveWriter(outFileName, 1, targetSampleRate, 32, true); writer.Write(buffer, buffer.Length << 2); writer.Close(); }
private void btnConvert_Click(object sender, EventArgs e) { if (newFormat == IntPtr.Zero) { MessageBox.Show("Please, specify destination format for converting"); return; } string fileName = tbFile2.Text + ".wav"; int size = ar.Milliseconds2Bytes(1000); int len = ar.GetLengthInBytes(); AcmConverter ac = new AcmConverter(oldFormat, newFormat, false); FileStream fs = new FileStream(fileName, FileMode.Create); WaveWriter ww = new WaveWriter(fs, AudioCompressionManager.FormatBytes(newFormat)); pbConvert.Maximum = len; int y = 0; while (y < len) { pbConvert.Value = y; byte[] data = ar.ReadDataInBytes(y, size); if (data.Length == 0) { break; } y += data.Length; byte[] newData = ac.Convert(data); ww.WriteData(newData); } ww.Close(); ar.Close(); gbConvert.Enabled = false; btnMakeMp3.Enabled = tbFile2.Text.ToLower().EndsWith(".wav"); OpenContainingFolder(fileName); }
/// <summary> /// データ wave の書き込み。 /// </summary> /// <param name="filename">ファイル名</param> public void WirteData(string filename) { using (WaveWriter writer = new WaveWriter(filename, this.data.Header)) { writer.Write(this.data.TimeL, this.data.TimeR); } }
private void WriteSamplesToWavFile(string pathToFile, int sampleRate, int channels, float[] samples) { WaveWriter waveWriter = new WaveWriter(pathToFile, channels, sampleRate, 8 * 4, true); waveWriter.Write(samples, samples.Length * 4); waveWriter.Close(); }
static void Main(string[] args) { using (var wasapiCapture = new WasapiLoopbackCapture()) { wasapiCapture.Initialize(); var wasapiCaptureSource = new SoundInSource(wasapiCapture); using (var stereoSource = wasapiCaptureSource.ToStereo()) { //using (var writer = MediaFoundationEncoder.CreateWMAEncoder(stereoSource.WaveFormat, "output.wma")) using (var writer = new WaveWriter("output.wav", stereoSource.WaveFormat)) { byte[] buffer = new byte[stereoSource.WaveFormat.BytesPerSecond]; wasapiCaptureSource.DataAvailable += (s, e) => { int read = stereoSource.Read(buffer, 0, buffer.Length); writer.Write(buffer, 0, read); }; wasapiCapture.Start(); Console.ReadKey(); wasapiCapture.Stop(); } } } }
public async Task <MemoryStream> GetLoopbackAudio(int ms) { var Stream = new MemoryStream(); using (WasapiCapture virtualaudiodev = new WasapiLoopbackCapture()) { virtualaudiodev.Initialize(); var soundInSource = new SoundInSource(virtualaudiodev) { FillWithZeros = false }; var convertedSource = soundInSource.ChangeSampleRate(44100).ToSampleSource().ToWaveSource(16); using (convertedSource = convertedSource.ToMono()) { using (var waveWriter = new WaveWriter(Stream, convertedSource.WaveFormat)) { soundInSource.DataAvailable += (s, e) => { var buffer = new byte[convertedSource.WaveFormat.BytesPerSecond / 2]; int read; while ((read = convertedSource.Read(buffer, 0, buffer.Length)) > 0) { waveWriter.Write(buffer, 0, read); } }; virtualaudiodev.Start(); Thread.Sleep(ms); virtualaudiodev.Stop(); } } } return(Stream); }
private void StartRecord() { using (WasapiCapture capture = new WasapiLoopbackCapture()) { //if nessesary, you can choose a device here //to do so, simply set the device property of the capture to any MMDevice //to choose a device, take a look at the sample here: http://cscore.codeplex.com/ //initialize the selected device for recording capture.Initialize(); //create a wavewriter to write the data to using (var stream = new FileStream("dump.wav", FileMode.CreateNew)) { using (var w = new WaveWriter(stream, capture.WaveFormat)) { //setup an eventhandler to receive the recorded data capture.DataAvailable += (s, args) => { //save the recorded audio w.Write(args.Data, args.Offset, args.ByteCount); }; //start recording capture.Start(); SpinWait.SpinUntil(() => !_recording); //stop recording capture.Stop(); } stream.Flush(true); } } }
public bool stopRecording() { bool isStopped = false; if (System.Web.HttpContext.Current.Session[ww] != null && System.Web.HttpContext.Current.Session[wc] != null) { capture = (WasapiCapture)System.Web.HttpContext.Current.Session[wc]; w = (WaveWriter)System.Web.HttpContext.Current.Session[ww]; //stop recording capture.Stop(); w.Dispose(); w = null; capture.Dispose(); capture = null; System.Web.HttpContext.Current.Session[ww] = null; System.Web.HttpContext.Current.Session[wc] = null; //Label1.Text = "Stopped"; } else { isStopped = true; } return(isStopped); }
public NaudioDemo() { using (WasapiCapture capture = new WasapiLoopbackCapture()) { //if nessesary, you can choose a device here //to do so, simply set the device property of the capture to any MMDevice //to choose a device, take a look at the sample here: http://cscore.codeplex.com/ //initialize the selected device for recording capture.Initialize(); //create a wavewriter to write the data to using (WaveWriter w = new WaveWriter("dump.wav", capture.WaveFormat)) { //setup an eventhandler to receive the recorded data capture.DataAvailable += (s, e) => { //save the recorded audio w.Write(e.Data, e.Offset, e.ByteCount); }; //start recording capture.Start(); Thread.Sleep(1000); //stop recording capture.Stop(); } } }
public void SaveData() { // TODO: Add support for other formats (see: OutputFormat) byte[] dataA, dataB; if (storeInMemoryUntilSave) { dataA = (currentFile == 0 ? channelMemoryB : channelMemoryA).ToArray(); dataB = (currentFile == 1 ? channelMemoryB : channelMemoryA).ToArray(); } else { var bytesA = Utility.ReadToEnd((currentFile == 0) ? channelStreamB : channelStreamA); var bytesB = Utility.ReadToEnd((currentFile == 1) ? channelStreamB : channelStreamA); dataA = bytesA.Skip(44).ToArray(); dataB = bytesB.Skip(44).ToArray(); } var saveDirectory = Config.SavePath.FullName + "/" + channelName + "/"; if (!Directory.Exists(saveDirectory)) { Directory.CreateDirectory(saveDirectory); } using (var writer = new WaveWriter(saveDirectory + DateTime.Now.ToString(Config.SaveNameFormat) + ".wav", channelCapture.WaveFormat)) { writer.Write(dataA, 0, dataA.Length); writer.Write(dataB, 0, dataB.Length); } }
public void Dispose() { if (_waveWriter != null) { _waveWriter.Dispose(); _waveWriter = null; } if (_notificationSource != null) { _notificationSource.Dispose(); _notificationSource = null; } if (_waveSource != null) { _waveSource.Dispose(); _waveSource = null; } if (_soundInSource != null) { _soundInSource.Dispose(); _soundInSource = null; } if (_capture != null) { _capture.Dispose(); _capture = null; } }
public void CSCoreAudioRecording() { using (capture = new WasapiLoopbackCapture()) { aTimer = new Timer(); aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); //jak czas minie, wyłącz nagrywanie aTimer.Interval = 8000; //czas nagrywania //inicjalizacja urządzenia do nagrywania capture.Initialize(); using (writer = new WaveWriter("dump.wav", capture.WaveFormat)) { capture.DataAvailable += (s, e) => { //save the recorded audio writer.Write(e.Data, e.Offset, e.ByteCount); }; //start recording capture.Start(); aTimer.Enabled = true; Console.WriteLine("Rozpoczęto nagrywanie."); Console.ReadKey(); } } }
/// <summary> /// Writes all audio data of the <paramref name="source" /> to the <paramref name="stream" />. /// </summary> /// <param name="source">Source which provides the audio data to write to the <paramref name="stream" />.</param> /// <param name="stream"><see cref="Stream" /> to store the audio data in.</param> /// <exception cref="System.ArgumentNullException"> /// source /// or /// stream /// </exception> /// <exception cref="System.ArgumentException">Stream is not writeable.;stream</exception> public static void WriteToWaveStream(this IWaveSource source, Stream stream) { if (source == null) { throw new ArgumentNullException("source"); } if (stream == null) { throw new ArgumentNullException("stream"); } if (!stream.CanWrite) { throw new ArgumentException("Stream is not writeable.", "stream"); } using (var writer = new WaveWriter(stream, source.WaveFormat)) { int read; var buffer = new byte[source.WaveFormat.BytesPerSecond]; while ((read = source.Read(buffer, 0, buffer.Length)) > 0) { writer.Write(buffer, 0, read); } } }
/// <summary> /// Decode File /// </summary> /// <param name="file"></param> /// <returns></returns> public bool DecodeFile() { try { if (!string.IsNullOrEmpty(CurrentFile)) { _chunkSize = 4096; // Set Default Chunk Size if (CurrentFile.ToLower().Contains(".mp3")) // Check Mp3 { if (System.IO.File.Exists(CurrentFile)) // Check File Exists { CurrentFileName = System.IO.Path.GetFileName(CurrentFile); using (var mp3Stream = new Mp3Sharp.Mp3Stream(CurrentFile)) { // Create Mp3 Stream _mp3Stream = mp3Stream; // Set Mp3 Stream _bytes = new byte[mp3Stream.Length]; // Set Bytes _totalBytes = mp3Stream.Length; // Set Total Bytes _numBytesToRead = _totalBytes; // Set Num Bytes to Read _numBytesRead = 0; // Set Num Bytes Read to 0 using (var writer = new WaveWriter(CurrentFile.Replace(".mp3", ".wav"))) { // Create Writer _writer = writer; // Set Writer while (_numBytesToRead > 0) // Loop through Chunks { if (_chunkSize > _numBytesToRead) // Check Progress isn't greater than remaining bytes { _chunkSize = 1; // Check a chunk at a time } var t = new Thread(ReadDecodeChunk); t.Start(); if (!t.Join(1500)) { t.Abort(); // Oops! We read 1 too many bytes! Lets stop trying, we got everything. _numBytesToRead = 0; // This should take us out of the loop soon } if (_readDecodeResult == 0) { break; } _numBytesRead += _readDecodeResult; _numBytesToRead -= _readDecodeResult; _percent = ((int)_numBytesRead * 100 / _totalBytes); if (PercentChanged != null) { PercentChanged(_percent); } } _writer = null; writer.Close(); writer.Dispose(); } _numBytesToRead = _bytes.Length; _mp3Stream = null; } } } } return(true); } catch { throw; } }
public void WriteSamplesToWaveFile(string pathToFile, float[] samples, int sampleRate) { const int BitsPerSample = 4 * 8; var waveWriter = new WaveWriter(pathToFile, BassConstants.NumberOfChannels, sampleRate, BitsPerSample, true); waveWriter.Write(samples, samples.Length * 4); waveWriter.Close(); }
public static int Capture(string output_file, int time) { int sampleRate = 48000; int bitsPerSample = 24; //create a new soundIn instance using (WasapiCapture soundIn = new WasapiLoopbackCapture()) { //initialize the soundIn instance soundIn.Initialize(); //create a SoundSource around the the soundIn instance SoundInSource soundInSource = new SoundInSource(soundIn) { FillWithZeros = false }; //create a source, that converts the data provided by the soundInSource to any other format IWaveSource convertedSource = soundInSource .ChangeSampleRate(sampleRate) // sample rate .ToSampleSource() .ToWaveSource(bitsPerSample); //bits per sample //channels... using (convertedSource = convertedSource.ToStereo()) { //create a new wavefile using (WaveWriter waveWriter = new WaveWriter(output_file, convertedSource.WaveFormat)) { //register an event handler for the DataAvailable event of the soundInSource soundInSource.DataAvailable += (s, e) => { //read data from the converedSource byte[] buffer = new byte[convertedSource.WaveFormat.BytesPerSecond / 2]; int read; //keep reading as long as we still get some data while ((read = convertedSource.Read(buffer, 0, buffer.Length)) > 0) { //write the read data to a file waveWriter.Write(buffer, 0, read); } }; //start recording soundIn.Start(); //delay and keep recording Thread.Sleep(time); //stop recording soundIn.Stop(); } } } return(0); }
public void StopRecording() { WaveIn?.StopRecording(); WaveIn?.Dispose(); WaveIn = null; WaveWriter?.Dispose(); WaveWriter = null; }
public void WavePcm8LoopedBuildAndParseEqual(int numChannels) { Pcm8Format audio = GenerateAudio.GeneratePcm8SineWave(BuildParseTestOptions.Samples, numChannels, BuildParseTestOptions.SampleRate).WithLoop(true); var writer = new WaveWriter { Configuration = { Codec = WaveCodec.Pcm8Bit } }; BuildParseTests.BuildParseCompareAudio(audio, writer, new WaveReader()); }
void StartCapture() { _recordStartSystemTimestamp = DateTime.Now; _recordFileName = Path.Combine(_destinationFolder, _recordStartSystemTimestamp.ToString("yyyyddMMHHmmssfff") + ".wav"); _writer = new WaveWriter( _recordFileName, _capture.WaveFormat ); }
void rex_Open(object sender, EventArgs e) { if (AudioWaveWriter == null) { AudioWaveWriter = new WaveWriter( File.Create(AudioFileName), AudioCompressionManager.FormatBytes(((RecorderEx)sender).Format)); } }
public void OpenRecorder(object sender, EventArgs e) { if (ww != null) { ww.Close(); } ww = new WaveWriter(_stream, recEx.FormatBytes()); OnChangeState(DictaphoneState.Record); }
private static IAudioReader GetVoxReader(string fileName, int sampleRate) { BinaryReader br = new BinaryReader(File.OpenRead(fileName)); MemoryStream ms = new MemoryStream(); IntPtr format = AudioCompressionManager.GetPcmFormat(1, 16, sampleRate); WaveWriter ww = new WaveWriter(ms, AudioCompressionManager.FormatBytes(format)); Vox.Vox2Wav(br, ww); br.Close(); return new WaveReader(ms); }
public bool SliceSample() { Stop(); int stream = Bass.BASS_StreamCreateFile(filePath, 0, 0, BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_STREAM_DECODE); long tLength = Bass.BASS_ChannelGetLength(stream); double seconds = (SelectionEnd - SelectionBegin).TotalSeconds; /* byte lengths */ int boffset = (int)Bass.BASS_ChannelSeconds2Bytes(stream, SelectionBegin.TotalSeconds); int blength = (int)Bass.BASS_ChannelSeconds2Bytes(stream, seconds); Bass.BASS_ChannelSetPosition(stream, boffset, BASSMode.BASS_POS_BYTES); BASS_CHANNELINFO info = new BASS_CHANNELINFO(); Bass.BASS_ChannelGetInfo(stream, info); // create the sample short[] data = new short[blength]; //, putdata = new byte[blength]; Bass.BASS_ChannelGetData(stream, data, blength); string f = filePath.Substring(0, filePath.LastIndexOf("\\") + 1) + "temp.wav"; WaveWriter w = new WaveWriter(f, stream, 16, true); w.Write(data, blength); w.Close(); return OpenFile(f); }
/// <summary> /// Recode the file /// </summary> /// <param name = "fileName">Initial file</param> /// <param name = "outFileName">Target file</param> /// <param name = "targetSampleRate">Target sample rate</param> public void RecodeTheFile(string fileName, string outFileName, int targetSampleRate) { int stream = Un4seen.Bass.Bass.BASS_StreamCreateFile(fileName, 0, 0, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT); TAG_INFO tags = new TAG_INFO(); BassTags.BASS_TAG_GetFromFile(stream, tags); int mixerStream = BassMix.BASS_Mixer_StreamCreate(targetSampleRate, 1, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT); if (BassMix.BASS_Mixer_StreamAddChannel(mixerStream, stream, BASSFlag.BASS_MIXER_FILTER)) { WaveWriter waveWriter = new WaveWriter(outFileName, mixerStream, true); const int length = 5512*10*4; float[] buffer = new float[length]; while (true) { int bytesRead = Un4seen.Bass.Bass.BASS_ChannelGetData(mixerStream, buffer, length); if (bytesRead == 0) break; waveWriter.Write(buffer, bytesRead); } waveWriter.Close(); } else throw new Exception(Un4seen.Bass.Bass.BASS_ErrorGetCode().ToString()); }
private static void Vox2Wav(string voxFile, string wavFile, int samplesPerSec) { BinaryReader br = new BinaryReader(File.OpenRead(voxFile)); IntPtr format = AudioCompressionManager.GetPcmFormat(1, 16, samplesPerSec); WaveWriter ww = new WaveWriter(File.Create(wavFile), AudioCompressionManager.FormatBytes(format)); Vox.Vox2Wav(br, ww); br.Close(); ww.Close(); }
public void RecodeFileToMonoWave(string pathToFile, string outputPathToFile, int targetSampleRate) { int stream = Bass.BASS_StreamCreateFile(pathToFile, 0, 0, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT); TAG_INFO tags = new TAG_INFO(); BassTags.BASS_TAG_GetFromFile(stream, tags); int mixerStream = BassMix.BASS_Mixer_StreamCreate(targetSampleRate, 1, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT); if (!BassMix.BASS_Mixer_StreamAddChannel(mixerStream, stream, BASSFlag.BASS_MIXER_FILTER)) { throw new Exception(Bass.BASS_ErrorGetCode().ToString()); } WaveWriter waveWriter = new WaveWriter(outputPathToFile, mixerStream, true); const int Length = 5512 * 10 * 4; float[] buffer = new float[Length]; while (true) { int bytesRead = Bass.BASS_ChannelGetData(mixerStream, buffer, Length); if (bytesRead == 0) { break; } waveWriter.Write(buffer, bytesRead); } waveWriter.Close(); }
public float[] RecordFromMicrophoneToFile(string pathToFile, int sampleRate, int secondsToRecord) { int stream = Bass.BASS_RecordStart(sampleRate, 1, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT, null, IntPtr.Zero); if (stream == 0) { throw new Exception(Bass.BASS_ErrorGetCode().ToString()); } int mixerStream = BassMix.BASS_Mixer_StreamCreate(sampleRate, 1, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT); if (mixerStream == 0) { throw new Exception(Bass.BASS_ErrorGetCode().ToString()); } if (!BassMix.BASS_Mixer_StreamAddChannel(mixerStream, stream, BASSFlag.BASS_MIXER_FILTER)) { throw new Exception(Bass.BASS_ErrorGetCode().ToString()); } float[] samples = ReadSamplesFromContinuousMixedStream(sampleRate, secondsToRecord, mixerStream); using (WaveWriter waveWriter = new WaveWriter(pathToFile, mixerStream, true)) { waveWriter.Write(samples, samples.Length); waveWriter.Close(); } Bass.BASS_StreamFree(mixerStream); Bass.BASS_StreamFree(stream); return samples; }
/// <summary> /// Decode File /// </summary> /// <param name="file"></param> /// <returns></returns> public bool DecodeFile() { try { if (!string.IsNullOrEmpty(CurrentFile)) { _chunkSize = 4096; // Set Default Chunk Size if (CurrentFile.ToLower().Contains(".mp3")) { // Check Mp3 if (System.IO.File.Exists(CurrentFile)) { // Check File Exists CurrentFileName = System.IO.Path.GetFileName(CurrentFile); using (var mp3Stream = new Mp3Sharp.Mp3Stream(CurrentFile)) { // Create Mp3 Stream _mp3Stream = mp3Stream; // Set Mp3 Stream _bytes = new byte[mp3Stream.Length]; // Set Bytes _totalBytes = mp3Stream.Length; // Set Total Bytes _numBytesToRead = _totalBytes; // Set Num Bytes to Read _numBytesRead = 0; // Set Num Bytes Read to 0 using (var writer = new WaveWriter(CurrentFile.Replace(".mp3", ".wav"))) { // Create Writer _writer = writer; // Set Writer while (_numBytesToRead > 0) { // Loop through Chunks if (_chunkSize > _numBytesToRead) { // Check Progress isn't greater than remaining bytes _chunkSize = 1; // Check a chunk at a time } var t = new Thread(ReadDecodeChunk); t.Start(); if (!t.Join(1500)) { t.Abort(); // Oops! We read 1 too many bytes! Lets stop trying, we got everything. _numBytesToRead = 0; // This should take us out of the loop soon } if (_readDecodeResult == 0) { break; } _numBytesRead += _readDecodeResult; _numBytesToRead -= _readDecodeResult; _percent = ((int)_numBytesRead * 100 / _totalBytes); if (PercentChanged != null) { PercentChanged(_percent); } } _writer = null; writer.Close(); writer.Dispose(); } _numBytesToRead = _bytes.Length; _mp3Stream = null; } } } } return true; } catch { throw; } }
private void SaveSegment(int segCount, Array testbuf) { var writer = new WaveWriter( File.Create(Path.Combine(segmentsFolder, string.Format("Segment_{0}.wav", segCount.ToString("D3")))), new WaveFormatEx(waveOutSamplesPerSecond, 16, 1)); writer.Write((short[]) testbuf); writer.Close(); }