Save() public abstract method

Saves the changes made in the current instance to the file it represents.
public abstract Save ( ) : void
return void
Exemplo n.º 1
0
        /// <summary>
        /// Set the value of a tag in the Ogg Vorbis file (THIS FUNCTION WRITES TO DISK)
        /// </summary>
        /// <param name="TagID">
        /// A <see cref="OggTags"/> indicating which tag to change
        /// </param>
        /// <param name="Value">
        /// A <see cref="System.String"/> containing the value to write
        /// </param>
        /// <returns>
        /// A <see cref="OggTagWriteCommandReturn"/> indicating the result of the operation
        /// </returns>
        public OggTagWriteCommandReturn SetQuickTag(OggTags TagID, string Value)
        {
            switch (TagID)
            {
            case OggTags.Title: m_TagLibFile.Tag.Title = Value; break;

            case OggTags.Artist: m_TagLibFile.Tag.Performers = new string[] { Value }; break;

            case OggTags.Album: m_TagLibFile.Tag.Album = Value; break;

            case OggTags.Genre: m_TagLibFile.Tag.Genres = new string[] { Value }; break;

            case OggTags.TrackNumber: m_TagLibFile.Tag.Track = uint.Parse(Value); break;

            case OggTags.Filename: return(OggTagWriteCommandReturn.ReadOnlyTag);

            case OggTags.Bitrate: return(OggTagWriteCommandReturn.ReadOnlyTag);

            case OggTags.Length: return(OggTagWriteCommandReturn.ReadOnlyTag);

            default: return(OggTagWriteCommandReturn.UnknownTag);
            }
            try { m_TagLibFile.Save(); } catch (Exception ex) { return(OggTagWriteCommandReturn.Error); }
            return(OggTagWriteCommandReturn.Success);
        }
Exemplo n.º 2
0
 public void RemoveAllTags(string path)
 {
     TagLib.File file = null;
     try
     {
         file = TagLib.File.Create(path);
         file.RemoveTags(TagLib.TagTypes.AllTags);
         file.Save();
     }
     catch (CorruptFileException ex)
     {
         _logger.Warn(ex, $"Tag removal failed for {path}.  File is corrupt");
     }
     catch (Exception ex)
     {
         _logger.Warn()
         .Exception(ex)
         .Message($"Tag removal failed for {path}")
         .WriteSentryWarn("Tag removal failed")
         .Write();
     }
     finally
     {
         file?.Dispose();
     }
 }
Exemplo n.º 3
0
        public void applyArtwork(DirectoryInfo albumDirs)
        //Checks for artwork and applies to all ID3 data on all tracks for that album
        {
            try
            {
                FileInfo picFile = new FileInfo(albumDirs.FullName + "\\" + "folder.jpg");

                if (picFile.Exists)
                {
                    Picture[] artwork = new Picture[1];
                    artwork[0] = Picture.CreateFromPath(albumDirs.FullName + "\\" + "folder.jpg");

                    foreach (FileInfo tracks in albumDirs.GetFiles("*.mp3"))
                    {
                        TagLib.File file = TagLib.File.Create(albumDirs.FullName + "\\" + tracks);
                        file.Tag.Pictures = artwork;
                        file.Save();
                    }
                }
                else
                {
                    AppendTextBoxLine("Artwork not found at " + albumDirs.FullName + "\\" + "folder.jpg");
                }
            }
            catch (Exception e)
            {
                AppendTextBoxLine("Couldn't find artwork at " + albumDirs.FullName + "\\" + "folder.jpg Exception: " + e);
            }
        }
Exemplo n.º 4
0
 private void buttonSave_Click(object sender, EventArgs e)
 {
     TagLib.File file = Globals.getFile(); // Grab selected audio file
     if (file == null)
     {
         return;                               // If no file is selected, exit method
     }
     file.Tag.Title = textBoxTitle.Text;       // Save title to audio file
     string[] performer = new string[1];       //<--- Save artist to audio file
     performer[0]        = textBoxArtist.Text; // ----
     file.Tag.Performers = performer;          //  --->
     file.Tag.Album      = textBoxAlbum.Text;  // Save album to audio file
     try
     {
         if (textBoxYear.Text.Equals(""))
         {
             file.Tag.Year = 0;                              // If year textbox is empty, change to zero
         }
         else
         {
             file.Tag.Year = uint.Parse(textBoxYear.Text);  // If not empty, parse number from text and save as year to audio file
         }
     } catch (Exception ParseError) { file.Tag.Year = 0; }
     string[] genre = new string[1];      // <--- Save genre to audio file
     genre[0]        = textBoxGenre.Text; //  ----
     file.Tag.Genres = genre;             //  ---->
     file.Save();                         // Submit changes to audio file
     MessageBox.Show("Your changes have been saved!");
 }
