Пример #1
0
        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();
            }
        }
Пример #2
0
        /// <summary>
        ///  Convert WAV to MP3 using libmp3lame library
        /// </summary>
        /// <param name="waveFileName">WAV filename</param>
        /// <param name="mp3FileName">MP3 filename</param>
        /// <param name="bitRate">Bit rate, default 128</param>
        /// <param name="artist">Optional artist name</param>
        /// <param name="album">Optional album name</param>
        /// <param name="setID3Tags">Set ID3 tags</param>
        public static bool WavToMP3(string waveFileName, string mp3FileName, int bitRate = 128, string artist = null, string album = null, bool setID3Tags = false, string genre = "148")
        {
            bool result = true;
            try
            {
                ID3TagData tags = new ID3TagData();
                if (setID3Tags)
                {
                    if (!String.IsNullOrEmpty(artist))
                    {
                        tags.Artist = artist;
                        tags.Album = album;
                        tags.Genre = genre;
                    }
                }

                using (var reader = new WaveFileReader(waveFileName))
                using (var writer = new LameMP3FileWriter(mp3FileName, reader.WaveFormat, bitRate, tags))
                    reader.CopyTo(writer);

            }
            catch (Exception)
            {
                result = false;
            }

            return result;
        }
Пример #3
0
        // Compare the properties of two tags, throw assertion exception on any apparent differences
        private static void CompareTags(ID3TagData left, ID3TagData right)
        {
            Assert.IsNotNull(right);

            // confirm elements are the same
            Assert.AreEqual(left.Title, right.Title, "Title mismatch");
            Assert.AreEqual(left.Artist, right.Artist, "Artist mismatch");
            Assert.AreEqual(left.Album, right.Album, "Album mismatch");
            Assert.AreEqual(left.Year, right.Year, "Year mismatch");
            Assert.AreEqual(left.Comment, right.Comment, "Comment mismatch");
            Assert.AreEqual(left.Genre, right.Genre, "Genre mismatch");
            Assert.AreEqual(left.Subtitle, right.Subtitle, "Subtitle mismatch");
            Assert.AreEqual(left.AlbumArtist, right.AlbumArtist, "AlbumArtist mismatch");
            Assert.AreEqual(left.UserDefinedText.Count, right.UserDefinedText.Count, "UserDefinedText count mismatch");

            foreach (var key in left.UserDefinedText.Keys)
            {
                Assert.IsTrue(right.UserDefinedText.ContainsKey(key));
                Assert.AreEqual(left.UserDefinedText[key], right.UserDefinedText[key], $"UDT[{key}] mismatch.");
            }

            Assert.AreEqual(left.AlbumArt?.Length ?? -1, right.AlbumArt?.Length ?? -1);
            if (left.AlbumArt != null)
            {
                Assert.IsTrue(System.Linq.Enumerable.SequenceEqual(left.AlbumArt, right.AlbumArt));
            }
        }
Пример #4
0
        public static async Task <string> WaveToMP3Async(string waveFileName,
                                                         string mp3FileName,
                                                         int bitRate              = 192,
                                                         string title             = "",
                                                         string subtitle          = "",
                                                         string comment           = "",
                                                         string artist            = "",
                                                         string albumArtist       = "",
                                                         string album             = "",
                                                         string year              = "",
                                                         string track             = "",
                                                         string genre             = "",
                                                         byte[] albumArt          = null,
                                                         string[] userDefinedTags = null)
        {
            ID3TagData tag = new ID3TagData
            {
                Title           = title,
                Artist          = artist,
                Album           = album,
                Year            = year,
                Comment         = comment,
                Genre           = LameMP3FileWriter.Genres[36], // 36 is game.  FUll list @ http://ecmc.rochester.edu/ecmc/docs/lame/id3.html
                Subtitle        = subtitle,
                AlbumArt        = albumArt,
                AlbumArtist     = albumArtist,
                Track           = track,
                UserDefinedTags = userDefinedTags
            };

            var reader = new AudioFileReader(waveFileName);

            if (reader.WaveFormat.Channels <= 2)
            {
                using (reader)
                {
                    using (var writer = new LameMP3FileWriter(mp3FileName, reader.WaveFormat, bitRate, tag))
                        await reader.CopyToAsync(writer); //reader.CopyTo(writer);
                }
            }
            else if (reader.WaveFormat.Channels > 2)
            {
                reader.Dispose();
                mp3FileName = string.Empty;
                SplitWav(waveFileName);
                var fileNames = MixSixChannel(waveFileName);
                foreach (var fileName in fileNames)
                {
                    using (reader = new AudioFileReader(fileName))
                    {
                        using (var writer = new LameMP3FileWriter(fileName.Replace(".wav", ".mp3"), reader.WaveFormat, bitRate, tag))
                            await reader.CopyToAsync(writer);
                        mp3FileName += fileName.Replace(".wav", ".mp3") + " ";
                    }
                }
            }

            return($"{mp3FileName} created.\r\n\r\n");
        }
