/// <summary> /// releases all the player related resources /// </summary> public void Dispose() { if (this.file != null) { this.file.Close(); this.file.Dispose(); this.file = null; } if (vorbisReader != null) { this.vorbisReader.Close(); this.vorbisReader.Dispose(); this.vorbisReader = null; } if (flacReader != null) { this.flacReader.Close(); this.flacReader.Dispose(); this.flacReader = null; } if (this.wavePlayer != null) { this.wavePlayer.PlaybackStopped -= wavePlayer_PlaybackStopped; this.wavePlayer.Dispose(); this.wavePlayer = null; } }
private Stream DecodeFLAC(SndAssetBankEntry entry) { var wavOutput = new MemoryStream(); try { using (var input = new MemoryStream(entry.Data.Get())) using (var wavWriter = new WavWriter(wavOutput)) using (var reader = new FlacReader(input, wavWriter)) { reader.SampleProcessed += (s, args) => BeginInvoke(new MethodInvoker(() => currentTimetoolStripLabel.Text = "Please wait, decoding audio... " + args.Progress + "%")); reader.Process(); } wavOutput.Position = 0; return(wavOutput); } catch (Exception e) { // Ignore exception for headerless FLAC if (e.Message.IndexOf("until eof", StringComparison.InvariantCulture) != -1 && entry.Data is AudioDataStream && ((AudioDataStream)entry.Data).Stream is HeaderlessFLACStream) { wavOutput.Position = 0; return(wavOutput); } return(null); } }
/// <summary> /// Initialize a local audio player with given type /// </summary> /// <param name="fileName">the file name to play</param> /// <param name="waveOutType">the wave out type to use</param> public LocalAudioPlayer(string fileName, WaveOutType waveOutType) { this.fileName = fileName; PlaybackStopType = PlaybackStopTypes.PlaybackStoppedReachingEndOfFile; Debug.Assert(this.wavePlayer == null); this.wavePlayer = CreateWavePlayer(waveOutType); wavePlayer.PlaybackStopped += wavePlayer_PlaybackStopped; try { if (fileName.ToLowerInvariant().EndsWith(".ogg")) { vorbisReader = new VorbisWaveReader(fileName); wavePlayer.Init(vorbisReader); } else if (fileName.ToLowerInvariant().EndsWith(".flac")) { flacReader = new FlacReader(fileName); wavePlayer.Init(flacReader); } else { this.file = new AudioFileReader(fileName); this.wavePlayer.Init(file); } //this.wavePlayer.PlaybackStopped += wavePlayer_PlaybackStopped; } catch (Exception) { //throw; } //Play(); }
public FlacStream(Stream baseStream, bool keepOpen, int bitsPerSample) { this.baseStream = baseStream; this.keepOpen = keepOpen; this.bitsPerSample = bitsPerSample; reader = new FlacReader(baseStream, true); reader.RecordType = FlacBox.FlacRecordType.FrameFooter; writer = new FlacWriter(baseStream, true); }
public override SampleFormat SetHeader(byte[] buffer) { m_FlacHeader = buffer; MemoryStream stream = new MemoryStream(buffer); using (FlacReader reader = new FlacReader(stream)) { return(NAudioPlayer.WaveFormatToSampleFormat(reader.WaveFormat)); } }
/// <summary> /// saves vorbis ogg or flac tag information to file /// </summary> /// <param name="taglibFile"></param> public void SaveVorbisTag(VorbisComment taglibFile) { if (taglibFile != null) { //string fName = file.FileName; //AudioFileReader prev = file; if (flacReader != null) { //float curVol = file.Volume; wavePlayer.Stop(); string prevFile = this.fileName; this.flacReader.Close(); this.flacReader.Dispose(); this.flacReader = null; try { taglibFile.SaveMetadata(); } catch (UnauthorizedAccessException) { } catch (Exception) { } this.flacReader = new FlacReader(prevFile); wavePlayer.Init(this.flacReader); //SetVolume(curVol); } else if (vorbisReader != null) { wavePlayer.Stop(); string prevFile = this.fileName; this.vorbisReader.Close(); this.vorbisReader.Dispose(); this.vorbisReader = null; try { taglibFile.SaveMetadata(); } catch (UnauthorizedAccessException) { } catch (Exception) { } this.vorbisReader = new VorbisWaveReader(prevFile); wavePlayer.Init(this.vorbisReader); //SetVolume(curVol); } } }
void ReadAudioFile() { WaveStream _audioFileReader; if (System.IO.Path.GetExtension(AudioFile).ToUpper() == ".FLAC") { _audioFileReader = new FlacReader(AudioFile); } else { _audioFileReader = new AudioFileReader(AudioFile); } var sampleChannel = new SampleChannel(_audioFileReader, true); var memoryStream = new System.IO.MemoryStream(); saplesCount = (int)(_audioFileReader.TotalTime.TotalSeconds * sampleChannel.WaveFormat.SampleRate * sampleChannel.WaveFormat.Channels); samples = new float[saplesCount]; lsamples = new float[saplesCount / 2 + 1]; rsamples = new float[saplesCount / 2 + 1]; sampleChannel.Read(samples, 0, samples.Length); // Separate channels for (int i = 0, j = 0, k = 0; i < samples.Length; i++) { if (i % 2 == 0) { lsamples[j] = samples[i]; j++; } else { rsamples[k] = samples[i]; k++; } } //System.Threading.Tasks.Task.Factory.StartNew(new Action(() => //{ // Dispatcher.Invoke(delegate // { // // Update painters // InitializePainer(WaveformPainterLeft, lsamples); // InitializePainer(WaveformPainterRight, rsamples); // }); // StoreToDatabase(); //})); }
public Task Process() { Task t = new Task(() => { int fCount = Directory.GetFiles(this.InputPath, "*.flac").Length; //Conversion List <Task> tasks = new List <Task>(); foreach (string flacFile in Directory.GetFiles(this.InputPath, "*.flac")) { Task t = new Task(() => { Stopwatch sWatch = new Stopwatch(); Log.Information("[Encode][WAVE][Process] Processing \"" + Path.GetFileNameWithoutExtension(flacFile) + "\""); sWatch.Start(); //Main Conversion Process using NAudio.Flac.FlacReader flacReader = new FlacReader(flacFile); byte[] flacBuffer; using (StreamReader streamReader = new StreamReader(flacReader)) { flacBuffer = new byte[streamReader.BaseStream.Length]; streamReader.BaseStream.Read(flacBuffer, 0, flacBuffer.Length); } using (NAudio.Wave.WaveFileWriter waveFileWriter = new NAudio.Wave.WaveFileWriter(Path.Combine(this.OutputPath, Path.GetFileNameWithoutExtension(flacFile) + ".wav"), new NAudio.Wave.WaveFormat())) { using StreamWriter streamWriter = new StreamWriter(waveFileWriter); waveFileWriter.Write(flacBuffer, 0, flacBuffer.Length); } flacBuffer = null; //# ### # sWatch.Stop(); Log.Information("[Encode][WAVE][Process] \"" + Path.GetFileNameWithoutExtension(flacFile) + "\" Processing finished - Duration: " + sWatch.Elapsed.ToString(@"hh\:mm\:ss\:fffffff")); }); tasks.Add(t); } tasks.All((x) => { x.Start(); return(true); }); Task.WaitAll(tasks.ToArray()); //# ### # //Copy Non Audio Files CopyNonAudioFiles(this.InputPath, this.OutputPath); //# ### # }); t.Start(); return(t); }
public override PcmChunkMessage Decode(PcmChunkMessage flacChunk) { byte[] allData = new byte[m_FlacHeader.Length + flacChunk.Payload.Length]; Buffer.BlockCopy(m_FlacHeader, 0, allData, 0, m_FlacHeader.Length); Buffer.BlockCopy(flacChunk.Payload, 0, allData, m_FlacHeader.Length, flacChunk.Payload.Length); using (MemoryStream stream = new MemoryStream(allData)) { using (FlacReader reader = new FlacReader(stream)) { byte[] newPayload = new byte[reader.Length]; reader.Read(newPayload, 0, newPayload.Length); flacChunk.ClearPayload(); flacChunk.SetPayload(newPayload); } } return(flacChunk); }
private void ButtonClicked(object sender, RoutedEventArgs e) { SoundButton button = sender as SoundButton; WaveOutEvent waveOut = new WaveOutEvent(); try { if (button.SoundClip.Contains(".ogg")) { FileStream fileStream = new FileStream(button.SoundClip, FileMode.Open, FileAccess.Read); MemoryStream memoryStream = new MemoryStream(); fileStream.CopyTo(memoryStream); var vorbisStream = new NAudio.Vorbis.VorbisWaveReader(memoryStream); vorbisStream.Position = 0; waveOut.Init(vorbisStream); } else if (button.SoundClip.Contains(".mp3")) { var reader = new Mp3FileReader(button.SoundClip); reader.Position = 0; waveOut.Init(reader); } else if (button.SoundClip.Contains(".flac")) { var reader = new FlacReader(button.SoundClip); reader.Position = 0; waveOut.Init(reader); } waveOut.PlaybackStopped += new EventHandler <StoppedEventArgs>(AudioPlaybackStopped); waveOut.Play(); } catch (Exception ex) { Debug.WriteLine(ex); waveOut.Dispose(); } }
public static AudioClip GetClipByType(byte[] data, SupportFormatType type) { try { MemoryStream memoryStream = new MemoryStream(data); WaveStream wave = null; switch (type) { case SupportFormatType.mp3: wave = new Mp3FileReader(memoryStream); break; case SupportFormatType.flac: wave = new FlacReader(memoryStream); break; //case SupportFormatType.wav: // wave = new WaveFileReader(memoryStream); // break; //case SupportFormatType.aiff: // wave = new AiffFileReader(memoryStream); // break; } WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(wave); WAV wav = new WAV(AudioMemStream(waveStream).ToArray()); Debug.Log(wav); AudioClip audioClip = AudioClip.Create(string.Format("{0}Sound", type.ToString()), wav.SampleCount, 1, wav.Frequency, false); audioClip.SetData(wav.LeftChannel, 0); return(audioClip); } catch (Exception e) { Debug.Log("NAudioPlayer.GetClipByType() Error:" + e.Message); return(null); } }
private async Task ConvertFiles(Func <BackgroundTaskControl, Task> callBack, BackgroundTaskControl bgtc) { await Task.Delay(250); // give time for rendering changes WaveStream inputStream = null; for (int i = 0; i < filePaths.Count(); i++) { try { if (filePaths[i].EndsWith(".ogg")) { inputStream = new VorbisWaveReader(filePaths[i]); } else if (filePaths[i].EndsWith(".flac")) { inputStream = new FlacReader(filePaths[i]); } else { inputStream = new AudioFileReader(filePaths[i]); } string selectedFileType = ""; Dispatcher.Invoke(() => { selectedFileType = OutputFileTypeComboBox.SelectedItem as string; WaitingLabel.Content = $"Now converting {safeFileNames[i]} to {selectedFileType.Substring(selectedFileType.IndexOf("(")+1,4)}"; if (bgtc != null) { bgtc.BackgroundTaskLabel.Content = WaitingLabel.Content; } }); if (selectedFileType.EndsWith("(.mp3)")) { string monoStereoSelection = ""; Dispatcher.Invoke(() => { monoStereoSelection = MSConvertComboBox.SelectedItem as string; }); if (inputStream.WaveFormat.BitsPerSample == 16) { IWaveProvider provider = MonoStereoConvert16(inputStream, monoStereoSelection == "Mono"); using (FileStream fileStream = File.Create($"{outputPath}/{safeFileNames[i]}.mp3")) using (NAudio.Lame.LameMP3FileWriter writer = new NAudio.Lame.LameMP3FileWriter(fileStream, provider.WaveFormat, 320000)) { byte[] buffer = new byte[4096]; int bytesRead = 0; do { bytesRead = provider.Read(buffer, 0, buffer.Length); writer.Write(buffer, 0, bytesRead); } while (bytesRead > 0); } } else if (inputStream.WaveFormat.BitsPerSample == 32) { ISampleProvider provider = MonoStereoConvert32(inputStream as ISampleProvider, monoStereoSelection == "Mono"); using (FileStream fileStream = File.Create($"{outputPath}/{safeFileNames[i]}.mp3")) using (NAudio.Lame.LameMP3FileWriter writer = new NAudio.Lame.LameMP3FileWriter(fileStream, provider.WaveFormat, 320000)) { byte[] buffer = new byte[4096]; int bytesRead = 0; do { var providerAsWave = provider.ToWaveProvider(); // need to write with bytes not floats bytesRead = providerAsWave.Read(buffer, 0, buffer.Length); writer.Write(buffer, 0, bytesRead); } while (bytesRead > 0); } } TagLib.File outputTags = TagLib.File.Create($"{outputPath}//{safeFileNames[i]}.mp3"); TagLib.File inputTags = TagLib.File.Create(filePaths[i]); outputTags.Tag.Album = inputTags.Tag.Album; outputTags.Tag.AlbumArtists = inputTags.Tag.AlbumArtists; outputTags.Tag.Genres = inputTags.Tag.Genres; outputTags.Tag.Performers = inputTags.Tag.Performers; outputTags.Tag.Year = inputTags.Tag.Year; outputTags.Tag.Pictures = inputTags.Tag.Pictures; outputTags.Tag.Title = inputTags.Tag.Title; outputTags.Tag.Track = inputTags.Tag.Track; outputTags.Save(); inputTags.Dispose(); outputTags.Dispose(); } //else if (selectedFileType.EndsWith("(.wma)")) //{ // FileStream fileStream = File.Create($"c:/temp/conversiontest/{safeFileName}.wma"); // fileStream.Close(); // using (MediaFoundationEncoder writer = new MediaFoundationEncoder(new NAudio.MediaFoundation.MediaType(inputStream.WaveFormat))) // { // writer.Encode($"c:/temp/conversiontest/{safeFileName}.wma", inputStream); // } //} else if (selectedFileType.EndsWith("(.wav)")) { string monoStereoSelection = ""; Dispatcher.Invoke(() => { monoStereoSelection = MSConvertComboBox.SelectedItem as string; }); if (inputStream.WaveFormat.BitsPerSample == 16) { IWaveProvider provider = MonoStereoConvert16(inputStream, monoStereoSelection == "Mono"); using (FileStream fileStream = File.Create($"{outputPath}/{safeFileNames[i]}.wav")) using (WaveFileWriter writer = new WaveFileWriter(fileStream, provider.WaveFormat)) { byte[] buffer = new byte[4096]; int bytesRead = 0; do { bytesRead = provider.Read(buffer, 0, buffer.Length); writer.Write(buffer, 0, bytesRead); } while (bytesRead > 0); } } else if (inputStream.WaveFormat.BitsPerSample == 32) { ISampleProvider provider = MonoStereoConvert32(inputStream as ISampleProvider, monoStereoSelection == "Mono"); using (FileStream fileStream = File.Create($"{outputPath}/{safeFileNames[i]}.wav")) using (WaveFileWriter writer = new WaveFileWriter(fileStream, provider.WaveFormat)) { byte[] buffer = new byte[4096]; int bytesRead = 0; do { var providerAsWave = provider.ToWaveProvider(); // need to write with bytes not floats bytesRead = providerAsWave.Read(buffer, 0, buffer.Length); writer.Write(buffer, 0, bytesRead); } while (bytesRead > 0); } } TagLib.File outputTags = TagLib.File.Create($"{outputPath}/{safeFileNames[i]}.wav"); TagLib.File inputTags = TagLib.File.Create(filePaths[i]); outputTags.Tag.Album = inputTags.Tag.Album; outputTags.Tag.AlbumArtists = inputTags.Tag.AlbumArtists; outputTags.Tag.Genres = inputTags.Tag.Genres; outputTags.Tag.Performers = inputTags.Tag.Performers; outputTags.Tag.Year = inputTags.Tag.Year; outputTags.Tag.Pictures = inputTags.Tag.Pictures; outputTags.Tag.Title = inputTags.Tag.Title; outputTags.Tag.Track = inputTags.Tag.Track; outputTags.Save(); inputTags.Dispose(); outputTags.Dispose(); } } catch (Exception e) { MessageBox.Show("Error converting " + filePaths[i] + ", message: " + e.Message); //just move onto the next song } finally { (inputStream as WaveStream)?.Close(); } } await callBack(bgtc); MessageBox.Show("File(s) successfully converted!"); }
public void SelectFile(string fileName) { InvalidFile = false; InvalidFileChanged?.Invoke(this, EventArgs.Empty); if (Playing) { Stop(); } _source = null; string extension = Path.GetExtension(fileName).ToLower(); try { if (extension == ".mp3") { _source = new Mp3FileReader(fileName); } else if (extension == ".wav") { _source = new WaveFileReader(fileName); } else if ((extension == ".fla") || (extension == ".flac")) { _source = new FlacReader(fileName); } } catch { InvalidFile = true; InvalidFileChanged?.Invoke(this, EventArgs.Empty); _source = null; } TotalTimeChanged?.Invoke(this, EventArgs.Empty); if (_source == null) { return; } _stretcher = new RubberBandWaveStream(_source); _stretcher.SourceRead += (sender, e) => { CurrentTimeChanged?.Invoke(this, e); }; _stretcher.EndOfStream += (sender, e) => { ReachedEnd?.Invoke(this, e); Stop(); }; TempoChanged?.Invoke(this, EventArgs.Empty); CurrentTimeChanged?.Invoke(this, EventArgs.Empty); _waveOut.Init(_stretcher); }
private static WaveStream ReaderForAudioFormat ( Stream fileInputStream, AudioFormat audioFormat, int?maxSeconds, out int seconds ) { WaveStream readerStream; switch (audioFormat) { case AudioFormat.Mp3: readerStream = new Mp3FileReader(fileInputStream); break; case AudioFormat.Wave: readerStream = new WaveFileReader(fileInputStream); break; case AudioFormat.Aiff: readerStream = new AiffFileReader(fileInputStream); break; case AudioFormat.Flac: readerStream = new FlacReader(fileInputStream); break; case AudioFormat.OggVorbis: readerStream = new VorbisWaveReader(fileInputStream); break; case AudioFormat.Other: default: var tempPath = Path.GetTempFileName(); AppDomain.CurrentDomain.ProcessExit += (o, e) => { File.Delete(tempPath); }; var tempFileStream = File.OpenWrite(tempPath); fileInputStream.CopyTo(tempFileStream); tempFileStream.Close(); Console.Error.WriteLine($"Creating MediaFoundationReader with file = {tempPath}"); readerStream = new MediaFoundationReader(tempPath); break; } if (maxSeconds.HasValue) { readerStream = new CapSecondsByAverageStream(readerStream, maxSeconds.Value); seconds = Math.Min(maxSeconds.Value, (int)(readerStream.Length / readerStream.WaveFormat.AverageBytesPerSecond)); } else { seconds = (int)(readerStream.Length / readerStream.WaveFormat.AverageBytesPerSecond); } readerStream = NormalizeWaveFormat(readerStream); return(readerStream); }
public Task Process() { Task t = new Task(() => { int fCount = Directory.GetFiles(this.InputPath, "*.flac").Length; int currFLAC = 0; //Conversion List <Task> tasks = new List <Task>(); foreach (string flacFile in Directory.GetFiles(this.InputPath, "*.flac")) { Task t = new Task(() => { Stopwatch sWatch = new Stopwatch(); //Reporting Log.Information("[Encode][MP3][Process] Processing \"" + Path.GetFileNameWithoutExtension(flacFile) + "\""); double perc = Math.Round((double)(currFLAC * 100 / fCount), 2); this.InternalProgress.Report(new EncodeProgress() { Percentage = perc }); //# ### # sWatch.Start(); byte[] flacBuffer; using (FlacReader flacReader = new FlacReader(flacFile)) { using StreamReader streamReader = new StreamReader(flacReader); flacBuffer = new byte[streamReader.BaseStream.Length]; streamReader.BaseStream.Read(flacBuffer, 0, flacBuffer.Length); } using (LibFlacSharp.FlacFile r = new LibFlacSharp.FlacFile(flacFile)) { LibFlacSharp.Metadata.VorbisComment s = r.VorbisComment; LConfig.ID3 = new ID3TagData() { Artist = s.CommentList.Where(x => x.Key.ToLower().StartsWith("artist")).FirstOrDefault().Value, AlbumArtist = s.CommentList.Where(x => x.Key.ToLower().Contains("album") && x.Key.ToLower().Contains("artist")).FirstOrDefault().Value, Album = s.CommentList.Where(x => x.Key.ToLower().StartsWith("album") && x.Key.ToLower().EndsWith("album")).FirstOrDefault().Value, Title = s.CommentList.Where(x => x.Key.ToLower().StartsWith("title")).FirstOrDefault().Value, Year = s.CommentList.Where(x => x.Key.ToLower().StartsWith("date")).FirstOrDefault().Value, Track = s.CommentList.Where(x => x.Key.ToLower().StartsWith("tracknumber")).FirstOrDefault().Value, Genre = s.CommentList.Where(x => x.Key.ToLower().StartsWith("genre")).FirstOrDefault().Value, Comment = s.CommentList.Where(x => x.Key.ToLower().Contains("comment")).FirstOrDefault().Value, AlbumArt = r.Pictures.Count() > 0 ? r.Pictures.Values.ElementAt(0).PictureData : null }; } //TODO: User defined Tags like, mood, original composer, etc. using (LameMP3FileWriter lameMP3FileWriter = new LameMP3FileWriter(Path.Combine(this.OutputPath, Path.GetFileNameWithoutExtension(flacFile) + ".mp3"), new NAudio.Wave.WaveFormat(), LConfig)) { using StreamWriter streamWriter = new StreamWriter(lameMP3FileWriter); lameMP3FileWriter.Write(flacBuffer, 0, flacBuffer.Length); } flacBuffer = null; sWatch.Stop(); //Reporting Log.Information("[Encode][MP3][Process] \"" + Path.GetFileNameWithoutExtension(flacFile) + "\" Processing finished - Duration: " + sWatch.Elapsed.ToString(@"hh\:mm\:ss\:fffffff")); currFLAC -= -1; perc = Math.Round((double)(currFLAC * 100 / fCount), 2); this.InternalProgress.Report(new EncodeProgress() { Percentage = perc }); //# ### # }); tasks.Add(t); } tasks.All((x) => { x.Start(); return(true); }); Task.WaitAll(tasks.ToArray()); //# ### # //Copy Non Audio Files CopyNonAudioFiles(this.InputPath, this.OutputPath); //# ### # }); t.Start(); return(t); }
private async Task ConvertFiles(Func <BackgroundTaskControl, Task> callBack, BackgroundTaskControl bgtc) { await Task.Delay(250); // give time for rendering changes WaveStream inputStream = null; for (int i = 0; i < selectedSongs.Count(); i++) { try { if (selectedSongs[i].FilePath.EndsWith(".ogg")) { inputStream = new VorbisWaveReader(selectedSongs[i].FilePath); } else if (selectedSongs[i].FilePath.EndsWith(".flac")) { inputStream = new FlacReader(selectedSongs[i].FilePath); } else { inputStream = new AudioFileReader(selectedSongs[i].FilePath); } string selectedFileType = ""; Dispatcher.Invoke(() => { selectedFileType = OutputFileTypeComboBox.SelectedItem as string; WaitingLabel.Content = $"Now converting {selectedSongs[i].Name} to {selectedFileType.Substring(selectedFileType.IndexOf("(") + 1, 4)}"; bgtc.BackgroundTaskLabel.Content = WaitingLabel.Content; }); if (selectedFileType.EndsWith("(.mp3)")) { using (FileStream fileStream = File.Create($"{outputPath}/{selectedSongs[i].Name}.mp3")) using (NAudio.Lame.LameMP3FileWriter writer = new NAudio.Lame.LameMP3FileWriter(fileStream, inputStream.WaveFormat, 320000)) { byte[] buffer = new byte[4096]; int bytesRead = 0; do { bytesRead = inputStream.Read(buffer, 0, buffer.Length); writer.Write(buffer, 0, bytesRead); } while (bytesRead > 0); } TagLib.File outputTags = TagLib.File.Create($"{outputPath}/{selectedSongs[i].Name}.mp3"); TagLib.File inputTags = TagLib.File.Create(selectedSongs[i].FilePath); outputTags.Tag.Album = inputTags.Tag.Album; outputTags.Tag.AlbumArtists = inputTags.Tag.AlbumArtists; outputTags.Tag.Genres = inputTags.Tag.Genres; outputTags.Tag.Performers = inputTags.Tag.Performers; outputTags.Tag.Year = inputTags.Tag.Year; outputTags.Tag.Pictures = inputTags.Tag.Pictures; outputTags.Tag.Title = inputTags.Tag.Title; outputTags.Tag.Track = inputTags.Tag.Track; outputTags.Save(); inputTags.Dispose(); outputTags.Dispose(); } else if (selectedFileType.EndsWith("(.wav)")) { using (FileStream fileStream = File.Create($"{outputPath}/{selectedSongs[i].Name}.wav")) using (WaveFileWriter writer = new WaveFileWriter(fileStream, inputStream.WaveFormat)) { byte[] buffer = new byte[4096]; int bytesRead = 0; do { bytesRead = inputStream.Read(buffer, 0, buffer.Length); writer.Write(buffer, 0, bytesRead); } while (bytesRead > 0); } TagLib.File outputTags = TagLib.File.Create($"{outputPath}/{selectedSongs[i].Name}.wav"); TagLib.File inputTags = TagLib.File.Create(selectedSongs[i].FilePath); outputTags.Tag.Album = inputTags.Tag.Album; outputTags.Tag.AlbumArtists = inputTags.Tag.AlbumArtists; outputTags.Tag.Genres = inputTags.Tag.Genres; outputTags.Tag.Performers = inputTags.Tag.Performers; outputTags.Tag.Year = inputTags.Tag.Year; outputTags.Tag.Pictures = inputTags.Tag.Pictures; outputTags.Tag.Title = inputTags.Tag.Title; outputTags.Tag.Track = inputTags.Tag.Track; outputTags.Save(); inputTags.Dispose(); outputTags.Dispose(); } } catch (Exception e) { MessageBox.Show("Error converting " + selectedSongs[i].FilePath + ", message: " + e.Message); await callBack(bgtc); inputStream?.Close(); return; } finally { inputStream?.Close(); } } await callBack(bgtc); MessageBox.Show("File(s) successfully converted!"); }
private void InitWaveformPainter(ISampleProvider sampleProvider) { WaveStream _audioFileReader; if (System.IO.Path.GetExtension(AudioFile).ToUpper() == ".FLAC") { _audioFileReader = new FlacReader(AudioFile); } else { _audioFileReader = new AudioFileReader(AudioFile); } var sampleChannel = new SampleChannel(_audioFileReader, true); byte[] buffer1 = new byte[4096]; var memoryStream = new System.IO.MemoryStream(); //int reader = 0; //while ((reader = _audioFileReader.Read(buffer1, 0, buffer1.Length)) != 0) // memoryStream.Write(buffer1, 0, reader); int saplesCount = (int)(_audioFileReader.TotalTime.TotalSeconds * sampleChannel.WaveFormat.SampleRate * sampleChannel.WaveFormat.Channels); float[] samples = new float[saplesCount]; float[] lsamples = new float[saplesCount / 2 + 1]; float[] rsamples = new float[saplesCount / 2 + 1]; sampleChannel.Read(samples, 0, samples.Length); byte[] buffer = memoryStream.ToArray(); //byte[] buffer = new byte[_audioFileReader.Length]; byte[] lbuffer = new byte[buffer.Length / 2]; //int read = _audioFileReader.Read(buffer, 0, buffer.Length); //for (int i = 0, j = 0; i < lbuffer.Length; i += 2, j++) //{ // lbuffer[j] = buffer[i]; //} for (int i = 0, j = 0, k = 0; i < samples.Length; i++) { if (i % 2 == 0) { lsamples[j] = samples[i]; j++; } else { rsamples[k] = samples[i]; k++; } } //var sc = new SamplesConverter(); //sc.Data = buffer; //var samples = sc.getSamples(_audioFileReader, _audioFileReader.WaveFormat.BitsPerSample); //sampleProvider.WaveFormat.BitsPerSample WaveformPainter1.ClearSamples(); int step = rsamples.Length / WaveformPainter1.MaxSamples; int cnt = 0; for (var i = 0; i < WaveformPainter1.MaxSamples; i++) { float[] avgs = new float[step]; var avgNeg = new List <float>(); var avgPos = new List <float>(); for (var j = 0; j < step; j++, cnt++) { if (cnt >= rsamples.Length) { break; } if (rsamples[cnt] > 0) { avgPos.Add(rsamples[cnt]); avgNeg.Add(0); } if (rsamples[cnt] <= 0) { avgNeg.Add(rsamples[cnt]); avgPos.Add(0); } avgs[j] = rsamples[cnt]; } //WaveformPainter1.AddMax(avgNeg.Min()); if (avgPos.Count > 0) { WaveformPainter1.PositiveSamples.Add(avgs.Max()); } if (avgNeg.Count > 0) { WaveformPainter1.NegativeSamples.Add(avgs.Min()); } //WaveformPainter1.AddMax(avg); } //for (var i = 0; i < lsamples.Length; i += step) //{ // WaveformPainter1.AddMax(lsamples[i]); //} WaveformPainter1.Invalidate(); /* * * var audiobyteLen = _audioFileReader.Length; * var sampleChannel = new SampleChannel(_audioFileReader, true); * * //var smplLng = audiobyteLen;// / sampleProvider.WaveFormat.BitsPerSample; * //float[] buffer = new float[smplLng]; * //float[] lbuffer = new float[smplLng / 2]; * //float[] rbuffer = new float[smplLng / 2]; * //var length = sampleChannel.Read(buffer, 0, (int)smplLng/4); * * //for (int i = 0, j = 0; i < lbuffer.Length; i += 2, j++) * //{ * // lbuffer[j] = buffer[i]; * //} * * //for (int i = 1, j = 0; i < rbuffer.Length; i += 2, j++) * //{ * // rbuffer[j] = buffer[i]; * //} * * int samplesDesired = (int)(audiobyteLen / 4 / 8); * byte[] buffer = new byte[samplesDesired * 4]; * int[] left = new int[samplesDesired]; * int[] right = new int[samplesDesired]; * int bytesRead = _audioFileReader.Read(buffer, 0, (int)audiobyteLen/8); * _audioFileReader.Position = 0; * int index = 0; * for (int sample = 0; sample < bytesRead / 4; sample++) * { * left[sample] = BitConverter.ToInt16(buffer, index); * index += 2; * right[sample] = BitConverter.ToInt16(buffer, index); * index += 2; * } * * * int step = left.Length / WaveformPainter1.MaxSamples; * * for (var i = 0; i < left.Length; i += step) * { * WaveformPainter1.AddMax(left[i]); * } * WaveformPainter1.Invalidate(); * return; * * * * * int samplesDesired = (int)(audiobyteLen / 2); * byte[] buffer = new byte[samplesDesired * 4]; * int[] left = new int[samplesDesired]; * int[] right = new int[samplesDesired]; * int bytesRead = _audioFileReader.Read(buffer, 0, (int)audiobyteLen); * _audioFileReader.Position = 0; * int index = 0; * for (int sample = 0; sample < bytesRead / 4; sample++) * { * left[sample] = BitConverter.ToInt16(buffer, index); * index += 2; * right[sample] = BitConverter.ToInt16(buffer, index); * index += 2; * } * * var sc = new SamplesConverter(); * sc.Amplitudes = left; * var samples = sc.getSamples(_audioFileReader, 24); * //sampleProvider.WaveFormat.BitsPerSample * int step = left.Length / WaveformPainter1.MaxSamples; * for (var i = 0; i < samples.Length; i += step) * { * WaveformPainter1.AddMax(samples[i]); * } * * //foreach (var s in samples) * //{ * // WaveformPainter1.AddMax(s); * //} * WaveformPainter1.Invalidate(); * * * * * * * WaveStream _audioFileReader; * if (System.IO.Path.GetExtension(AudioFile).ToUpper() == ".FLAC") * { * _audioFileReader = new FlacReader(AudioFile); * } * else * _audioFileReader = new AudioFileReader(AudioFile); * * * * * * * * int size = sampleProvider.WaveFormat.BitsPerSample / 8; * var offset = 0; * var data = new byte[audiobyteLen / sampleProvider.WaveFormat.Channels]; * var dataLen = data.Length; * // Use data from left channel. * while (offset < dataLen) * { * _audioFileReader.Read(data, offset, size); * //_audioFileReader.Seek(size, System.IO.SeekOrigin.Current); * offset += size; * } * * _audioFileReader.Position = 0; * * //float[] buffer = new float[smplLng]; * //var length = sampleProvider.Read(buffer, 0, (int)smplLng); * * * * * * var sc = new SamplesConverter(); * sc.Data = data; * var samples = sc.getSamples(_audioFileReader, 24); * //sampleProvider.WaveFormat.BitsPerSample * * for (var i = 0; i < samples.Length; i += 32) * { * WaveformPainter1.AddMax(samples[i]); * } * * //foreach (var s in samples) * //{ * // WaveformPainter1.AddMax(s); * //} * WaveformPainter1.Invalidate(); * * //var size = sampleProvider.WaveFormat.ConvertLatencyToByteSize((int)audioFileReader.CurrentTime.TotalMilliseconds); * //float[] buffer = new float[size]; * ////var length = sampleProvider.Read(buffer, 0); * * //DbProviderFactory fact = DbProviderFactories.GetFactory("System.Data.SQLite"); * //using (DbConnection cnn = fact.CreateConnection()) * //{ * // cnn.ConnectionString = "Data Source=test.db3"; * // cnn.Open(); * //} * * * //audioFileReader.*/ }
public FLACMemorySoundFX(FlacReader reader) : base(reader) { }
private void GetTracksFromFolders() { var extensions = new List <string> { ".mp3", ".flac" }; var index = Math.Max(tracks.Count, 1); foreach ( var files in folders .Select(folder => Directory .GetFiles(folder, "*.*", SearchOption.AllDirectories) .Where(f => extensions.IndexOf(Path.GetExtension(f)) >= 0))) { foreach (var file in files) { var artists = ""; var album = ""; var title = ""; int duration; try { var tagFile = File.Create(file); duration = (int)tagFile.Properties.Duration.TotalMilliseconds; artists = string.Join(", ", tagFile.Tag.Performers); album = tagFile.Tag.Album ?? ""; title = tagFile.Tag.Title ?? ""; } catch (Exception) { try { var extension = file.Split('.').Last(); if (extension.Equals("mp3")) { var reader = new Mp3FileReader(file); duration = (int)reader.TotalTime.TotalMilliseconds; } else { var reader = new FlacReader(file); duration = (int)reader.TotalTime.TotalMilliseconds; } } catch (Exception) { continue; } } if (duration > 10 * 60 * 1000) { continue; } if (tracks.ContainsKey(file)) { continue; } var track = new Track { Id = index++, IsSpotifyTrack = false, HasMetaData = title.Length != 0, TrackName = title, Artist = artists, Album = album, TrackPath = file, TotalTime = duration, Location = file }; tracks.Add(file, track); } } }