Exemplo n.º 5
0
        public async void ApplyTag()
        {
            Windows.Storage.StorageFolder folder = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(FolderUrl);

            Windows.Storage.StorageFile file = await folder.GetFileAsync(FileName);

            Stream fileStream = await file.OpenStreamForWriteAsync();

            TagLib.File tagFile = TagLib.File.Create(new StreamFileAbstraction(FileName, fileStream, fileStream));
            tagFile.Tag.Title      = Title;
            tagFile.Tag.Performers = new string[] { Artist };
            tagFile.Tag.Album      = Album;
            if (tagFile.MimeType == "taglib/mp3")
            {
                IPicture pic = GeneratePicture();
                if (pic != null)
                {
                    tagFile.Tag.Pictures = new IPicture[] { pic };
                }
            }
            if (tagFile.MimeType == "taglib/flac")
            {
            }
            tagFile.Save();
            tagFile.Dispose();
            fileStream.Close();
        }
Exemplo n.º 6
0
        //#warning test wav to mp3 conversion
        //        /// <summary>
        //        /// Convert the wav file to an mp3 file
        //        /// </summary>
        //        /// <param name="filenameWAV">input file name of the wav file</param>
        //        /// <param name="filenameMP3">output file name of the mp3 file</param>
        //        /// <param name="deleteWAV">delete the wav file after conversion or not</param>
        //        /// see: https://github.com/filoe/cscore/blob/master/Samples/ConvertWavToMp3/Program.cs
        //        private void ConvertWAVToMP3(string filenameWAV, string filenameMP3, bool deleteWAV)
        //        {
        //            if (!System.IO.File.Exists(filenameWAV)) { return; }

        //            RecordState = RecordStates.CONVERTING_WAV_TO_MP3;
        //            IWaveSource source = CodecFactory.Instance.GetCodec(filenameWAV);
        //            MediaFoundationEncoder encoder = MediaFoundationEncoder.CreateMP3Encoder(source.WaveFormat, filenameMP3);

        //            byte[] buffer = new byte[source.WaveFormat.BytesPerSecond];
        //            int read;
        //            while ((read = source.Read(buffer, 0, buffer.Length)) > 0)
        //            {
        //                encoder.Write(buffer, 0, read);
        //            }

        //            try
        //            {
        //                encoder.Dispose();
        //                source.Dispose();
        //            }
        //            catch (Exception) { }

        //            if (deleteWAV) { System.IO.File.Delete(filenameWAV); }
        //        }

        #endregion

        //***********************************************************************************************************************************************************************************************************

        #region Add tags to sound file

        /// <summary>
        /// Add additional infos to the .wav and/or .mp3 file
        /// </summary>
        private void AddTrackTags(string fileName, GenericPlayer.PlayerTrack trackInfo)
        {
            Image _albumImage = null;

            if (trackInfo.Album.Images != null && trackInfo.Album.Images.Count > 0)
            {
                _albumImage = new Bitmap(trackInfo.Album.Images.First());
            }

            if (System.IO.File.Exists(fileName))
            {
                RecordState = RecordStates.ADDING_TAGS;

#warning Tagging WAV file with title with special characters (ä, ö, ü) shows some hyroglyphical characters in file (seems to be a display problem of windows explorer (using no unicode))
                TagLib.File wavFile = TagLib.File.Create(fileName);
                wavFile.Tag.Title        = trackInfo.TrackName;
                wavFile.Tag.AlbumArtists = trackInfo.Artists.Select(a => a.ArtistName).ToArray();
                wavFile.Tag.Album        = trackInfo.Album.AlbumName;
                try
                {
                    if (_albumImage != null)
                    {
                        wavFile.Tag.Pictures = new TagLib.IPicture[] { new TagLib.Picture(new TagLib.ByteVector((byte[])new System.Drawing.ImageConverter().ConvertTo(_albumImage, typeof(byte[])))) };
                    }
                }
                catch (Exception) { /* AlbumArt couldn't be set */ }

                wavFile.Save();
            }
        }