Пример #5
0
 /// <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);
         }
 }
Пример #6
0
        /// <summary>
        /// Convert a WAV into MP3 file
        /// </summary>
        /// <param name="inputFile">Input WAV files path</param>
        /// <param name="outputFile">Output MP3 file path</param>
        /// <param name="id3Tag">MP3 tags</param>
        public static void WavToMp3(string inputFile, string outputFile, ID3TagData id3Tag)
        {
            var reader = new WaveFileReader(inputFile);
            var writer = new LameMP3FileWriter(outputFile, reader.WaveFormat, ExportQuality, id3Tag);

            reader.CopyTo(writer);
            writer.Close();
            reader.Close();
        }
Пример #7
0
        // Write tag to file, read it back, then ensure that the two match.
        private static void CheckTagRoundTrip(ID3TagData tag)
        {
            // round-trip the tag
            var newTag = GetTagAsWritten(tag);

            Assert.IsNotNull(newTag);

            // confirm the the various elements are the same
            CompareTags(tag, newTag);
        }
Пример #8
0
        internal static void UpdateSongInfo()
        {
            if (IsDefaultStaion)
            {
                ID3TagData TempID3 = new ID3TagData();

                using (WebClient client = new WebClient())
                {
                    SongInfo.CurrentSong = GetSong(client, SongInfo.RadioStation.Endpoints.Song);
                    while (true)
                    {
                        TempID3 = GetSong(client, SongInfo.RadioStation.Endpoints.Song);
                        if (SongInfo.CurrentSong.Artist != TempID3.Artist && SongInfo.CurrentSong.Title != TempID3.Title)
                        {
                            if (!SongInfo.IsContinuous)
                            {
                                if (RecordStreamThread.ThreadState == ThreadState.Running)
                                {
                                    RecordStreamThread.Abort();
                                }

                                Thread.Sleep(1000 * SongInfo.StreamDelay);

                                SongInfo.CurrentSong   = TempID3;
                                SongInfo.Elapsed.Value = 0;

                                if (RecordStreamThread.ThreadState == ThreadState.Aborted)
                                {
                                    if (Mp3Reader != null)
                                    {
                                        Mp3Reader = null;
                                    }
                                    if (Mp3Writer != null)
                                    {
                                        Mp3Writer = null;
                                    }

                                    RecordStreamThread = new Thread(RecordStream);
                                    RecordStreamThread.Start();
                                }
                            }
                        }
                        UpdateElapsed();
                    }
                }
            }
            else
            {
                while (true)
                {
                    UpdateElapsed();
                }
            }
        }
