//Окончание записи private void waveIn_RecordingStopped(object sender, EventArgs e) { if (InvokeRequired) { BeginInvoke(new EventHandler(waveIn_RecordingStopped), sender, e); } else { _www.Dispose(); _www = null; _writer.Close(); _writer.Dispose(); try { using (var reader = new AudioFileReader(_writer.Filename)) { using (var write = new LameMP3FileWriter(@"D:\MP3\gg.mp3", reader.WaveFormat, 128)) { reader.CopyTo(write); write.Flush(); } reader.Flush(); } } catch (Exception ev) { MessageBox.Show(ev.Message); } } }
public void TC01_EncodeStream() { Assert.IsTrue(File.Exists(SourceFilename)); using (var mp3data = new MemoryStream()) { // Convert source wave to MP3 using (var source = new AudioFileReader(SourceFilename)) using (var mp3writer = new LameMP3FileWriter(mp3data, source.WaveFormat, LAMEPreset.STANDARD)) { TimeSpan source_time = source.TotalTime; source.CopyTo(mp3writer); Assert.AreEqual(source.Length, source.Position); } // Open MP3 file and test content mp3data.Position = 0; using (var encoded = new Mp3FileReader(mp3data)) { // encoding did not supply an ID3 tag, ensure none was present in file Assert.IsNull(encoded.Id3v1Tag); Assert.IsNull(encoded.Id3v2Tag); // the STANDARD lame preset produces a Xing header. Check it. Assert.IsNotNull(encoded.XingHeader); Assert.AreEqual(mp3data.Length, encoded.XingHeader.Bytes); // confirm that length is a multiple of the block size int blkSize = (encoded.XingHeader.Mp3Frame.SampleCount * encoded.WaveFormat.BitsPerSample * encoded.WaveFormat.Channels) / 8; int calcLength = blkSize * encoded.XingHeader.Frames; Assert.AreEqual(calcLength, encoded.Length); } } }
public void Convert() { if (File.Exists(this.MetaData.OutputFilePath.Value)) { return; } var outputTag = new ID3TagData { Album = this.MetaData.Tag.Album, Artist = this.MetaData.Tag.Artist, Comment = this.MetaData.Tag.Comment, Genre = this.MetaData.Tag.Genre, Title = this.MetaData.Tag.Title, Track = this.MetaData.Tag.Track, Year = this.MetaData.Tag.Year, }; using (var reader = new AudioFileReader(this.MetaData.InputFilePath)) using (var writer = new LameMP3FileWriter(this.MetaData.OutputFilePath.Value , reader.WaveFormat , 320 , outputTag )) { reader.CopyTo(writer); } using (var outputFile = TagLib.File.Create(this.MetaData.OutputFilePath.Value)) { this.MetaData.Tag.CopyTo(this.MetaData.OutputFilePath.Value); outputFile.Save(); } }
private void button4_Click(object sender, EventArgs e) { synth.SelectVoice(ddlVoices.SelectedItem.ToString()); if (audioFile != null) { audioFile.Close(); } synth.SpeakAsyncCancelAll(); Thread.Sleep(1000); Console.WriteLine("Redirecting output"); synth.SetOutputToWaveFile("temp.wav"); Console.WriteLine("Speaking text..."); synth.Speak(rtfText.Text); Console.WriteLine("Done speaking text"); synth.SetOutputToNull(); Console.WriteLine("Done setting output to null"); SaveFileDialog ofd = new SaveFileDialog(); ofd.Filter = "Text files (*.mp3)|*.mp3|All files (*.*)|*.*"; ofd.ShowDialog(); using (var reader = new AudioFileReader("temp.wav")) using (var writer = new LameMP3FileWriter(ofd.FileName, reader.WaveFormat, LAMEPreset.ABR_128)) reader.CopyTo(writer); LastSavedFile = ofd.FileName; }
private bool DownloadAndSave(string title) { try { var videoID = mDownloadList.Find(x => x.Item1 == title)?.Item2; if (String.IsNullOrEmpty(videoID)) { return(false); } var streamManifest = youtube.Videos.Streams.GetManifestAsync(videoID).GetAwaiter().GetResult(); var streamInfo = streamManifest.GetAudioOnly().FirstOrDefault(); var kekwaitstream = youtube.Videos.Streams.GetAsync(streamInfo).GetAwaiter().GetResult(); var filename = string.Join("_", title.Split(Path.GetInvalidFileNameChars())); using (var reader = new AudioFileReader(streamInfo.Url)) using (var writer = new LameMP3FileWriter($"{AppDomain.CurrentDomain.BaseDirectory}Output\\{filename}.mp3", reader.WaveFormat, 128)) reader.CopyTo(writer); return(true); } catch { Thread.Sleep(300); return(DownloadAndSave(title)); } }
/// <summary> /// Converts the recorded WAV file to MP3. The WAV file will be converted /// ONLY if the recording was finished successfully (using StopRecording). /// </summary> public void ConvertToMP3() { if (!_isRecording) { // Convert WAV to MP3 using libmp3lame library try { _state = RecorderState.ConvertingInProgress; using (var reader = new AudioFileReader(_tempWavFilePath)) using (var writer = new LameMP3FileWriter(_mp3FilePath, reader.WaveFormat, _mp3Preset)) reader.CopyTo(writer); } catch (Exception) { _state = RecorderState.ConvertError; return; } } else { _state = RecorderState.ConvertError; return; } _state = RecorderState.ConvertingFinsihed; }
/// <summary>Convert WAV file to MP3 using libmp3lame library, setting ID3 tag</summary> /// <param name="waveFileName">Filename of WAV file to convert</param> /// <param name="mp3FileName">Filename to save to</param> /// <param name="tag">ID3 tag data to insert into file</param> /// <param name="bitRate">MP3 bitrate in kbps, defaults to 128kbps</param> /// <remarks>Uses NAudio to read, can read any file compatible with <see cref="NAudio.Wave.AudioFileReader"/></remarks> public static void WaveToMP3(string waveFileName, string mp3FileName, ID3TagData tag, int bitRate = 128) { using (var reader = new AudioFileReader(waveFileName)) using (var writer = new LameMP3FileWriter(mp3FileName, reader.WaveFormat, 128, tag)) { reader.CopyTo(writer); } }
public static async Task ToMP3(string WaveFileName, string MP3FileName, int bitRate) { await Task.Factory.StartNew(() => { using (var reader = new AudioFileReader(WaveFileName)) using (var writer = new LameMP3FileWriter(MP3FileName, reader.WaveFormat, bitRate)) reader.CopyTo(writer); }); }
// Convert WAV to MP3 using libmp3lame library public static void WaveToMP3(string waveFileName, string mp3FileName, int bitRate = 320) { using (var reader = new AudioFileReader(waveFileName)) { using (var writer = new LameMP3FileWriter(mp3FileName, reader.WaveFormat, bitRate)) { reader.CopyTo(writer); } } }
public void WaveToMP3(string waveFileName, string mp3FileName, int bitRate = 192) { using var reader = new AudioFileReader(waveFileName); using var writer = new LameMP3FileWriter(mp3FileName, reader.WaveFormat, bitRate); reader.CopyTo(writer); var message = $"{mp3FileName} created."; _sendMessageEvent.OnSendMessageEvent(new SendMessageEventArgs(message)); _logger.LogInformation(message); }
public static void WaveToMP3(string waveFileName, string mp3FileName, int bitRate = 128) { try { var readerStream = File.OpenRead(waveFileName); BinaryReader br = new BinaryReader(readerStream); if (br.ReadInt32() != mmioStringToFOURCC("RIFF", 0)) { readerStream.Dispose(); readerStream.Close(); File.Move(waveFileName, mp3FileName); Program.Message(string.Format("Renamed {0} to mp3", waveFileName)); File.Delete(waveFileName); } else { using (var reader = new AudioFileReader(waveFileName)) using (var writer = new LameMP3FileWriter(mp3FileName, reader.WaveFormat, bitRate)) { reader.CopyTo(writer); Program.Message(string.Format("Converted {0} to mp3", waveFileName)); if (reader != null) { reader.CopyTo(writer); //reader.Dispose(); //reader.Close(); } //if (writer != null) //{ // writer.Dispose(); // writer.Close(); //} } //File.Delete(waveFileName); } } catch (Exception ex) { Program.Message(string.Format("{0} ", ex.Message)); } }
private void ConvertFile(string Filename, string outputfile) { using (AudioFileReader reader = new AudioFileReader(Filename)) { writer = new WaveFileWriter(outputfile, reader.WaveFormat); IsDoneConverting = false; reader.CopyTo(writer); } IsDoneConverting = true; writer.Close(); writer.Dispose(); }
private void DoConvert(string fileName) { string target = Path.ChangeExtension(fileName, ".mp3"); using (var reader = new AudioFileReader(fileName)) using (var writer = new LameMP3FileWriter(target, reader.WaveFormat, _quality)) { long length = reader.Length; writer.OnProgress += (sender, inputBytes, outputBytes, finished) => OnProgress(new ConvertProgressEventArgs(fileName, (float)inputBytes / length, false, null)); reader.CopyTo(writer); } }
public static void ConvertToMp3V3(string inPath, string outPath) { using (var reader = new AudioFileReader(inPath)) { if (!Directory.Exists(Path.GetDirectoryName(outPath))) { Directory.CreateDirectory(Path.GetDirectoryName(outPath)); } var writer = new LameMP3FileWriter(outPath, reader.WaveFormat, 128); reader.CopyTo(writer); reader.Dispose(); writer.Dispose(); } }
public void TC03_VBRPreset() { // Presets to test, should result in different sizes for all cases var presets = new[] { LAMEPreset.STANDARD, LAMEPreset.EXTREME, LAMEPreset.ABR_160, LAMEPreset.V1, LAMEPreset.V4, LAMEPreset.V6, LAMEPreset.V9 }; var results = new Dictionary <LAMEPreset, long>(); WaveFormat sourceFormat; using (var srcms = new MemoryStream()) { using (var source = new AudioFileReader(SourceFilename)) { sourceFormat = source.WaveFormat; source.CopyTo(srcms); } foreach (var preset in presets) { var config = new LameConfig { Preset = preset }; if (preset == LAMEPreset.STANDARD) { config.BitRate = 128; } using (var mp3data = new MemoryStream()) { using (var mp3writer = new LameMP3FileWriter(mp3data, sourceFormat, preset)) { srcms.Position = 0; srcms.CopyTo(mp3writer); } results[preset] = mp3data.Length; } } } // Compare encoded sizes for all combinations of presets for (int i = 0; i < presets.Length - 2; i++) { var left = results[presets[i]]; for (int j = i + 1; j < presets.Length; j++) { var right = results[presets[j]]; Assert.AreNotEqual(left, right, $"{presets[i]} size matched {presets[j]}"); } } }
/// <summary>Convert WAV file to MP3 using libmp3lame library, setting ID3 tag</summary> /// <param name="waveFileName">Filename of WAV file to convert</param> /// <param name="mp3FileName">Filename to save to</param> /// <param name="tag">ID3 tag data to insert into file</param> /// <param name="bitRate">MP3 bitrate in kbps, defaults to 128kbps</param> /// <remarks>Uses NAudio to read, can read any file compatible with <see cref="NAudio.Wave.AudioFileReader"/></remarks> public static void WaveToMP3(string waveFileName, string mp3FileName, ID3TagData tag, int bitRate = 128) { byte[] tagBytes = null; using (var reader = new AudioFileReader(waveFileName)) using (var writer = new LameMP3FileWriter(mp3FileName, reader.WaveFormat, 128, tag)) { reader.CopyTo(writer); tagBytes = writer.GetID3v2TagBytes(); } if (tagBytes != null) { var dectag = ID3Decoder.Decode(tagBytes); } }
static void Main(string[] args) { var now = DateTime.Now; var machineName = Environment.MachineName.ToLower(CultureInfo.CurrentCulture); var outputFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "NAudio"); Directory.CreateDirectory(outputFolder); var outputFilepath = Path.Combine(outputFolder, $"output.wav"); var mp3Filepath = Path.Combine(outputFolder, $"{machineName}{now:ddMMdyyyyHHmmss}.mp3"); var waveIn = new WasapiCapture { }; var writer = new WaveFileWriter(outputFilepath, waveIn.WaveFormat); waveIn.StartRecording(); var tm = new System.Timers.Timer(10 * 1000); tm.Elapsed += (sender, eventArgs) => waveIn.StopRecording(); tm.Start(); waveIn.DataAvailable += (sender, eventArgs) => { Console.Write("."); writer.Write(eventArgs.Buffer, 0, eventArgs.BytesRecorded); }; var e = new ManualResetEvent(false); waveIn.RecordingStopped += (sender, eventArgs) => { writer.Dispose(); waveIn.Dispose(); Console.WriteLine("writing mp3"); using (var reader = new AudioFileReader(outputFilepath)) using (var mp3Writer = new LameMP3FileWriter(mp3Filepath, reader.WaveFormat, 128)) reader.CopyTo(mp3Writer); Console.WriteLine("writing done"); e.Set(); }; e.WaitOne(); }
private static Stream EncodeSampleFile(LameConfig config, int copies = 1) { var mp3data = new MemoryStream(); using (var source = new AudioFileReader(SourceFilename)) using (var mp3writer = new LameMP3FileWriter(mp3data, source.WaveFormat, config)) { for (int i = 0; i < copies; i++) { source.Position = 0; source.CopyTo(mp3writer); } } mp3data.Position = 0; return(mp3data); }
public string ExportFile(string preferredFileName = "") { string pseudoUniqueFileName = string.Empty; string exportFolderName = appSettingService.ExportOutputPath; try { var exportFolder = new DirectoryInfo(exportFolderName); if (!exportFolder.Exists) { exportFolder.Create(); } // ToDo ensure file does not exist yet (would now be just overridden without asking) // ToDo ensure unique export file name pseudoUniqueFileName = string.IsNullOrEmpty(preferredFileName) ? Path.Combine(exportFolder.FullName, $"{SelectedFile.Name.Replace(SelectedFile.Extension, ".mp3")}") : Path.Combine(exportFolder.FullName, $"{preferredFileName}.mp3"); var generatedFileInfo = new FileInfo(pseudoUniqueFileName); var generatedFileName = generatedFileInfo.Name.Replace(generatedFileInfo.Extension, string.Empty); // ToDo progress indicator (longer files might take considerably longer to convert :D)) using (var reader = new AudioFileReader(SelectedFile.FullName)) using (var writer = new LameMP3FileWriter( outFileName: pseudoUniqueFileName, format: reader.WaveFormat, quality: (LAMEPreset)Enum.Parse(typeof(LAMEPreset), appSettingService.Mp3ExportBitrate.ToString()), id3: new ID3TagData() { Title = generatedFileName, Comment = "Powered by RecNForget @ https://github.com/DrCopyPaste/RecNForget/releases/latest", Year = DateTime.Now.Year.ToString() } )) reader.CopyTo(writer); } catch (Exception ex) { pseudoUniqueFileName = string.Empty; } return(pseudoUniqueFileName); }
static void ConvertFile(string sourceFileName, string destFileName) { Console.WriteLine($"------------------------------------------------------------"); Console.WriteLine($" Source: {sourceFileName}"); IMFMediaSource mediaSource = GetMediaSource(sourceFileName); int bitRate = GetBitRate(mediaSource); IMFMetadata metadata = GetMetadata(mediaSource); ID3TagData tagData = new ID3TagData() { Title = GetStringProperty(metadata, "Title"), Artist = GetStringProperty(metadata, "Author"), Album = GetStringProperty(metadata, "WM/AlbumTitle"), Year = GetStringProperty(metadata, "WM/Year"), Genre = GetStringProperty(metadata, "WM/Genre"), Track = GetUIntProperty(metadata, "WM/TrackNumber"), AlbumArtist = GetStringProperty(metadata, "WM/AlbumArtist") }; COMBase.SafeRelease(metadata); metadata = null; COMBase.SafeRelease(mediaSource); mediaSource = null; Console.WriteLine($" Title: {tagData.Title}"); Console.WriteLine($"Album artist: {tagData.AlbumArtist}"); Console.WriteLine($" Artist: {tagData.Artist}"); Console.WriteLine($" Album: {tagData.Album}"); Console.WriteLine($" Year: {tagData.Year}"); Console.WriteLine($" Genre: {tagData.Genre}"); Console.WriteLine($" Track: {tagData.Track}"); Console.WriteLine($" Bit rate: {bitRate}"); using (AudioFileReader reader = new AudioFileReader(sourceFileName)) { using (LameMP3FileWriter writer = new LameMP3FileWriter(destFileName, reader.WaveFormat, bitRate, tagData)) { reader.CopyTo(writer); } } Console.WriteLine($" Destination: {destFileName}"); }
static void Main(string[] args) { ID3TagData tag = new ID3TagData { Title = "A Test File", Artist = "Microsoft", Album = "Windows 7", Year = "2009", Comment = "Test only.", Genre = LameMP3FileWriter.Genres[1], Subtitle = "From the Calligraphy theme", AlbumArt = System.IO.File.ReadAllBytes(@"disco.png") }; using (var reader = new AudioFileReader(@"test.wav")) using (var writer = new LameMP3FileWriter(@"test.mp3", reader.WaveFormat, 128, tag)) { reader.CopyTo(writer); } }
/// <summary> /// Связывается с сервисом Yandex.Cloud отправляет текст и получает в ответ файл, который передается в SRS /// </summary> /// <param name="speech">Объект содержащий данные для вывода голосового сообщения</param> /// <returns></returns> public async Task TextToSpeech(Speech speech) { await UpdateIamToken(); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Authorization", "Bearer " + IamToken); var speed = Math.Round(speech.Speed, 1); var values = new Dictionary <string, string> { { "text", speech.Message }, { "voice", speech.Voice }, { "emotion", speech.Emotion }, { "speed", speed.ToString().Replace(",", ".") }, { "lang", speech.Lang }, { "format", "lpcm" }, { "sampleRateHertz", "48000" }, { "folderId", AppSet.Config.FolderId } }; var sampleRate = 48000; var content = new FormUrlEncodedContent(values); var response = await client.PostAsync("https://tts.api.cloud.yandex.net/speech/v1/tts:synthesize", content); if (response.IsSuccessStatusCode) { var responseBytes = await response.Content.ReadAsByteArrayAsync(); var ms = new MemoryStream(responseBytes); var rs = new RawSourceWaveStream(ms, new WaveFormat(sampleRate, 16, 1)); var outpath = "example.wav"; WaveFileWriter.CreateWaveFile(outpath, rs); using (var reader = new AudioFileReader("example.wav")) using (var writer = new LameMP3FileWriter("speech.mp3", reader.WaveFormat, 192)) reader.CopyTo(writer); SendToSRS(speech); } else { Console.WriteLine("Error! Status Code: " + response.StatusCode); } }
public void TC04_OutputSampleRate() { Stream sourceStream; WaveFormat sourceFormat; bool TestSampleRate(int rate) { sourceStream.Position = 0; using (var mp3data = new MemoryStream()) { using (var writer = new LameMP3FileWriter(mp3data, sourceFormat, new LameConfig { OutputSampleRate = rate })) { sourceStream.CopyTo(writer); } mp3data.Position = 0; using (var reader = new Mp3FileReader(mp3data)) { return(reader.Mp3WaveFormat.SampleRate == rate); } } } using (sourceStream = new MemoryStream()) { using (var source = new AudioFileReader(SourceFilename)) { sourceFormat = source.WaveFormat; source.CopyTo(sourceStream); } Assert.IsTrue(TestSampleRate(22050)); Assert.IsTrue(TestSampleRate(11025)); Assert.IsTrue(TestSampleRate(8000)); } }
/// <summary> /// Load in the music files from the pack's respective Directory/Songs folder. Typically Content/Music/Wav/FolderName/Songs /// </summary> public override void loadMusicFiles() { List <string> wavFiles = Directory.GetFiles(this.songsDirectory, "*.wav").ToList(); wavFiles.AddRange(Directory.GetFiles(this.songsDirectory, "*.mp3")); List <Song> listOfSongs = new List <Song>(); DateTime span = DateTime.Now; foreach (var wav in wavFiles) { MemoryStream memoryStream = new MemoryStream(); AudioFileReader fileReader = new AudioFileReader(wav); fileReader.CopyTo(memoryStream); byte[] wavData = memoryStream.ToArray(); SoundEffect eff = null; System.IO.Stream waveFileStream = waveFileStream = File.OpenRead(wav); //TitleContainer.OpenStream(file); if (wav.Contains(".wav")) { eff = SoundEffect.FromStream(waveFileStream); } else if (wav.Contains(".mp3")) { using (Mp3FileReader reader = new Mp3FileReader(waveFileStream)) { using (WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(reader)) { StardewSymphony.ModMonitor.Log("MP3 CONVERT! " + Path.GetFileNameWithoutExtension(wav) + ".wav"); WaveFileWriter.CreateWaveFile(Path.Combine(this.songsDirectory, (Path.GetFileNameWithoutExtension(wav) + ".wav")), pcmStream); waveFileStream = File.OpenRead((Path.GetFileNameWithoutExtension(wav) + ".wav")); //TitleContainer.OpenStream(file); eff = SoundEffect.FromStream(waveFileStream); File.Delete(Path.Combine(this.songsDirectory, (Path.GetFileNameWithoutExtension(wav) + ".wav"))); } } } else if (wav.Contains(".ogg")) { StardewSymphony.ModMonitor.Log("Sorry, but .ogg files are currently not supported. Keep bugging the mod author (me) for this if you want it!", StardewModdingAPI.LogLevel.Alert); continue; } //SoundEffect eff = new SoundEffect(wavData, 48000 , AudioChannels.Mono); if (eff == null) { continue; } SoundEffectInstance instance = eff.CreateInstance(); string name = Path.GetFileNameWithoutExtension(wav); if (this.sounds.ContainsKey(name)) { continue; } this.sounds.Add(name, instance); //waveFileStream.Dispose(); Song song = new Song(wav); this.songInformation.listOfSongsWithoutTriggers.Add(song); //listOfSongs.Add(song); } if (StardewSymphony.Config.EnableDebugLog) { StardewSymphony.ModMonitor.Log("Time to load WAV music pack: " + this.musicPackInformation.name + span.Subtract(DateTime.Now).ToString()); } }
private static void CompressToMP3() { var bitRate = 128; using (var reader = new AudioFileReader(_waveFileName)) using (var writer = new LameMP3FileWriter(_targetFileName, reader.WaveFormat, bitRate)) reader.CopyTo(writer); }
void ConvertToMP3(string waveFileName, string mp3FileName, int bitRate = 128) { using (var reader = new AudioFileReader(waveFileName)) using (var writer = new LameMP3FileWriter(mp3FileName, reader.WaveFormat, bitRate)) reader.CopyTo(writer); }
public void ApplyEffects(string InputFile, string OutputFile, Delegates.DownloadProgressChangedCallback progressCallback = null, CancellationToken cancellationToken = default) { int step = 0; if (Effects.Count != 0) { bool RequiresRencoding = false; int Succeeded = 0; AudioFileReader Reader = new AudioFileReader(InputFile); foreach (AudioEffect Effect in Effects) { if (cancellationToken.IsCancellationRequested) { return; } step++; progressCallback?.Invoke(step, -1, $"Applying effect {Effect.GetType().Name}", null); if (string.IsNullOrEmpty(Effect.AudioCachePath)) { Effect.AudioCachePath = AudioCachePath; } Reader.Position = 0; System.Console.WriteLine($"Applying effect of type {Effect.GetType().Name}"); AudioEffectResult Result = Effect.ApplyEffect(ref Reader); if (Result == AudioEffectResult.Completed) { System.Console.WriteLine("Returned S"); RequiresRencoding = true; Succeeded += 1; } else if (Result == AudioEffectResult.Failed) { System.Console.WriteLine("Effect Failed."); } else if (Result == (AudioEffectResult.Completed | AudioEffectResult.PreEncoded)) { System.Console.WriteLine("Effect Completed + Encoded."); RequiresRencoding = false; Succeeded += 1; } } bool ReEncode; if (Succeeded == 0) { System.Console.WriteLine("Re encoding; No effects passed"); ReEncode = false; } else if (RequiresRencoding) { System.Console.WriteLine("Re encoding; Re-encoding declared as required"); ReEncode = true; } else { System.Console.WriteLine("Copying Stream; Stream declared as pre-encoded"); ReEncode = false; } if (ReEncode) { step++; progressCallback?.Invoke(step, -1, $"Re-encoding mp3", null); System.Console.WriteLine("Re-Encoding..."); using (var writer = new LameMP3FileWriter(OutputFile, Reader.WaveFormat, 128)) { Reader.CopyTo(writer); } Reader.Dispose(); } else { step++; progressCallback?.Invoke(step, -1, $"Finalizing effects", null); System.Console.WriteLine("Copy Out"); File.Copy(Reader.FileName, OutputFile); } } else { File.Copy(InputFile, OutputFile); } }
private void CopyToMP3() { // Time to clear lock Thread.Sleep(10000); if (lastTrack != null) { //Save last track to mp3 var configET = new MapperConfiguration(cfg => cfg.CreateMap <FullTrack, ExtTrack>()); var mapperET = configET.CreateMapper(); string name = CleanString(lastTrack.Name); int remaster = name.IndexOf("- Remaster", StringComparison.CurrentCultureIgnoreCase); if (remaster > 0) { name = name.Substring(0, remaster - 1); } else { remaster = name.IndexOf("/ Remaster", StringComparison.CurrentCultureIgnoreCase); if (remaster > 0) { name = name.Substring(0, remaster - 1); } } remaster = name.IndexOf("Remaster", StringComparison.CurrentCultureIgnoreCase); if (remaster > 0) { name = name.Substring(0, remaster - 1); } string artist = CleanString(lastTrack.Artists[0].Name); ExtTrack extTrack = mapperET.Map <ExtTrack>(lastTrack); extTrack.AddProps(name, artist, ""); List <string> genres = DiscogCall(extTrack, txtAddGenres.Text); string directory = GetMp3Path(extTrack); string fullPathMP3 = directory + @"\" + CleanString(extTrack.Filename) + ".mp3"; Directory.CreateDirectory(directory); // LASTFM - genres dodgy? // extTrack.Year = LastFMCall(extTrack.OCName, extTrack.OCArtist); extTrack.TagGenres = genres.ToArray(); // temporary workaround for problems with genres extTrack.TagGenres = new string[] { string.Join(",", extTrack.TagGenres) }; using (var reader = new AudioFileReader(WAVPATH + (fileToCopy == 1 ? "thisTrack1.wav" : "thisTrack2.wav"))) using (var writer = new LameMP3FileWriter(fullPathMP3, reader.WaveFormat, BITRATE)) reader.CopyTo(writer); //tag mp3 file TagLib.File mp3 = TagLib.File.Create(fullPathMP3); mp3.Tag.Title = extTrack.Filename; mp3.Tag.Performers = extTrack.TagArtists; mp3.Tag.Album = extTrack.Album.Name; mp3.Tag.AlbumArtists = extTrack.TagArtists; mp3.Tag.Genres = extTrack.TagGenres; //mp3.Tag.Comment = "my comments, maybe some info about track"; if (extTrack.Year != null) { mp3.Tag.Year = (uint)extTrack.Year; } mp3.Save(); mp3.Dispose(); } }
private static void WaveToMP3(string waveFileName, string mp3FileName, ExtTrack extTrack, int bitRate = 320) { //get genres genres = new List <string>(); DiscogCall(extTrack); string directory = savePathMP3 + "\\" + CleanString(extTrack.TagArtists[0]) + "\\" + CleanString(extTrack.Album.Name); string fullPathMP3 = directory + "\\" + CleanString(extTrack.Filename) + ".mp3"; Directory.CreateDirectory(directory); // LASTFM - genres dodgy? // extTrack.Year = LastFMCall(extTrack.OCName, extTrack.OCArtist); extTrack.TagGenres = genres.ToArray(); // temporary workaround for problems with genres extTrack.TagGenres = new string[] { string.Join(",", extTrack.TagGenres) }; //Stopwatch timer = new Stopwatch(); //timer.Start(); using (var reader = new AudioFileReader(waveFileName)) using (var writer = new LameMP3FileWriter(fullPathMP3, reader.WaveFormat, bitRate)) reader.CopyTo(writer); //timer.Stop(); //long elapsedSecs = timer.ElapsedMilliseconds / 1000; //tag wav file TagLib.File wav = TagLib.File.Create(waveFileName); wav.Tag.Title = extTrack.Filename; wav.Tag.Performers = extTrack.TagArtists; wav.Tag.Album = extTrack.Album.Name; wav.Tag.AlbumArtists = extTrack.TagArtists; wav.Tag.Genres = extTrack.TagGenres; //wav.Tag.Comment = "my comments, maybe some info about track"; if (extTrack.Year != null) { wav.Tag.Year = (uint)extTrack.Year; } wav.Save(); wav.Dispose(); //tag mp3 file TagLib.File mp3 = TagLib.File.Create(fullPathMP3); mp3.Tag.Title = extTrack.Filename; mp3.Tag.Performers = extTrack.TagArtists; mp3.Tag.Album = extTrack.Album.Name; mp3.Tag.AlbumArtists = extTrack.TagArtists; mp3.Tag.Genres = extTrack.TagGenres; //mp3.Tag.Comment = "my comments, maybe some info about track"; if (extTrack.Year != null) { mp3.Tag.Year = (uint)extTrack.Year; } mp3.Save(); mp3.Dispose(); // update table with filepath of mp3. OfficialChartsEntities db2 = new OfficialChartsEntities(); var record = db2.Tracks.SingleOrDefault(b => b.TrackID == extTrack.OCID); if (record != null) { record.PathOnDisc = fullPathMP3; db2.SaveChanges(); } // CheckFileTags(extTrack.Filename); }
// Save the last minute of audio private void Button_Save_Click(object sender, RoutedEventArgs e) { Task.Run(() => { // Show Saving message for 1 seconds SavingMsgVis = true; Thread.Sleep(1000); SavingMsgVis = false; }); Task.Run(() => { // Create output filename string outFileNameSpeakerWav = DateTime.Now.ToLongDateString() + "_" + DateTime.Now.ToLongTimeString().Replace(":", ".") + "_Speaker.wav"; string outFileNameMicWav = DateTime.Now.ToLongDateString() + "_" + DateTime.Now.ToLongTimeString().Replace(":", ".") + "_Mic.wav"; string outFileNameMuxWav = DateTime.Now.ToLongDateString() + "_" + DateTime.Now.ToLongTimeString().Replace(":", ".") + "_Mux.wav"; string outFileNameMp3 = DateTime.Now.ToLongDateString() + "_" + DateTime.Now.ToLongTimeString().Replace(":", ".") + ".mp3"; // Write speaker audio to disk var wavWriter = new WaveFileWriter(Path.Combine(OutputLocation, outFileNameSpeakerWav), audioCapture.WaveFormat); byte[] writeBytes = speakerBytes.ToArray(); wavWriter.Write(writeBytes, 0, writeBytes.Length); wavWriter.Dispose(); wavWriter = null; // Write mic audio to disk if (InputDeviceId != -9999) { wavWriter = new WaveFileWriter(Path.Combine(OutputLocation, outFileNameMicWav), audioCapture.WaveFormat); writeBytes = micBytes.ToArray(); wavWriter.Write(writeBytes, 0, writeBytes.Length); wavWriter.Dispose(); wavWriter = null; } // Mux mic and speaker audio if (InputDeviceId != -9999) { //using (var reader1 = new AudioFileReader(Path.Combine(OutputLocation, outFileNameSpeakerWav))) //using (var reader2 = new AudioFileReader(Path.Combine(OutputLocation, outFileNameMicWav))) //{ // reader1.Volume = 0.75f; // reader2.Volume = 0.75f; // var mixer = new MixingSampleProvider(new[] { reader1, reader2 }); // WaveFileWriter.CreateWaveFile16(Path.Combine(OutputLocation, outFileNameMuxWav), mixer); //} using (var reader1 = new AudioFileReader(Path.Combine(OutputLocation, outFileNameSpeakerWav))) using (var reader2 = new AudioFileReader(Path.Combine(OutputLocation, outFileNameMicWav))) { reader1.Volume = 0.75f; reader2.Volume = 0.75f; var mixer = new MixingSampleProvider(new[] { reader1, reader2 }); var waveProvider = mixer.ToWaveProvider(); var mp3Writer = new LameMP3FileWriter(Path.Combine(OutputLocation, outFileNameMp3), mixer.WaveFormat, 128); WaveProviderToWaveStream waveStream = new WaveProviderToWaveStream(waveProvider); waveStream.CopyTo(mp3Writer); waveStream.Dispose(); mp3Writer.Dispose(); } } else { using (var reader = new AudioFileReader(Path.Combine(OutputLocation, outFileNameSpeakerWav))) using (var writer = new LameMP3FileWriter(Path.Combine(OutputLocation, outFileNameMp3), reader.WaveFormat, 128)) reader.CopyTo(writer); } // Delete original wav file File.Delete(Path.Combine(OutputLocation, outFileNameSpeakerWav)); if (InputDeviceId != -9999) { File.Delete(Path.Combine(OutputLocation, outFileNameMicWav)); File.Delete(Path.Combine(OutputLocation, outFileNameMuxWav)); } // Show saved message for 2 seconds SavedMsgVis = true; Thread.Sleep(2000); SavedMsgVis = false; }); }