Exemplo n.º 7
0
        private void ProcessAudio(string fileIn)
        {
            TagLib.File f       = TagLib.File.Create(fileIn);
            string      artists = viAudio.Title;
            string      title   = viAudio.Title;

            if (viAudio.Title.Contains("-"))
            {
                artists = viAudio.Title.Substring(0, viAudio.Title.IndexOf("-")).Trim();
                title   = viAudio.Title.Substring(viAudio.Title.IndexOf("-") + 1).Trim();
            }

            f.Tag.Album      = viAudio.Title;
            f.Tag.Title      = title;
            f.Tag.Performers = new string[] { artists };

            WebClient wc = new WebClient();

            using (MemoryStream ms = new MemoryStream(wc.DownloadData(viAudio.ThumbnailUrl)))
            {
                byte[]         myBytes    = ms.ToArray();
                ByteVector     byteVector = new ByteVector(myBytes, myBytes.Length);
                TagLib.Picture picture    = new Picture(byteVector);

                f.Tag.Pictures = new TagLib.IPicture[]
                {
                    picture
                };
            }

            f.Save();
        }
Exemplo n.º 8
0
        public static bool SaveTrack(TrackViewModel tv)
        {
            try
            {
                using (File f = File.Create(tv.Path))
                {
                    f.Tag.Title      = tv.Title;
                    f.Tag.Album      = tv.Album;
                    f.Tag.Performers = new[] { tv.Artist };
                    f.Tag.Genres     = new[] { tv.Genre };
                    f.Tag.Year       = tv.Year;
                    f.Tag.Composers  = new[] { tv.Composer };
                    f.Save();
                }
            }

            catch (Exception e)
            {
                if (!pendingTagWrites.ContainsKey(tv.Path))
                {
                    pendingTagWrites.Add(tv.Path, tv);
                }
                else
                {                       //remove previous one, and add the latest one
                    pendingTagWrites.Remove(tv.Path);
                    pendingTagWrites.Add(tv.Path, tv);
                }
                return(false);
            }
            return(true);
        }
Exemplo n.º 9
0
        public void WriteTag()
        {
            File file = File.Create(OriginalPath);

            if (file == null)
            {
                return;
            }

            // artist Song editor
            file.Tag.Performers = new[] { Artist };

            // album Song editor
            file.Tag.Album     = Album;
            file.Tag.Genres    = new[] { Genre };
            file.Tag.Composers = Composers;

            // song
            file.Tag.Title = Title;
            file.Tag.Track = Convert.ToUInt32(TrackNumber);

            uint year = 0;

            if (UInt32.TryParse(Year, out year))
            {
                file.Tag.Year = year;
            }

            // save
            file.Save();
        }
Exemplo n.º 10
0
        private void lbl_writeData_Click(object sender, EventArgs e)
        {
            TagLib.File metaFile = TagLib.File.Create(txt_folder.Text + "/" + txt_selectedSong.Text);

            // Write Title ID3 to File
            if (chkbx_writeSong.Checked == true)
            {
                metaFile.Tag.Title = txt_songName.Text;
            }


            // Write Artist ID3 to File
            if (chkbx_writeArtist.Checked == true)
            {
                metaFile.Tag.Performers = new string[1] {
                    txt_artistName.Text
                };
            }

            //Write Year ID3 to File
            if (chkbx_writeYear.Checked == true)
            {
                metaFile.Tag.Year = Convert.ToUInt32(txt_yearMade.Text);
            }

            //Write Album ID3 to File
            if (chkbx_albumName.Checked == true)
            {
                metaFile.Tag.Album = txt_albumName.Text;
            }

            metaFile.Save();
        }
Exemplo n.º 11
0
        public static bool WriteLyrics(string strFile, string strLyrics)
        {
            if (!IsAudio(strFile))
            {
                return(false);
            }

            try
            {
                // Set the flag to use the standard System Encoding set by the user
                // Otherwise Latin1 is used as default, which causes characters in various languages being displayed wrong
                TagLib.ByteVector.UseBrokenLatin1Behavior = true;
                TagLib.File tag = TagLib.File.Create(strFile);
                tag.Tag.Lyrics = strLyrics;
                tag.Save();
                return(true);
            }
            catch (UnsupportedFormatException)
            {
                Log.Warn("Tagreader: Unsupported File Format {0}", strFile);
            }
            catch (Exception ex)
            {
                Log.Warn("TagReader: Exception writing file {0}. {1}", strFile, ex.Message);
            }
            return(false);
        }