Пример #9
0
        private void convertToMp3()
        {
            if (IsRecording)
            {
                return;
            }

            int i          = 0;
            var outputFile = Path.Combine(SettingsFile.Instance.SavePath, buildFileName(i));

            while (File.Exists(outputFile))
            {
                outputFile = Path.Combine(SettingsFile.Instance.SavePath, buildFileName(++i));
            }

            try {
                log.Debug($"Generating mp3: {outputFile}");

                var tag = new ID3TagData();
                tag.UserDefinedText.Add("CallId", Call.CallId);
                tag.UserDefinedText.Add("From", Call.From?.SkypeId);
                tag.UserDefinedText.Add("FromDisplayName", Call.From?.DisplayName);
                tag.UserDefinedText.Add("To", Call.To?.SkypeId);
                tag.UserDefinedText.Add("ToDisplayName", Call.To?.DisplayName);

                var mixer = new WaveMixerStream32 {
                    AutoStop = true
                };

                log.Debug($"  adding wave input: {_micSourceFile}");
                addMixerStream(mixer, _micSourceFile);
                log.Debug($"  adding wave input: {_spkSourceFile}");
                addMixerStream(mixer, _spkSourceFile);

                log.Debug($"  encoding");
                var wave32    = new Wave32To16Stream(mixer);
                var mp3Writer = new LameMP3FileWriter(outputFile, wave32.WaveFormat, LAMEPreset.VBR_90, tag);
                wave32.CopyTo(mp3Writer);

                // close all streams
                wave32.Close();
                mp3Writer.Close();

                log.Debug($"  finished, removing temp files");

                File.Delete(_micSourceFile);
                File.Delete(_spkSourceFile);
            }
            catch (Exception ex) {
                log.Error("Error generating mp3: " + ex.Message, ex);
            }
        }
Пример #10
0
        /// <summary>
        /// Concat a list of WAV in a MP3 file
        /// </summary>
        /// <param name="inputFiles">List of input WAV files paths</param>
        /// <param name="outputFile">Output MP3 file path</param>
        /// <param name="id3Tag">MP3 tags</param>
        public static void WavToMp3(List <string> inputFiles, string outputFile, ID3TagData id3Tag)
        {
            var writer = new LameMP3FileWriter(outputFile, TempWaveFormat, ExportQuality, id3Tag);

            foreach (var inputFile in inputFiles)
            {
                var reader = new WaveFileReader(inputFile);
                reader.CopyTo(writer);
                reader.Close();
            }
            writer.Flush();
            writer.Close();
        }
Пример #11
0
        private void splitWavPrep(string albumPath, string filePath)
        {
            string artist = artistTxt.Text;
            MediaFoundationReader reader = new MediaFoundationReader(filePath);
            int bytesPerMilliSecond      = reader.WaveFormat.AverageBytesPerSecond / 1000;

            for (int i = 0; i < tracks.Count; i++)
            {
                int startMilliSeconds = getFullMilliSeconds(tracks[i].StartTime);

                string trackName = tracks[i].Title;

                int duration;
                if (i < tracks.Count - 1)
                {
                    //if there's a next track
                    duration = (int)getFullMilliSeconds(tracks[i + 1].StartTime) - startMilliSeconds;
                }
                else
                {
                    //this is the last track
                    duration = (int)reader.TotalTime.TotalMilliseconds - startMilliSeconds;
                }
                int startPos = startMilliSeconds * bytesPerMilliSecond;
                startPos = startPos - startPos % reader.WaveFormat.BlockAlign;
                int endMilliSeconds = startMilliSeconds + duration;
                int endBytes        = (endMilliSeconds - startMilliSeconds) * bytesPerMilliSecond;
                endBytes = endBytes - endBytes % reader.WaveFormat.BlockAlign;

                int endPos = startPos + endBytes;

                string trackPath = Path.Combine(albumPath, trackName + ".mp3");

                ID3TagData tag = new ID3TagData
                {
                    Title       = trackName,
                    Artist      = artist,
                    Album       = albumNameTxt.Text,
                    Comment     = "YT2MP3 https://github.com/teknoalex/YT2MP3",
                    AlbumArtist = artist,
                    Track       = i.ToString(),
                    AlbumArt    = getThumbnail(id)
                };



                splitMp3(trackPath, startPos, endPos, reader, tag);
            }
        }
Пример #12
0
        public void Test_Issue42()
        {
            var waveFormat = new WaveFormat();
            var tag        = new ID3TagData {
                Album = "Album"
            };

            using (var ms = new MemoryStream())
                using (var writer = new LameMP3FileWriter(ms, waveFormat, LAMEPreset.STANDARD, tag))
                {
                    byte[] empty = new byte[8192];
                    writer.Write(empty, 0, 8192);
                    writer.Flush();
                }
        }
Пример #13
0
        // Create an in-memory MP3 file with the supplied ID3v2 tag, then read the tag back from the MP3 file
        private static ID3TagData GetTagAsWritten(ID3TagData tag)
        {
            var waveFormat = new WaveFormat();

            using (var ms = new MemoryStream())
            {
                using (var writer = new LameMP3FileWriter(ms, waveFormat, LAMEPreset.STANDARD, tag))
                {
                    byte[] empty = new byte[8192];
                    writer.Write(empty, 0, 8192);
                    writer.Flush();
                }
                ms.Position = 0;
                return(ID3Decoder.Decode(ReadID3v2Tag(ms)));
            }
        }
Пример #14
0
        /// <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);
            }
        }
Пример #15
0
        static void ID3Test()
        {
            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")
            };

            Codec.WaveToMP3("test.wav", "test_id3.mp3", tag);
        }
Пример #16
0
        public MyAudioClass(string filename, InputClass config, ID3TagData tagData)
        {
//            _filename = filename;
            _config    = config;
            _txtWriter = File.CreateText($"{filename}.txt");
            var format = new WaveFormat(config.SampleRate, 16, 2);

            _mp3Writer = new LameMP3FileWriter($"{filename}.mp3", format, 128, tagData);
//            var outfile = $"{filename}.wav";
            var outfile = _rawStream;

            _writer  = new WaveFileWriter(outfile, format);
            _lrc     = new LrcClass($"{filename}.lrc");
            _speaker = new SpeechSynthesizer();
            _speaker.SelectVoice(_config.SpeakVoice);
            _speaker.Rate   = _config.Speed;
            _speaker.Volume = _config.Volume;
        }
Пример #17
0
        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}");
        }
Пример #18
0
        public static void Main(string[] args)
        {
            CheckAddBinPath();
            Console.Write("请输入文件名: ");
            var name = Console.ReadLine();

            if (name == null)
            {
                return;
            }

            if (!File.Exists($"{name}/in.json"))
            {
                Console.WriteLine("文件不存在,新建配置");
                Directory.CreateDirectory(name);
                var config   = InputClass.Default;
                var inWriter = File.CreateText($"{name}/in.json");
                inWriter.Write(JsonConvert.SerializeObject(config));
                inWriter.Close();
                Console.WriteLine("配置新建完成!");
                return;
            }
            var streamReader = File.OpenText($"{name}/in.json");
            var input        = JsonConvert.DeserializeObject <InputClass>(streamReader.ReadToEnd());

            streamReader.Close();

            var tag = new ID3TagData
            {
                Album   = name,
                Artist  = "WayZer",
                Comment = "Made by WordVoiceCreater(by Way__Zer)",
            };

            for (int i = 0, n = 0; i < input.Parts.Length; n += input.Parts[i], i++)
            {
                var i1 = i;
                tag.Title = $"{name}-{i1 + 1}";
                var audiof = new MyAudioClass($"{name}/{name}.part{i1+1}", input, tag);
                audiof.Run(n, i1);
                audiof.Close();
            }
        }
Пример #19
0
        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);
                }
        }
        private void ReadAudioTrack(
            int track, ExtractionPaths paths, ProgressReporter progress)
        {
            Directory.CreateDirectory(paths.OutputDirectory);

            string     outputPath = GenerateOutputPath(paths, track - 1);
            ID3TagData metadata   = GenerateTrackMetadata(track - 1);

            using (var mp3Writer = new LameMP3FileWriter(
                       outputPath, new WaveFormat(), LAMEPreset.STANDARD, metadata))
            {
                CdDataReadEventHandler     onDataRead = (x, y) => OnDataRead(x, y, mp3Writer);
                CdReadProgressEventHandler onProgress = (x, y) => OnTrackProgress(x, y, progress);

                if (m_drive.ReadTrack(track, onDataRead, onProgress) == 0)
                {
                    throw new InvalidOperationException($"Cannot read track {track}");
                }
            }
        }