Exemplo n.º 12
0
        public void WriteTagsToFile()
        {
            try
            {
                FileInfo fileInfo = new FileInfo(Location);
                fileInfo.IsReadOnly = false;
                fileInfo.Refresh();

                using (TagLib.File f = TagLib.File.Create(Location))
                {
                    f.Tag.Track        = Tags.Track;
                    f.Tag.TrackCount   = Tags.TrackCount;
                    f.Tag.Title        = Tags.Title;
                    f.Tag.AlbumArtists = Tags.AlbumArtists;
                    f.Tag.Performers   = Tags.Performers;
                    f.Tag.Disc         = Tags.Disc;
                    f.Tag.DiscCount    = Tags.DiscCount;
                    f.Tag.Album        = Tags.Album;
                    f.Tag.Genres       = Tags.Genres;
                    f.Tag.Year         = Tags.Year;
                    f.Tag.Pictures     = Tags.Pictures;
                    f.Save();
                }
            }
            catch (Exception ex)
            {
                DebugHelper.WriteException(ex, "Error writing tags to file");
            }
        }
Exemplo n.º 13
0
        public void TestPrivateFrame()
        {
            MockFileSystem fileSystem = new MockFileSystem();

            fileSystem.AddFile(@"C:\test.mp3", new MockFileData(System.IO.File.ReadAllBytes(@"TestData\test.mp3")));

            File.IFileAbstraction mp3File = fileSystem.File.CreateFileAbstraction(@"C:\test.mp3");
            File file = File.Create(mp3File);

            Tag id3V2Tag = (Tag)file.GetTag(TagTypes.Id3v2, true);

            // Get the private frame, create if necessary.
            PrivateFrame frame = PrivateFrame.Get(id3V2Tag, "SW/Uid", true);

            string uid = Guid.NewGuid().ToString("N");

            frame.PrivateData = Encoding.Unicode.GetBytes(uid);

            file.Save();


            File actualFile = File.Create(mp3File);

            id3V2Tag = (Tag)actualFile.GetTag(TagTypes.Id3v2, true);
            // Get the private frame, create if necessary.
            PrivateFrame actualFrame = PrivateFrame.Get(id3V2Tag, "SW/Uid", true);

            // Set the frame data to your value.  I am 90% sure that these are encoded with UTF-16.
            string actualUid = Encoding.Unicode.GetString(actualFrame.PrivateData.Data);

            actualUid.Should().Be(uid);
        }
Exemplo n.º 14
0
        public void TagTheMP3(string Filename, string _TrackName, string _Artist, string _Album, Bitmap _Artwork)
        {
            Busy = true;
            //Initialize Info
            if (_Album == _TrackName)
            {
                _Album = "Single";
            }
            Bitmap TagArtwork = new Bitmap(_Artwork);

            TagLib.File TagFile = TagLib.File.Create(Filename);
            TagFile.Tag.Title   = _TrackName;
            TagFile.Tag.Album   = _Album;
            TagFile.Tag.Artists = new string[] { _Artist };
            TagFile.Tag.Comment = "Ripped From Spotify By TheBitBrine's Spotify Recorder";

            //Artwork Stuff
            TagLib.Picture TempArtwork = new TagLib.Picture();
            TempArtwork.Type        = TagLib.PictureType.FrontCover;
            TempArtwork.Description = "Cover";
            TempArtwork.MimeType    = System.Net.Mime.MediaTypeNames.Image.Jpeg;
            MemoryStream ms = new MemoryStream();

            TagArtwork.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            ms.Position          = 0;
            TempArtwork.Data     = TagLib.ByteVector.FromStream(ms);
            TagFile.Tag.Pictures = new TagLib.IPicture[] { TempArtwork };

            //Finally Write To File & Close Memory Stream
            TagFile.Save();
            ms.Close();
            Busy = false;
        }