Пример #21
0
        public void Encode(Stream source, string outputPath, SongTags tags, byte[] reusedBuffer)
        {
            WaveFileReader    reader = null;
            LameMP3FileWriter writer = null;

            try             //Idk if using captures the original instance - clearer to just use try-finally
            {
                reader = new WaveFileReader(source);

                var id3 = new ID3TagData()
                {
                    Artist = tags.Artist,
                    Title  = tags.Title,
                };

                if (LamePreset != null)
                {
                    writer = new LameMP3FileWriter(outputPath, reader.WaveFormat, LamePreset.GetValueOrDefault(), id3);
                }
                else if (BitRate != null)
                {
                    writer = new LameMP3FileWriter(outputPath, reader.WaveFormat, BitRate.GetValueOrDefault(), id3);
                }
                else
                {
                    writer = new LameMP3FileWriter(outputPath, reader.WaveFormat, LAMEPreset.STANDARD, id3);
                }

                while (reader.Position < reader.Length)
                {
                    int bytesRead = reader.Read(reusedBuffer, 0, reusedBuffer.Length);
                    writer.Write(reusedBuffer, 0, bytesRead);
                }
            }
            finally
            {
                reader?.Dispose();
                writer?.Dispose();
            }
        }
Пример #22
0
        private static ID3TagData MakeDefaultTag()
        {
            var res = new ID3TagData
            {
                Title       = "Title",
                Artist      = "Artist",
                Album       = "Album",
                Year        = "1999",
                Comment     = "Comment, standard ASCII",
                Genre       = @"Other",
                Track       = "7",
                Subtitle    = "Subtitle",
                AlbumArtist = "AlbumArtist",
            };

            res.SetUDT(new string[]
            {
                @"UDF01=Some simple ASCII text",
                @"Empty=",
            });
            return(res);
        }
Пример #23
0
        static void ID3Test()
        {
            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")
            };

            tag.SetUDT(new[]
            {
                "udf1=First UDF added",
                "udf2=Second UDF",
                "unicode1=Unicode currency symbols: ₠ ₡ ₢ ₣ ₤ ₥ ₦ ₧ ₨ ₩ ₪ ₫"
            });

            Codec.WaveToMP3("test.wav", "test_id3.mp3", tag);
        }
Пример #24
0
        public bool SaveMP3(List <string> saveLocationList)
        {
            string tempFilename = System.IO.Path.GetFileNameWithoutExtension(myrecorder.FilePath);

            int cnt = 0;

            foreach (var p in saveLocationList)
            {
                if (p != "" && !System.IO.Directory.Exists(p))
                {
                    var x1 = new SpecialMessageBox();
                    x1.ShowMessage(parent, "Error", "Check the save location(s)", String.Format("The save location \"{0}\" does not exist. Enter a valid location, or, leave it empty to skip.", p));
                    return(false);
                }

                cnt++;
            }
            if (cnt == 0)
            {
                var x1 = new SpecialMessageBox();
                x1.ShowMessage(parent, "Error", "Check the save location(s)", String.Format("No save locations specified. Enter at least one location to save the MP3."));
                return(false);
            }

            // path to the temporary location where the raw recording is saved (i.e. the WAV file),
            // not including the file extension.
            string tempRecordingPath = System.IO.Path.Combine(appPreferences.TempLocation, tempFilename);

            //if (!_usingCustomPath && File.Exists(saveLocation.Text) &&
            //    MessageBox.Show("A file with the same name exists, overwrite?", "File exists", MessageBoxButtons.YesNo,
            //        MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No) return;
            //btnSave.Enabled = false;
            foreach (var p in saveLocationList)
            {
                if (p != "")
                {
                    var testFile = System.IO.Path.Combine(p, tempFilename + ".mp3");
                    if (System.IO.File.Exists(testFile))
                    {
                        var x1 = new SpecialMessageBox();
                        x1.ShowMessage(parent, "Error", "Sermon not saved.", String.Format("The MP3 export was aborted because the file already exists at the save location:\n\n\"" + testFile + "\""));
                        return(false);
                    }
                }
            }

            var tag = new ID3TagData
            {
                Title       = _title.Trim(),
                Artist      = _speaker.Trim(),
                Album       = _series.Trim(),
                Year        = $"{Recorder.StartTime.Year:#0000}{Recorder.StartTime.Month:#00}{Recorder.StartTime.Day:#00}",
                Comment     = _passage,
                AlbumArtist = _service.Trim(),
                Genre       = "swec.org.au"
            };

            //TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Normal);
            //TaskbarManager.Instance.SetProgressValue(0, 1);

            using (var inputWave = new WaveFileReader(myrecorder.FilePath))
                using (var compressor = new SimpleCompressorStream(inputWave)
                {
                    Attack = (float)1.5,
                    Enabled = true,
                    Threshold = 10,
                    Ratio = 4,
                    MakeUpGain = -3
                })
                    using (var writer = new LameMP3FileWriter(tempRecordingPath + ".compressed.mp3", inputWave.WaveFormat,
                                                              LAMEPreset.MEDIUM,
                                                              tag))
                    {
                        writer.MinProgressTime = 0;
                        writer.OnProgress     += (w, i, o, f) =>
                        {
                            //if (f) Close(); //??? throw...
                            //else UpdateProgressBar(i, inputWave.Length);
                        };

                        var bytesPerMillisecond = inputWave.WaveFormat.AverageBytesPerSecond / 1000;

                        var startPos = 0; // (int)waveform.TimeStart.TotalMilliseconds * bytesPerMillisecond;

                        var endBytes = 0; // (int)waveform.TimeEnd.TotalMilliseconds * bytesPerMillisecond;
                        endBytes = endBytes - endBytes % inputWave.WaveFormat.BlockAlign;
                        var endPos = (int)inputWave.Length - endBytes;

                        inputWave.Position = startPos - startPos % inputWave.WaveFormat.BlockAlign;
                        var buffer = new byte[1024];
                        while (inputWave.Position < endPos)
                        {
                            var bytesRequired = (int)(endPos - inputWave.Position);
                            if (bytesRequired > 0)
                            {
                                var bytesToRead = Math.Min(bytesRequired, buffer.Length);
                                var bytesRead   = compressor.Read(buffer, 0, bytesToRead);
                                if (bytesRead > 0)
                                {
                                    writer.Write(buffer, 0, bytesRead);
                                }
                            }
                        }
                    }

            using (var inputWave = new WaveFileReader(myrecorder.FilePath))
                using (var writer = new LameMP3FileWriter(tempRecordingPath + ".mp3", inputWave.WaveFormat, LAMEPreset.MEDIUM, tag))
                {
                    inputWave.CopyTo(writer);
                }

            foreach (var p in saveLocationList)
            {
                if (p != "")
                {
                    System.IO.File.Copy(tempRecordingPath + ".compressed.mp3", System.IO.Path.Combine(p, tempFilename + ".mp3"));
                }
            }

            // Cleanup
            System.IO.File.Delete(tempRecordingPath + ".mp3");
            System.IO.File.Delete(tempRecordingPath + ".compressed.mp3");

            return(true);
        }
Пример #25
0
        private async Task ConvertAsync(
            string waveFileName,
            string mp3FileName,
            int bitRate        = 192,
            string title       = "",
            string subtitle    = "",
            string comment     = "",
            string artist      = "",
            string albumArtist = "",
            string album       = "",
            string year        = "",
            string track       = "",
            string genre       = "",
            byte[] albumArt    = null)
        {
            var tag = new ID3TagData
            {
                Title       = title,
                Artist      = artist,
                Album       = album,
                Year        = year,
                Comment     = comment,
                Genre       = genre.Length == 0 ? LameMP3FileWriter.Genres[36] : genre, // 36 is game.  Full list @ http://ecmc.rochester.edu/ecmc/docs/lame/id3.html
                Subtitle    = subtitle,
                AlbumArt    = albumArt,
                AlbumArtist = albumArtist,
                Track       = track
            };
            var reader = new AudioFileReader(waveFileName);

            if (reader.WaveFormat.Channels <= 2)
            {
                using (reader)
                    using (var writer = new LameMP3FileWriter(mp3FileName, reader.WaveFormat, bitRate, tag))
                    {
                        await reader.CopyToAsync(writer);
                    }
                var createMessage = $"{mp3FileName} created";
                _sendMessageEvent.OnSendMessageEvent(new SendMessageEventArgs(createMessage));
                _logger.LogInformation(createMessage);
            }
            else if (reader.WaveFormat.Channels == 4 || reader.WaveFormat.Channels == 6)
            {
                reader.Dispose();
                mp3FileName = string.Empty;
                await Task.Run(() => SplitWav(waveFileName));

                var fileNames = MixSixChannel(waveFileName);
                foreach (var fileName in fileNames)
                {
                    using (reader = new AudioFileReader(fileName))
                    {
                        using (var writer = new LameMP3FileWriter(fileName.Replace(".wav", ".mp3"), reader.WaveFormat, bitRate: bitRate, id3: tag))
                        {
                            await reader.CopyToAsync(writer);
                        }
                        mp3FileName += string.IsNullOrEmpty(mp3FileName) ? fileName.Replace(".wav", ".mp3") + " & " : fileName.Replace(".wav", ".mp3");
                    }
                }
                var createMessage = $"{mp3FileName} created";
                _sendMessageEvent.OnSendMessageEvent(new SendMessageEventArgs(createMessage));
                _logger.LogInformation(createMessage);
            }
            else
            {
                throw new Exception($"Could not convert {mp3FileName.Trim()}: It has {reader.WaveFormat.Channels} channels.");
            }
        }