Exemplo n.º 15
0
 private void TagEditor(TagLib.File fSong, String strAlbum, String[] strPerformers, String[] strArtistAndTitle, bool blnImgFound, IPicture ipImg)
 {
     try
     {
         fSong.Tag.Album      = strAlbum;
         fSong.Tag.Performers = strPerformers;
         if (strArtistAndTitle.Length == 2)
         {
             fSong.Tag.Title = strArtistAndTitle[1];
         }
         else
         {
             fSong.Tag.Title = strArtistAndTitle[0];
         }
         if (blnImgFound)
         {
             fSong.Tag.Pictures = new IPicture[] { ipImg };
         }
         fSong.Save();
     }
     catch (Exception ex)
     {
         lbError.Items.Add(ex.ToString());
     }
 }
Exemplo n.º 16
0
        /// <summary>
        /// Tag an audio file (currently, only MP3 ID3 tags are supported).
        /// </summary>
        public static void tagAudio(string inFile, string artist, string albumTitle,
                                    string songTitle, string genre, string lyrics, int track, int totalTracks)
        {
            try
            {
                TagLib.File f = TagLib.File.Create(inFile);

                f.Tag.Performers = new string[] { artist };
                f.Tag.Album      = albumTitle;
                f.Tag.Title      = songTitle;
                f.Tag.Genres     = new string[] { genre };
                f.Tag.Track      = (uint)track;
                f.Tag.TrackCount = (uint)totalTracks;

                if (lyrics.Trim() != "")
                {
                    f.Tag.Lyrics = lyrics;
                }

                f.Save();
            }
            catch
            {
                // Ignore and move on
            }
        }
Exemplo n.º 17
0
        private int RecursiveTraversal(string path, int fileIndex)
        {
            //System.Threading.Thread.Sleep(5000);
            int step = 0;

            var childDirs = SortedSubDirectories(path);

            if (childDirs.Length == 0)
            {
                var files = Directory.GetFiles(path);

                if (files.Length > 1)
                {
                    return(-999);
                }

                int index    = 0;
                int maxIndex = 0;
                foreach (var file in files)
                {
                    maxIndex = fileIndex + index++;
                    var destination = Directory.GetParent(path).FullName + "\\" + RoundIndexToTwoPlaces(maxIndex) + Path.GetExtension(file);
                    if (!System.IO.File.Exists(destination))
                    {
                        System.IO.File.Move(file, destination);

                        if (ItWasNotAlreadySortedBefore(file))
                        {
                            TagLib.File tFile = TagLib.File.Create(destination);
                            tFile.Tag.Title = "";
                            tFile.Save();
                        }
                    }
                }
                if (Directory.GetFiles(path).Length == 0)
                {
                    Directory.Delete(path);
                }

                return(++maxIndex);
            }
            else
            {
                foreach (var dir in childDirs)
                {
                    var maxIndex = RecursiveTraversal(dir, step);
                    if (maxIndex == -999)
                    {
                        break;
                    }

                    step = maxIndex;
                }
            }

            return(step);
        }
Exemplo n.º 18
0
        static void FinishEncode()
        {
            audioStreamComplete = true;
            Session.Pause();
            Session.UnloadPlayer();
            lame.LameSetInSampleRate(staticfmt.sample_rate);
            lame.LameSetNumChannels(staticfmt.channels);
            lame.LameSetBRate(_confo.lameBitrate);
            Log.Debug("Encoding at " + _confo.lameBitrate + "kbps");
            lame.LameInitParams();
            outStream = outFile.OpenWrite();

            short[] left = new short[buf.Length / 4],
            right = new short[buf.Length / 4];
            byte[] fourbytes = new byte[4];
            for (int i = 0; i < buf.Length; i += 4)
            {
                buf.Read(fourbytes, 0, 4);
                left[i / 4] = BitConverter.ToInt16(new byte[2] {
                    fourbytes[0], fourbytes[1]
                }, 0);
                right[i / 4] = BitConverter.ToInt16(new byte[2] {
                    fourbytes[2], fourbytes[3]
                }, 0);
            }

            int outSize = lame.LameEncodeBuffer(left, right, left.Length, mp3Out);

            outStream.Write(mp3Out, 0, outSize);
            outSize = lame.LameEncodeFlush(mp3Out);
            outStream.Write(mp3Out, 0, outSize);
            outStream.Flush();
            outStream.Close();
            Log.Debug("File written to disk! Trying to write tags...");
            TagLib.File tf = TagLib.File.Create(outFile.FullName);
            tf.Tag.Album        = _album;
            tf.Tag.AlbumArtists = null;
            tf.Tag.AlbumArtists = new string[1] {
                _artist
            };
            tf.Tag.Title      = _song;
            tf.Tag.Performers = null;
            tf.Tag.Performers = new string[1] {
                _artist
            };
            tf.Tag.Artists = null;
            tf.Tag.Artists = new string[1] {
                _artist
            };
            tf.Save();
            Log.Debug("Tags written! Finished!");
            if (frm != null)
            {
                frm.BeginInvoke((Delegate) new MethodInvoker(() => frm.SetStatus("Download finished")));
            }
            new SftpUploader(_confo).go(outFile.FullName);
        }
Exemplo n.º 19
0
 static void ChangeDescription(string path, string name, string artist, string album)
 {
     TagLib.File f = TagLib.File.Create(path);
     Console.WriteLine(f.Writeable);
     f.Tag.Album      = album;
     f.Tag.Title      = name;
     f.Tag.Performers = new string[] { artist };
     f.Save();
 }
Exemplo n.º 20
0
 public void writeCommentinFile(List <string> listFile)
 {
     for (int i = 0; i < listFile.Count(); i++)
     {
         TagLib.File File = TagLib.File.Create(listFile[i]);
         File.Tag.Comment = i.ToString();  //access comment section in file
         File.Save();
     }
 }
Exemplo n.º 21
0
        private string CheckMP3Tag(string fileName, string author, string album, int track)
        {
            /* // sanitise album string - pesky george's marvellous medcine!!
             * album = album.Replace("'", "''");
             * // check the value of id3tag for the author/album
             * DataTable dt = new DataTable();
             * using (ODBCClass o = new ODBCClass(DSN))
             * {
             *   OdbcCommand oCommand = o.GetCommand("SELECT id3tags FROM storytapes"
             + " WHERE title = '" + album + "'"
             + " AND authorid=(SELECT id FROM `authors` WHERE author='" + author + "')");
             +   OdbcDataReader oReader = oCommand.ExecuteReader();
             +   dt.Load(oReader);
             + }
             +
             + if (dt.Rows.Count > 0)
             + {
             +   foreach (DataRow row in dt.Rows)
             +   {
             +       if (row["id3tags"].ToString() != "N") // tagged - so exit // changed to if not untagged - value can be Y (tagged) N (not tagged) or X (not complete)
             +       {
             +           return row["id3tags"].ToString(); // Y or X - don't bother
             +       }
             +   }
             + } */

            if (cbTags.Checked)
            {
                TagLib.File tagFile = TagLib.File.Create(fileName);
                if (tagFile.Tag.Album != null)
                {
                    Log(fileName + " already has tags." + " Author: " + author + " Album: " + album + " Track: " + track.ToString());
                    // update id3tag field
                    //SetTagsUpdated(author, album);
                }
                else
                {
                    Log(fileName + " TAGS REQUIRED" + " Author: " + author + " Album: " + album + " Track: " + track.ToString());

                    List <string> sl = new List <string>();
                    sl.Add(author);

                    tagFile.Tag.AlbumArtists = sl.ToArray();
                    tagFile.Tag.Artists      = sl.ToArray();
                    tagFile.Tag.Track        = (uint)track;
                    tagFile.Tag.Album        = album;

                    tagFile.Save();
                }
                return("N");
            }
            else
            {
                return("Y"); // update tags is not checked, so return 'already tagged'
            }
        }