Пример #26
0
        private static void mixFinalAudio(string outputFilename, List <KeyPosition> sounds, List <string> samples)
        {
            var mixedSamples = new List <OffsetSampleProvider>();

            // Find P1 and P2 ends
            int[] playerEnd = { -1, -1 };
            foreach (var sound in sounds)
            {
                if (sound.keysoundId == -1 && sound.key == -1)
                {
                    playerEnd[sound.player] = sound.offset;
                }
            }

            foreach (var sound in sounds)
            {
                if (sound.keysoundId == -1)
                {
                    continue;
                }

                var audioFile = new AudioFileReader(samples[sound.keysoundId]);
                var volSample = new VolumeSampleProvider(audioFile);

                if (volSample.WaveFormat.Channels == 1)
                {
                    volSample = new VolumeSampleProvider(volSample.ToStereo());
                }

                if (volSample.WaveFormat.SampleRate != 44100)
                {
                    // Causes pop sound at end of audio
                    volSample = new VolumeSampleProvider(
                        new WaveToSampleProvider(
                            new MediaFoundationResampler(
                                new SampleToWaveProvider(volSample),
                                WaveFormat.CreateIeeeFloatWaveFormat(44100, 2)
                                )
                    {
                        ResamplerQuality = 60
                    }
                            )
                        );
                }

                if (options.AssistClap && sound.keysoundId == assistClapIdx)
                {
                    volSample.Volume = options.AssistClapVolume;
                }
                else
                {
                    volSample.Volume = options.RenderVolume;
                }

                var sample = new OffsetSampleProvider(volSample);
                sample.DelayBy = TimeSpan.FromMilliseconds(sound.offset);

                if (sound.player >= 0 && sound.player <= 1 && playerEnd[sound.player] != -1 && sound.offset + audioFile.TotalTime.TotalMilliseconds > playerEnd[sound.player])
                {
                    sample.Take = TimeSpan.FromMilliseconds(playerEnd[sound.player] - sound.offset);
                }

                mixedSamples.Add(sample);
            }

            var mixers = new List <MixingSampleProvider>();

            for (int i = 0; i < mixedSamples.Count; i += 128)
            {
                var arr = mixedSamples.Skip(i).Take(128).ToArray();
                mixers.Add(new MixingSampleProvider(arr));
            }

            var mixer = new MixingSampleProvider(mixers);

            if (options.OutputFormat.ToLower() == "wav")
            {
                WaveFileWriter.CreateWaveFile16(outputFilename, mixer);
            }
            else if (options.OutputFormat.ToLower() == "mp3")
            {
                var tempFilename = GetTempFileName();

                WaveFileWriter.CreateWaveFile16(tempFilename, mixer);

                ID3TagData id3 = new ID3TagData();
                id3.Album       = options.Id3Album;
                id3.AlbumArtist = options.Id3AlbumArtist;
                id3.Title       = options.Id3Title;
                id3.Artist      = options.Id3Artist;
                id3.Genre       = options.Id3Genre;
                id3.Track       = options.Id3Track;
                id3.Year        = options.Id3Year;

                using (var reader = new AudioFileReader(tempFilename))
                    using (var writer = new LameMP3FileWriter(outputFilename, reader.WaveFormat, 320, id3))
                    {
                        reader.CopyTo(writer);
                    }

                File.Delete(tempFilename);
            }
        }