Exemplo n.º 22
0
 public static string WriteInfos(int a)
 {
     try
     {
         TagLib.File f = TagLib.File.Create(mp3.pfad[a]);
         f.Tag.Title           = title[a];
         f.Tag.Performers[0]   = artist[a];
         f.Tag.Album           = album[a];
         f.Tag.AlbumArtists[0] = albumartist[a];
         if (track[a] == -1)
         {
         }
         else
         {
             f.Tag.Track = Convert.ToUInt16(track[a]);
         }
         if (year[a] == -1)
         {
         }
         else
         {
             f.Tag.Year = Convert.ToUInt16(year[a]);
         }
         f.Tag.Genres[0] = genre[a];
         f.Tag.Comment   = comment[a];
         if (Settings.Default.CommentChangeEnabled)
         {
             f.Tag.Comment = Settings.Default.Comment;
         }
         //albumcover
         TagLib.IPicture[] pictures            = new IPicture[albumcover[a].Count()];
         TagLib.Id3v2.AttachedPictureFrame pic = new TagLib.Id3v2.AttachedPictureFrame();
         for (int i = 1; i < albumcover[a].Count(); i++)
         {
             mp3.albumcoverpfad[a][i] = Path.GetTempPath() + i + System.DateTime.Now.GetHashCode() + ".jpg";
             mp3.albumcover[a][i].Save(mp3.albumcoverpfad[a][i]);
             pic.TextEncoding = TagLib.StringType.Latin1;
             pic.MimeType     = System.Net.Mime.MediaTypeNames.Image.Jpeg;
             pic.Type         = TagLib.PictureType.FrontCover;
             pic.Data         = TagLib.ByteVector.FromPath(mp3.albumcoverpfad[a][i]);
             pictures[i]      = pic;
         }
         f.Tag.Pictures = pictures;
         f.Save();
         if (mp3.dateiname[a] != mp3.newdateiname[a] && mp3.newdateiname != null)
         {
             Dateien.RenameFile(mp3.newdateiname[a], a);
         }
         f = null;
         return("OK");
     }
     catch
     {
         return("WriteInfos(): Datei schreibgeschützt");
     }
 }
Exemplo n.º 23
0
        bool SaveFile(File file)
        {
            try {
                file.Save();
            } catch (Exception) {
                return(false);
            }

            return(true);
        }
Exemplo n.º 24
0
        private void MediaMetadataHandlerWriter(string metadata)
        {
            TagLib.File file = TagLib.File.Create(FilePath);

            file.Tag.Copyright = metadata;

            file.Save();

            //return file;
        }
Exemplo n.º 25
0
        public void SaveTagToFile(MusicFileTag tag)
        {
            if (String.IsNullOrEmpty(tag.FilePath))
            {
                return;
            }

            File tagInfo = MusicFileTag.ConvertMusicFileTagToTag(tag);

            tagInfo.Save();
        }
Exemplo n.º 26
0
        private void buttonUpdate_Click(object sender, EventArgs e)
        {
            if (!validLocation())
            {
                return;
            }
            if (dataTable.Rows.Count <= 1)
            {
                updateTable();
            }
            this.Enabled = false;
            string[] filePaths = Directory.GetFiles(textBoxPath.Text, "*.mp3", SearchOption.TopDirectoryOnly);
            foreach (string path in filePaths)
            {
                TagLib.File file     = TagLib.File.Create(@path);
                string      fileName = @path.Substring(@path.LastIndexOf(@"\") + 1);
                string      jpgPath  = null;
                try  {
                    jpgPath           = path.Substring(0, @path.LastIndexOf(".")) + ".jpg";
                    file.Tag.Pictures = new TagLib.IPicture[]
                    {
                        new TagLib.Picture(new TagLib.ByteVector((byte[])new System.Drawing.ImageConverter().ConvertTo(System.Drawing.Image.FromFile(jpgPath), typeof(byte[]))))
                    };
                } catch (Exception error) { }
                if (@fileName.Contains("-"))
                {
                    try
                    {
                        string[] artistTitle = fileName.Split('-');
                        string[] artists     = new string[1];
                        artists[0]          = new CultureInfo("en-US").TextInfo.ToTitleCase(artistTitle[0]);
                        file.Tag.Performers = artists;
                        string title = artistTitle[1].Substring(0, artistTitle[1].LastIndexOf(".")).Trim();
                        file.Tag.Title = new CultureInfo("en-US").TextInfo.ToTitleCase(title);
                    }
                    catch (Exception er) { }
                }
                file.Save();

                if (checkBox.Checked)
                {
                    string targetPath = @path.Substring(0, @path.LastIndexOf("."));
                    if (!System.IO.Directory.Exists(targetPath))
                    {
                        System.IO.Directory.CreateDirectory(targetPath);
                    }
                    string destFile = System.IO.Path.Combine(targetPath, fileName);
                    System.IO.File.Copy(path, destFile, true);
                }
                // System.IO.File.Delete(path);
            }
            this.Enabled = true;
            MessageBox.Show("All done!");
        }
Exemplo n.º 27
0
        public static void writePictureData(ByteVector data, string path)
        {
            TagLib.File file = TagLib.File.Create(path);
            Picture     pic  = new Picture();

            pic.Data          = data;
            file.Tag.Pictures = new IPicture[1] {
                pic
            };
            file.Save();
        }
Exemplo n.º 28
0
 /// <summary>
 /// Add Album Information
 /// </summary>
 /// <param name="path"></param>
 /// <param name="Album"></param>
 public static void AddAlbum(string path, string Album)
 {
     try
     {
         TagLib.File f = TagLib.File.Create(path);
         f.Tag.Album = Album;
         f.Save();
     }
     catch (Exception)
     {
     }
 }
Exemplo n.º 29
0
 /// <summary>
 /// Add Year Information
 /// </summary>
 /// <param name="path"></param>
 /// <param name="date"></param>
 public static void AddYear(string path, DateTime date)
 {
     try
     {
         TagLib.File f = TagLib.File.Create(path);
         f.Tag.Year = (uint)date.Year;
         f.Save();
     }
     catch (Exception)
     {
     }
 }
Exemplo n.º 30
0
 /// <summary>
 /// Add Genre Information
 /// </summary>
 /// <param name="path"></param>
 /// <param name="genres"></param>
 public static void AddGenre(string path, string[] genres)
 {
     try
     {
         TagLib.File f = TagLib.File.Create(path);
         f.Tag.Genres = genres;
         f.Save();
     }
     catch (Exception)
     {
     }
 }
		private void SaveSong(File song, Mp3FileInfoModel fileInfo)
		{
			_logController.SaveSong(fileInfo);

			song.Save();
		}
Exemplo n.º 32
0
        /// <summary>
        ///     Изменяет слова в тегах к верхнему регистру
        /// </summary>
        /// <param name="mp3File">Изменяемый файл</param>
        public static void TagsToUpper(File mp3File)
        {
            var file = mp3File.Tag;

            if (file.FirstPerformer != null)
            {
                var wordsInTag = file.FirstPerformer.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                file.Performers[0] = StringToUp(wordsInTag);
            }

            if (file.Title != null)
            {
                var wordsInTag = file.Title.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                file.Title = StringToUp(wordsInTag);
            }

            if (file.Album != null)
            {
                var wordsInTag = file.Album.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                file.Album = StringToUp(wordsInTag);
            }

            if (file.Genres.Count() != 0)
            {
                var wordsInTag = file.Genres[0].Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                file.Genres[0] = StringToUp(wordsInTag);
            }

            mp3File.Save();
        }
        /// <summary>
        /// Saves the new/changed values to the file
        /// </summary>
        /// <param name="id3">New values to be saved</param>
        /// <param name="oldId3">Old values (needed for log file)</param>
        /// <returns>Success or not</returns>
        public static bool Save(File id3, File oldId3)
        {
            try
            {
                Logger.Info("---------------");
                Logger.Info($"Changing values for \"{id3.Name}\"");
                var newTags = id3.TagTypes != TagTypes.Id3v2 ? id3.Tag : id3.GetTag(TagTypes.Id3v2);
                var oldTags = oldId3.TagTypes != TagTypes.Id3v2 ? oldId3.Tag : oldId3.GetTag(TagTypes.Id3v2);
                foreach (var property in Properties)
                {
                    if (property.Equals("Performers") || property.Equals("Genres"))
                        LogDifferences(newTags.GetPropertyValue($"Joined{property}"),
                            oldTags.GetPropertyValue($"Joined{property}"), property, newTags.GetPropertyValue(property),
                            oldTags.GetPropertyValue(property));
                    else
                        LogDifferences(newTags.GetPropertyValue(property),
                            oldTags.GetPropertyValue(property), property);
                }
                if (id3.TagTypes == TagTypes.Id3v2)
                    LogDifferences(newTags.GetPopularimeterFrame().Rating.ToStars(), oldTags.GetPopularimeterFrame().Rating.ToStars(), "Rating");

                id3.Save();
                Logger.Info("---------------");
                return true;
            }
            catch (CorruptFileException ex)
            {
                Logger.Error($"An exception occured while changing values for \"{id3.Name}\"", ex);
                return false;
            }
        }