Пример #27
0
        private void BtnSave_Click(object sender, EventArgs e)
        {
            if (!_usingCustomPath && File.Exists(saveLocation.Text) &&
                MessageBox.Show("A file with the same name exists, overwrite?", "File exists", MessageBoxButtons.YesNo,
                                MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
            {
                return;
            }
            btnSave.Enabled = false;
            var tag = new ID3TagData
            {
                Title       = _title.Text.Trim(),
                Artist      = _speaker.Text.Trim(),
                Album       = _series.Text.Trim(),
                Year        = $"{Recorder.StartTime.Year:#0000}{Recorder.StartTime.Month:#00}{Recorder.StartTime.Day:#00}",
                Comment     = _passage.Text,
                AlbumArtist = _service.Text.Trim(),
                Genre       = "swec.org.au"
            };

            TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Normal);
            TaskbarManager.Instance.SetProgressValue(0, 1);

            using (var inputWave = new WaveFileReader(Recorder.FilePath))
                using (var compressor = new SimpleCompressorStream(inputWave)
                {
                    Attack = (float)1.5,
                    Enabled = true,
                    Threshold = 10,
                    Ratio = 4,
                    MakeUpGain = -3
                })
                    using (var writer = new LameMP3FileWriter(saveLocation.Text + ".compressed.mp3", inputWave.WaveFormat,
                                                              LAMEPreset.MEDIUM,
                                                              tag))
                    {
                        writer.MinProgressTime = 0;
                        writer.OnProgress     += (w, i, o, f) =>
                        {
                            if (f)
                            {
                                Close();
                            }
                            else
                            {
                                UpdateProgressBar(i, inputWave.Length);
                            }
                        };

                        var bytesPerMillisecond = inputWave.WaveFormat.AverageBytesPerSecond / 1000;

                        var startPos = (int)waveform.TimeStart.TotalMilliseconds * bytesPerMillisecond;

                        var endBytes = (int)waveform.TimeEnd.TotalMilliseconds * bytesPerMillisecond;
                        endBytes = endBytes - endBytes % inputWave.WaveFormat.BlockAlign;
                        var endPos = (int)inputWave.Length - endBytes;

                        inputWave.Position = startPos - startPos % inputWave.WaveFormat.BlockAlign;
                        var buffer = new byte[1024];
                        while (inputWave.Position < endPos)
                        {
                            var bytesRequired = (int)(endPos - inputWave.Position);
                            if (bytesRequired > 0)
                            {
                                var bytesToRead = Math.Min(bytesRequired, buffer.Length);
                                var bytesRead   = compressor.Read(buffer, 0, bytesToRead);
                                if (bytesRead > 0)
                                {
                                    writer.Write(buffer, 0, bytesRead);
                                }
                            }
                        }
                    }
            using (var inputWave = new WaveFileReader(Recorder.FilePath))
                using (var writer = new LameMP3FileWriter(saveLocation.Text, inputWave.WaveFormat, LAMEPreset.MEDIUM,
                                                          tag))
                {
                    inputWave.CopyTo(writer);
                }
        }
Пример #28
0
        private void splitMp3(string trackPath, int startPos, int endPos, MediaFoundationReader reader, ID3TagData tagData)
        {
            int progress = 0;

            using (var writer = new NAudio.Lame.LameMP3FileWriter(trackPath, reader.WaveFormat, NAudio.Lame.LAMEPreset.V3, tagData))
            {
                reader.Position = startPos;
                byte[] buffer = new byte[1024];
                while (reader.Position < endPos)
                {
                    int bytesRequired = (int)(endPos - reader.Position);
                    if (bytesRequired > 0)
                    {
                        int bytesToRead = Math.Min(bytesRequired, buffer.Length);
                        int bytesRead   = reader.Read(buffer, 0, bytesToRead);
                        if (bytesRead > 0)
                        {
                            writer.Write(buffer, 0, bytesRead);
                            progress += bytesRead;
                        }
                    }
                }
            }
        }