Dispose() public method

public Dispose ( ) : void
return void
Exemplo n.º 1
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.º 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
 private static void renameToArtistTitle(FileInfo[] files)
 {
     foreach (FileInfo file in files)
     {
         string      filePath  = file.FullName;
         TagLib.File musicFile = TagLib.File.Create(filePath);
         string      artist    = String.Join("/", musicFile.Tag.Performers);
         if (artist == null)
         {
             artist = "<unknown>";
         }
         artist = MakeValidFileName(artist);
         string title = musicFile.Tag.Title;
         musicFile.Dispose();
         if (title != null)
         {
             title = MakeValidFileName(title);
             try
             {
                 System.IO.File.Move(filePath, "C:/Users/steng/Desktop/New folder/" + artist + "-" + title + ".mp3");
             }
             catch (IOException e)
             {
                 if (e.Message == "Cannot create a file when that file already exists.\r\n")
                 {
                     System.IO.File.Move(filePath, "C:/Users/steng/Desktop/New folder/" + artist + "-" + title + "_.mp3");
                 }
             }
         }
     }
 }
Exemplo n.º 4
0
        // used for getting art from a tag.
        // We don't set the FilePath here, because that is only used for actual art files on disk
        private Art CreateArt(TagLib.File file)
        {
            Art art = new Art();

            if (file.Tag.Pictures.Length > 0)
            {
                byte[] data = file.Tag.Pictures[0].Data.Data;
                art.Md5Hash      = data.MD5();
                art.FileSize     = data.Length;
                art.LastModified = System.IO.File.GetLastWriteTime(file.Name).ToUnixTime();

                art.ArtId = Injection.Kernel.Get <IArtRepository>().ArtIdForMd5(art.Md5Hash);
                if (art.ArtId == null)
                {
                    // This art isn't in the database yet, so add it
                    art.ArtId = Injection.Kernel.Get <IItemRepository>().GenerateItemId(ItemType.Art);
                    Injection.Kernel.Get <IArtRepository>().InsertArt(art);
                }
            }

            // Close file handle
            file.Dispose();

            return(art);
        }
Exemplo n.º 5
0
 public void Dispose()
 {
     m_TagLibFile.Dispose();
     m_TagLibFile = null;
     m_CSVorbisFile.Dispose();
     m_CSVorbisFile = null;
 }
Exemplo n.º 6
0
 private async Task<SongFile> ReadTagFromFile(StorageFile file)
 {
     Stream fileStream = await file.OpenStreamForReadAsync();
     TagLib.File tagFile = TagLib.File.Create(new StreamFileAbstraction(file.Name, fileStream, fileStream));
     Tag tag = null;
     if (tagFile.MimeType == "taglib/mp3")
     {
         tag = tagFile.GetTag(TagTypes.Id3v2);
     }
     if (tagFile.MimeType == "taglib/flac")
     {
         tag = tagFile.GetTag(TagTypes.FlacMetadata);
     }
     string performers = "";
     foreach (string performer in tag.Performers)
     {
         performers += performer;
     }
     tagFile.Dispose();
     fileStream.Close();
     return new SongFile
     {
         FileName = file.Name,
         Title = tag.Title,
         Album = tag.Album,
         Tag = tag,
         Artist = performers,
         Path = file.Path
     };
 }
Exemplo n.º 7
0
 public RenamerTag(string FileName)
 {
     _FileName = FileName;
     TagLib.File temp = TagLib.File.Create(FileName);
     SetTag(temp);
     temp.Dispose();
 }
        public static BitmapSource GetPicture(string path)
        {
            TL.File      media = TL.File.Create(path);
            BitmapSource bs    = getPic(media.Tag);

            media.Dispose();
            return(bs);
        }
Exemplo n.º 9
0
        public void Cleanup()
        {
            _vp?.Dispose();
            _vp = null;

            _det?.Dispose();
            _det = null;

            _context = null;
        }
Exemplo n.º 10
0
        /// <summary>
        /// Confirms the file tags can actually be read, proving the file is valid.
        /// TODO: Possibly find a better way to validate more file types quicker
        /// TODO: perhaps by reading the resolved url ending rather than assuming mp3 immediately
        /// </summary>
        /// <returns>True if the file was downloaded correctly and can be modified</returns>
        public override async Task <bool> Validate()
        {
            var   valid = false;
            var   retry = false;
            SFile file  = null;

            try
            {
                // Test if the file is a valid mp3
                file = SFile.Create(MainResource.AbsolutePath);
            }
            catch (CorruptFileException) // File isn't mp3
            {
                try
                {
                    // Check if the file is wma
                    var old = MainResource.AbsolutePath;
                    MainResource.AbsolutePath = MainResource.AbsolutePath.Substring(0,
                                                                                    MainResource.AbsolutePath.Length - 3) + "wma";
                    File.Move(old, MainResource.AbsolutePath);
                    file = SFile.Create(MainResource.AbsolutePath);
                }
                catch (CorruptFileException e) // File isn't any supported type
                {
                    File.Delete(MainResource.AbsolutePath);

                    // If manual has already been attempted, this isn't possible
                    retry = !_forceManual;

                    if (!retry)
                    {
                        View.Report("Error!", true);
                        CrashHandler.Throw("Unable to download a valid song format for editing!", e);
                    }
                }
            }
            finally
            {
                if (file != null)
                {
                    valid = true;
                    file.Dispose();
                }
            }

            // Retry the download if necessary
            if (retry)
            {
                valid = await RetryDownload();
            }

            return(valid);
        }
Exemplo n.º 11
0
        private void btnSet_Click(object sender, EventArgs e)
        {
            //Doesn't work so don't use it ... yet :3
            OpenFileDialog getFile = new OpenFileDialog();

            if (getFile.ShowDialog() == DialogResult.OK)
            {
                TagLib.File myVideo = TagLib.File.Create(getFile.FileName);
                myVideo.Tag.Title = "Test";
                myVideo.Tag.Year  = 2014;
                myVideo.Save();
                myVideo.Dispose();
            }
        }
Exemplo n.º 12
0
        public bool ReadID3Info()
        {
            if (loaded)
            {
                return(true);
            }
            if (tool.IsAudioFile(path))
            {
                title = Path.GetFileNameWithoutExtension(path);
                try
                {
                    file = TagLib.File.Create(path);
                    file.GetTag(TagTypes.AllTags);
                    album    = file.Tag.Album;
                    artist   = file.Tag.FirstAlbumArtist;
                    track    = file.Tag.Track;
                    lyrics   = file.Tag.Lyrics;
                    pictures = file.Tag.Pictures;
                    year     = file.Tag.Year.ToString();
                    length   = file.Length.ToString();
                    if (!string.IsNullOrEmpty(file.Tag.FirstGenre))
                    {
                        genres = file.Tag.FirstGenre; //genre loading appers tp be broken
                    }
                    if (!string.IsNullOrEmpty(file.Tag.Title))
                    {
                        title = file.Tag.Title;
                    }

                    return(loaded = true);
                }
                catch (Exception e)
                {
                    TagLoadingLog.Add(string.Concat("--> Failed to Get All Tags: \n", e.Message, "\n", path));
                    invalid = true;
                    return(loaded = false);
                }
                finally
                {
                    if (file != null)
                    {
                        file.Dispose();
                    }
                }
            }
            invalid = true;
            return(false);
        }
Exemplo n.º 13
0
        private Video CreateVideo(string filePath, int?folderId, TagLib.File file)
        {
            int?itemId = Injection.Kernel.Get <IItemRepository>().GenerateItemId(ItemType.Video);

            if (itemId == null)
            {
                return(new Video());
            }

            Video video = new Video();

            video.ItemId = itemId;

            video.FolderId = folderId;
            video.FileType = video.FileType.FileTypeForTagLibMimeType(file.MimeType);

            if (video.FileType == FileType.Unknown)
            {
                logger.IfInfo("\"" + filePath + "\" Unknown file type: " + file.Properties.Description);
            }

            video.Width    = file.Properties.VideoWidth;
            video.Height   = file.Properties.VideoHeight;
            video.Duration = Convert.ToInt32(file.Properties.Duration.TotalSeconds);
            video.Bitrate  = file.Properties.AudioBitrate;

            // Get filesystem information about file
            FileInfo fsFile = new FileInfo(filePath);

            video.FileSize     = fsFile.Length;
            video.LastModified = fsFile.LastWriteTime.ToUnixTime();
            video.FileName     = fsFile.Name;

            // Generate an art id from the embedded art, if it exists
            int?artId = CreateArt(file).ArtId;

            // Close file handles
            fsFile = null;
            file.Dispose();

            // If there was no embedded art, use the folder's art
            artId = (object)artId == null?Injection.Kernel.Get <IArtRepository>().ArtIdForItemId(video.FolderId) : artId;

            // Create the art/item relationship
            Injection.Kernel.Get <IArtRepository>().UpdateArtItemRelationship(artId, video.ItemId, true);

            return(video);
        }
Exemplo n.º 14
0
        public MusicInfo(string path)
        {
            try
            {
                if (System.IO.File.Exists(path))
                {
                    TagLib.File file  = TagLib.File.Create(path);
                    Shell       shell = new Shell();
                    string      p     = path.ToString();
                    Folder      dir   = shell.NameSpace(System.IO.Path.GetDirectoryName(p));
                    FolderItem  item  = dir.ParseName(System.IO.Path.GetFileName(p));
                    Path  = path;
                    Title = dir.GetDetailsOf(item, 21);
                    if (String.IsNullOrEmpty(Title))
                    {
                        Title = GetTitleFromPath(path);
                    }
                    Album = dir.GetDetailsOf(item, 14);
                    if (String.IsNullOrEmpty(Album))
                    {
                        Album = "未知专辑";
                    }
                    Artist = dir.GetDetailsOf(item, 13);
                    if (String.IsNullOrEmpty(Artist))
                    {
                        Artist = "未知歌手";
                    }
                    //Tarck
                    Track = (int)file.Tag.Track;

                    //封面
                    if (file.Tag.Pictures.Count() != 0)
                    {
                        CoverImage = ByteToBitmapImage(file.Tag.Pictures[0].Data.Data);
                        if (CoverImage.CanFreeze)
                        {
                            CoverImage.Freeze();
                        }
                    }

                    SampleRate = file.Properties.AudioSampleRate;
                    Duration   = file.Properties.Duration;
                    Bitrate    = file.Properties.AudioBitrate;
                    file.Dispose();
                }
            }
            catch { }
        }
        public MusicEntity CreateEntity(string path)
        {
            TL.File     media = TL.File.Create(path);
            MusicEntity me    = new MusicEntity()
            {
                Album     = media.Tag.Album,
                Artist    = media.Tag.Performers,
                Extension = Path.GetExtension(path),
                Name      = Path.GetFileNameWithoutExtension(path),
                Year      = media.Tag.Year.ToString(),
                Path      = path,
            };

            media.Dispose();
            return(me);
        }
Exemplo n.º 16
0
        public Song(string _path, Font _font)
            : base("SongText", _font)
        {
            Path = _path;

            MetaData md = MetaData.Create(_path);

            SetNameFromMetaData(md);
            DisplayedString = Name;

            //formatting
            CharacterSize = 14;
            Color         = Color.Black;

            Program.Window.MouseButtonPressed += (o, e) => CollisionCheck(e);

            md.Dispose();
        }
Exemplo n.º 17
0
        /// <summary>
        /// This refreshes the file to get rid of unused bytes and saves all made changes.
        /// </summary>
        /// <param name="Item"></param>
        /// <param name="Source"></param>

        public static void Refresh(this TagLib.File Item, string Source)
        {
            Item.Save();
            Item.Dispose();

            TagLib.File tagFile = TagLib.File.Create(Source);
            TagLib.Tag  tempTag = new TagLib.Id3v2.Tag();
            tagFile.Tag.CopyTo(tempTag, true);
            tagFile.RemoveTags(TagLib.TagTypes.AllTags);
            tagFile.Save();
            tagFile.Dispose();


            TagLib.File tagFile2 = TagLib.File.Create(Source);
            tempTag.CopyTo(tagFile2.Tag, true);
            tagFile2.Save();
            tagFile2.Dispose();
        }
Exemplo n.º 18
0
    public byte[] RemoveAllTags(byte[] data)
    {
        Stream dataStream = new MemoryStream(data);

        TagLib.File tagData = TagLib.File.Create(new FileBytesAbstraction("tempFile.mp3", dataStream));
        //TagLib.Tag tempTags = new TagLib.Id3v2.Tag();
        //tagData.Tag.Lyrics = "test lyric";
        tagData.RemoveTags(TagLib.TagTypes.AllTags);
        //tagData.Tag.CopyTo(tempTags, true);
        tagData.Save();
        tagData.Dispose();
        //tagData = TagLib.File.Create(new FileBytesAbstraction(audioFile, dataStream));
        //tempTags.CopyTo(tagData.Tag, true);
        //tagData.Save();
        //tagData.Dispose();

        byte[] dStream = new byte[dataStream.Length];
        dataStream.Read(dStream, 0, dStream.Length);
        return(dStream);
    }
Exemplo n.º 19
0
 public AboutTags()
 {
     InitializeComponent();
     PathTextbox.Text = MainForm.FilePath;
     TagLib.File file = TagLib.File.Create(MainForm.FilePath);
     TitleTextbox.Text  = file.Tag.Title;
     AuthorTextbox.Text = "";
     foreach (string i in file.Tag.Performers)
     {
         AuthorTextbox.Text += $"{i} ";
     }
     AlbumTextbox.Text = file.Tag.Album;
     YearTextbox.Text  = file.Tag.Year.ToString();
     TrackTextbox.Text = file.Tag.Track.ToString();
     GenreTextbox.Text = "";
     foreach (string i in file.Tag.Genres)
     {
         GenreTextbox.Text += $"{i} ";
     }
     if (Path.GetExtension(MainForm.FilePath) == ".wav")
     {
         var wave = new WaveFileReader(MainForm.FilePath);
         LengthTextbox.Text = wave.TotalTime.ToString();
         FreqTextbox.Text   = $"{wave.WaveFormat.SampleRate.ToString()} Hz";
         wave.Close();
     }
     else if (Path.GetExtension(MainForm.FilePath) == ".mp3")
     {
         var mp3 = new Mp3FileReader(MainForm.FilePath);
         LengthTextbox.Text  = mp3.TotalTime.ToString();
         FreqTextbox.Text    = $"{mp3.WaveFormat.SampleRate.ToString()} Hz";
         BitrateTextbox.Text = Convert.ToString(mp3.Mp3WaveFormat.AverageBytesPerSecond * 8 / 1024) + "Kbps (aprox.)";
         mp3.Close();
     }
     LyricsRighText.Text = file.Tag.Lyrics;
     LyricsRighText.SelectAll();
     LyricsRighText.SelectionAlignment = HorizontalAlignment.Center;
     LyricsRighText.DeselectAll();
     file.Dispose();
 }
Exemplo n.º 20
0
 void LoadTags()
 {
     if (tracks.Count == 1 && !Program.mainWindow.supportedModuleTypes.Contains(Path.GetExtension(tracks[0].filename)))
     {
         using (TagLib.File tagFile = TagLib.File.Create(tracks[0].filename))
         {
             dgv.Rows[0].Cells[1].Value = tagFile.Tag.Title;
             if (tagFile.Tag.Performers.Length > 0)
             {
                 dgv.Rows[1].Cells[1].Value = tagFile.Tag.Performers[0];
             }
             else
             {
                 dgv.Rows[1].Cells[1].Value = "";
             }
             dgv.Rows[2].Cells[1].Value = tagFile.Tag.Album;
             dgv.Rows[3].Cells[1].Value = tagFile.Tag.Year;
             dgv.Rows[4].Cells[1].Value = tagFile.Tag.Comment;
             if (tagFile.Tag.Genres.Length > 0)
             {
                 dgv.Rows[5].Cells[1].Value = tagFile.Tag.Genres[0];
             }
             else
             {
                 dgv.Rows[5].Cells[1].Value = "";
             }
             tagFile.Dispose();
         }
     }
     else
     {
         dgv.Rows[0].Cells[1].Value                     =
             dgv.Rows[1].Cells[1].Value                 =
                 dgv.Rows[2].Cells[1].Value             =
                     dgv.Rows[3].Cells[1].Value         =
                         dgv.Rows[4].Cells[1].Value     =
                             dgv.Rows[5].Cells[1].Value = "&unchanged";
     }
 }
Exemplo n.º 21
0
        public MusicEntity CreateEntity(string path)
        {
            TL.File     media = TL.File.Create(path);
            MusicEntity me    = new MusicEntity()
            {
                Album     = media.Tag.Album,
                Artist    = media.Tag.Performers,
                Extension = Path.GetExtension(path),
                Name      = Path.GetFileNameWithoutExtension(path),
                Year      = media.Tag.Year.ToString(),
                Path      = path,
            };

            if (me.Artist == null || me.Artist.Length == 0)
            {
                me.Artist = new string[] { Converter.ConvertTo("CORE_FUNC", "CORE_PRESENTOR_UNKNOW_ARTIST") };
            }
            if (string.IsNullOrEmpty(me.Album))
            {
                me.Album = Converter.ConvertTo("CORE_FUNC", "CORE_PRESENTOR_UNKNOW_ALBUM");
            }
            media.Dispose();
            return(me);
        }
Exemplo n.º 22
0
 public void Dispose()
 {
     _songFile.Dispose();
 }
Exemplo n.º 23
0
        public void Read(string path)
        {
            Logger.Debug($"Starting tag read for {path}");

            IsValid = false;
            TagLib.File file = null;
            try
            {
                file = TagLib.File.Create(path);
                var tag = file.Tag;

                Title        = tag.Title ?? tag.TitleSort;
                Performers   = tag.Performers ?? tag.PerformersSort;
                AlbumArtists = tag.AlbumArtists ?? tag.AlbumArtistsSort;
                Track        = tag.Track;
                TrackCount   = tag.TrackCount;
                Album        = tag.Album ?? tag.AlbumSort;
                Disc         = tag.Disc;
                DiscCount    = tag.DiscCount;
                Year         = tag.Year;
                Publisher    = tag.Publisher;
                Duration     = file.Properties.Duration;
                Genres       = tag.Genres;
                ImageSize    = tag.Pictures.FirstOrDefault()?.Data.Count ?? 0;

                DateTime tempDate;

                // Do the ones that aren't handled by the generic taglib implementation
                if (file.TagTypesOnDisk.HasFlag(TagTypes.Id3v2))
                {
                    var id3tag = (TagLib.Id3v2.Tag)file.GetTag(TagTypes.Id3v2);
                    Media = id3tag.GetTextAsString("TMED");
                    Date  = ReadId3Date(id3tag, "TDRC");
                    OriginalReleaseDate = ReadId3Date(id3tag, "TDOR");
                }
                else if (file.TagTypesOnDisk.HasFlag(TagTypes.Xiph))
                {
                    // while publisher is handled by taglib, it seems to be mapped to 'ORGANIZATION' and not 'LABEL' like Picard is
                    // https://picard.musicbrainz.org/docs/mappings/
                    var flactag = (TagLib.Ogg.XiphComment)file.GetTag(TagLib.TagTypes.Xiph);
                    Media = flactag.GetField("MEDIA").ExclusiveOrDefault();
                    Date  = DateTime.TryParse(flactag.GetField("DATE").ExclusiveOrDefault(), out tempDate) ? tempDate : default(DateTime?);
                    OriginalReleaseDate = DateTime.TryParse(flactag.GetField("ORIGINALDATE").ExclusiveOrDefault(), out tempDate) ? tempDate : default(DateTime?);
                    Publisher           = flactag.GetField("LABEL").ExclusiveOrDefault();
                }
                else if (file.TagTypesOnDisk.HasFlag(TagTypes.Ape))
                {
                    var apetag = (TagLib.Ape.Tag)file.GetTag(TagTypes.Ape);
                    Media = apetag.GetItem("Media")?.ToString();
                    Date  = DateTime.TryParse(apetag.GetItem("Year")?.ToString(), out tempDate) ? tempDate : default(DateTime?);
                    OriginalReleaseDate = DateTime.TryParse(apetag.GetItem("Original Date")?.ToString(), out tempDate) ? tempDate : default(DateTime?);
                    Publisher           = apetag.GetItem("Label")?.ToString();
                }
                else if (file.TagTypesOnDisk.HasFlag(TagTypes.Asf))
                {
                    var asftag = (TagLib.Asf.Tag)file.GetTag(TagTypes.Asf);
                    Media = asftag.GetDescriptorString("WM/Media");
                    Date  = DateTime.TryParse(asftag.GetDescriptorString("WM/Year"), out tempDate) ? tempDate : default(DateTime?);
                    OriginalReleaseDate = DateTime.TryParse(asftag.GetDescriptorString("WM/OriginalReleaseTime"), out tempDate) ? tempDate : default(DateTime?);
                    Publisher           = asftag.GetDescriptorString("WM/Publisher");
                }
                else if (file.TagTypesOnDisk.HasFlag(TagTypes.Apple))
                {
                    var appletag = (TagLib.Mpeg4.AppleTag)file.GetTag(TagTypes.Apple);
                    Media = appletag.GetDashBox("com.apple.iTunes", "MEDIA");
                    Date  = DateTime.TryParse(appletag.DataBoxes(FixAppleId("day")).FirstOrDefault()?.Text, out tempDate) ? tempDate : default(DateTime?);
                    OriginalReleaseDate = DateTime.TryParse(appletag.GetDashBox("com.apple.iTunes", "Original Date"), out tempDate) ? tempDate : default(DateTime?);
                }

                OriginalYear = OriginalReleaseDate.HasValue ? (uint)OriginalReleaseDate?.Year : 0;

                foreach (ICodec codec in file.Properties.Codecs)
                {
                    IAudioCodec acodec = codec as IAudioCodec;

                    if (acodec != null && (acodec.MediaTypes & MediaTypes.Audio) != MediaTypes.None)
                    {
                        int bitrate = acodec.AudioBitrate;
                        if (bitrate == 0)
                        {
                            // Taglib can't read bitrate for Opus.
                            bitrate = EstimateBitrate(file, path);
                        }

                        Logger.Debug("Audio Properties: " + acodec.Description + ", Bitrate: " + bitrate + ", Sample Size: " +
                                     file.Properties.BitsPerSample + ", SampleRate: " + acodec.AudioSampleRate + ", Channels: " + acodec.AudioChannels);

                        Quality = QualityParser.ParseQuality(file.Name, acodec.Description);
                        Logger.Debug($"Quality parsed: {Quality}, Source: {Quality.QualityDetectionSource}");

                        MediaInfo = new MediaInfoModel
                        {
                            AudioFormat     = acodec.Description,
                            AudioBitrate    = bitrate,
                            AudioChannels   = acodec.AudioChannels,
                            AudioBits       = file.Properties.BitsPerSample,
                            AudioSampleRate = acodec.AudioSampleRate
                        };
                    }
                }

                IsValid = true;
            }
            catch (Exception ex)
            {
                if (ex is CorruptFileException)
                {
                    Logger.Warn(ex, $"Tag reading failed for {path}.  File is corrupt");
                }
                else
                {
                    // Log as error so it goes to sentry with correct fingerprint
                    Logger.Error(ex, "Tag reading failed for {0}", path);
                }
            }
            finally
            {
                file?.Dispose();
            }

            // make sure these are initialized to avoid errors later on
            if (Quality == null)
            {
                Quality = QualityParser.ParseQuality(path);
                Logger.Debug($"Unable to parse qulity from tag, Quality parsed from file path: {Quality}, Source: {Quality.QualityDetectionSource}");
            }

            MediaInfo = MediaInfo ?? new MediaInfoModel();
        }
Exemplo n.º 24
0
        public void Write(string path)
        {
            Logger.Debug($"Starting tag write for {path}");

            // patch up any null fields to work around TagLib exception for
            // WMA with null performers/albumartists
            Performers   = Performers ?? new string[0];
            AlbumArtists = AlbumArtists ?? new string[0];
            Genres       = Genres ?? new string[0];

            TagLib.File file = null;
            try
            {
                file = TagLib.File.Create(path);
                var tag = file.Tag;

                // do the ones with direct support in TagLib
                tag.Title        = Title;
                tag.Performers   = Performers;
                tag.AlbumArtists = AlbumArtists;
                tag.Track        = Track;
                tag.TrackCount   = TrackCount;
                tag.Album        = Album;
                tag.Disc         = Disc;
                tag.DiscCount    = DiscCount;
                tag.Publisher    = Publisher;
                tag.Genres       = Genres;

                if (ImageFile.IsNotNullOrWhiteSpace())
                {
                    tag.Pictures = new IPicture[1] {
                        new Picture(ImageFile)
                    };
                }

                if (file.TagTypes.HasFlag(TagTypes.Id3v2))
                {
                    var id3tag = (TagLib.Id3v2.Tag)file.GetTag(TagTypes.Id3v2);
                    id3tag.SetTextFrame("TMED", Media);
                    WriteId3Date(id3tag, "TDRC", "TYER", "TDAT", Date);
                    WriteId3Date(id3tag, "TDOR", "TORY", null, OriginalReleaseDate);
                }
                else if (file.TagTypes.HasFlag(TagTypes.Xiph))
                {
                    // while publisher is handled by taglib, it seems to be mapped to 'ORGANIZATION' and not 'LABEL' like Picard is
                    // https://picard.musicbrainz.org/docs/mappings/
                    tag.Publisher = null;

                    // taglib inserts leading zeros so set manually
                    tag.Track = 0;

                    var flactag = (TagLib.Ogg.XiphComment)file.GetTag(TagLib.TagTypes.Xiph);

                    flactag.SetField("DATE", Date.HasValue ? Date.Value.ToString("yyyy-MM-dd") : null);
                    flactag.SetField("ORIGINALDATE", OriginalReleaseDate.HasValue ? OriginalReleaseDate.Value.ToString("yyyy-MM-dd") : null);
                    flactag.SetField("ORIGINALYEAR", OriginalReleaseDate.HasValue ? OriginalReleaseDate.Value.Year.ToString() : null);
                    flactag.SetField("TRACKTOTAL", TrackCount);
                    flactag.SetField("TOTALTRACKS", TrackCount);
                    flactag.SetField("TRACKNUMBER", Track);
                    flactag.SetField("TOTALDISCS", DiscCount);
                    flactag.SetField("MEDIA", Media);
                    flactag.SetField("LABEL", Publisher);
                }
                else if (file.TagTypes.HasFlag(TagTypes.Ape))
                {
                    var apetag = (TagLib.Ape.Tag)file.GetTag(TagTypes.Ape);

                    apetag.SetValue("Year", Date.HasValue ? Date.Value.ToString("yyyy-MM-dd") : null);
                    apetag.SetValue("Original Date", OriginalReleaseDate.HasValue ? OriginalReleaseDate.Value.ToString("yyyy-MM-dd") : null);
                    apetag.SetValue("Original Year", OriginalReleaseDate.HasValue ? OriginalReleaseDate.Value.Year.ToString() : null);
                    apetag.SetValue("Media", Media);
                    apetag.SetValue("Label", Publisher);
                }
                else if (file.TagTypes.HasFlag(TagTypes.Asf))
                {
                    var asftag = (TagLib.Asf.Tag)file.GetTag(TagTypes.Asf);

                    asftag.SetDescriptorString(Date.HasValue ? Date.Value.ToString("yyyy-MM-dd") : null, "WM/Year");
                    asftag.SetDescriptorString(OriginalReleaseDate.HasValue ? OriginalReleaseDate.Value.ToString("yyyy-MM-dd") : null, "WM/OriginalReleaseTime");
                    asftag.SetDescriptorString(OriginalReleaseDate.HasValue ? OriginalReleaseDate.Value.Year.ToString() : null, "WM/OriginalReleaseYear");
                    asftag.SetDescriptorString(Media, "WM/Media");
                    asftag.SetDescriptorString(Publisher, "WM/Publisher");
                }
                else if (file.TagTypes.HasFlag(TagTypes.Apple))
                {
                    var appletag = (TagLib.Mpeg4.AppleTag)file.GetTag(TagTypes.Apple);

                    appletag.SetText(FixAppleId("day"), Date.HasValue ? Date.Value.ToString("yyyy-MM-dd") : null);
                    appletag.SetDashBox("com.apple.iTunes", "Original Date", OriginalReleaseDate.HasValue ? OriginalReleaseDate.Value.ToString("yyyy-MM-dd") : null);
                    appletag.SetDashBox("com.apple.iTunes", "Original Year", OriginalReleaseDate.HasValue ? OriginalReleaseDate.Value.Year.ToString() : null);
                    appletag.SetDashBox("com.apple.iTunes", "MEDIA", Media);
                }

                file.Save();
            }
            catch (CorruptFileException ex)
            {
                Logger.Warn(ex, $"Tag writing failed for {path}.  File is corrupt");
            }
            catch (Exception ex)
            {
                Logger.Warn()
                .Exception(ex)
                .Message($"Tag writing failed for {path}")
                .WriteSentryWarn("Tag writing failed")
                .Write();
            }
            finally
            {
                file?.Dispose();
            }
        }
Exemplo n.º 25
0
        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();
            }
        }
Exemplo n.º 26
0
 void SaveTags()
 {
     dgv.EndEdit();
     foreach (Track t in tracks)
     {
         if (Program.mainWindow.nowPlaying != null && Program.mainWindow.nowPlaying.filename == t.filename)
         {
             Program.mainWindow.UnloadAudioFile();
         }
         if (!System.IO.File.Exists(t.filename))
         {
             continue;
         }
         using (TagLib.File tagFile = TagLib.File.Create(t.filename))
         {
             string title = (string)dgv.Rows[0].Cells[1].Value;
             if (title == "&unchanged")
             {
                 title = tagFile.Tag.Title;
             }
             string artist = (string)dgv.Rows[1].Cells[1].Value;
             if (artist == "&unchanged")
             {
                 if (tagFile.Tag.Performers.Length > 0)
                 {
                     artist = tagFile.Tag.Performers[0];
                 }
                 else
                 {
                     artist = "";
                 }
             }
             string album = (string)dgv.Rows[2].Cells[1].Value;
             if (album == "&unchanged")
             {
                 album = tagFile.Tag.Album;
             }
             string comment = (string)dgv.Rows[4].Cells[1].Value;
             if (comment == "&unchanged")
             {
                 comment = tagFile.Tag.Comment;
             }
             string genre = (string)dgv.Rows[5].Cells[1].Value;
             if (genre == "&unchanged")
             {
                 if (tagFile.Tag.Genres.Length > 0)
                 {
                     genre = tagFile.Tag.Genres[0];
                 }
                 else
                 {
                     genre = "";
                 }
             }
             int year = (int)tagFile.Tag.Year;
             if ((string)dgv.Rows[3].Cells[1].Value != "&unchanged")
             {
                 try
                 {
                     year = Int32.Parse((string)dgv.Rows[3].Cells[1].Value);
                 }
                 catch (Exception)
                 {
                     MessageBox.Show("Year field is invalid. Must be a 4-digit number.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                     return;
                 }
             }
             tagFile.Tag.Title      = title;
             tagFile.Tag.Performers = null;
             tagFile.Tag.Performers = new[] { artist };
             tagFile.Tag.Album      = album;
             tagFile.Tag.Year       = (uint)year;
             tagFile.Tag.Comment    = comment;
             tagFile.Tag.Genres     = null;
             tagFile.Tag.Genres     = new[] { genre };
             tagFile.Save();
             if (!String.IsNullOrEmpty(title))
             {
                 t.title = title;
             }
             t.artist = artist;
             t.album  = album;
             //t.year=(string)year;
             //t.comment=comment;
             tagFile.Dispose();
         }
     }
     Program.mainWindow.UpdateCache(tracks);
     (Owner as Echoes).RefreshGrid();
 }
Exemplo n.º 27
0
        private void copyAudioFile(string input, string output, string entryName, BeatmapEntry bmp)
        {
            try
            {
                System.IO.File.Copy(input, output, true);

                if (Configs.OverwriteAlbum || Configs.OverwriteArtist || Configs.OverwriteTitle)
                {
                    File = TagLib.File.Create(output);
                    TagLib.File fileAux = null;

                    if (useAuxFile())
                    {
                        fileAux = File;
                    }

                    if (forceTitle()) //ask title
                    {
                        File.Tag.Title = bmp.Title;
                    }
                    else if (notForceTitle())
                    {
                        if (fileAux.Tag.Title == null)
                        {
                            File.Tag.Title = bmp.Title;
                        }
                    }

                    if (forceAlbum()) //ask album
                    {
                        File.Tag.Album = ValidMode;
                    }
                    else if (notForceTitle())
                    {
                        if (fileAux.Tag.Album == null)
                        {
                            File.Tag.Album = ValidMode;
                        }
                    }

                    if (forceArtist())
                    {
                        updateArtist(bmp.Artist);
                    }
                    else if (notForceArtist())
                    {
                        if (fileAux.Tag.AlbumArtists.Count() == 0 && fileAux.Tag.Performers.Count() == 0)
                        {
                            updateArtist(bmp.Artist);
                        }
                        else if (fileAux.Tag.AlbumArtists.Count() != 0 && fileAux.Tag.Performers.Count() == 0)
                        {
                            updateArtist(File.Tag.AlbumArtists[0]);
                        }
                        else if (fileAux.Tag.Performers.Count() != 0 && fileAux.Tag.AlbumArtists.Count() == 0)
                        {
                            updateArtist(File.Tag.Performers[0]);
                        }
                    }

                    if (Configs.IncludeThumbnails && Configs.ForceImage)
                    {
                        embedPicture(PicDefault);
                    }
                    else if (Configs.IncludeThumbnails)
                    {
                        BeatmapFile beatmapFile = BeatmapFile.Read(Path.Combine(Configs.SongsPath, bmp.FolderName, bmp.BeatmapFileName), true);

                        string imagePath;
                        if (beatmapFile.BackgroundImageFile != null && System.IO.File.Exists(imagePath = Path.Combine(Configs.SongsPath, bmp.FolderName, beatmapFile.BackgroundImageFile)))
                        {
                            try
                            {
                                using (MemoryStream ms = new MemoryStream())
                                {
                                    Image png = Image.FromFile(imagePath);

                                    png.Save(ms, ImageFormat.Jpeg);
                                    ms.Position = 0;
                                    png.Dispose();

                                    Pic.Data = TagLib.ByteVector.FromStream(ms);
                                    embedPicture(Pic);
                                }
                            }
                            catch (Exception)
                            {
                                embedPicture(PicDefault);
                            }
                        }
                        else
                        {
                            embedPicture(PicDefault);
                        }
                    }

                    File.Save();

                    if (useAuxFile())
                    {
                        fileAux.Dispose();
                    }
                }
            }
            catch (FileNotFoundException fileMissing)
            {
                Log.Add("[Error] For beatmap: " + entryName + " = " + fileMissing.Message);
            }
            catch (UnauthorizedAccessException noAccess)
            {
                Log.Add("[Error] For beatmap: " + entryName + " = " + noAccess.Message);
            }
            catch (TagLib.UnsupportedFormatException unsupportedFile)
            {
                Log.Add("[Error] For beatmap: " + entryName + " = " + unsupportedFile.Message);
            }
            catch (TagLib.CorruptFileException corrupt)
            {
                Log.Add("[Error] For beatmap: " + entryName + " = " + corrupt.Message);
            }
            catch (Exception exeption)
            {
                Log.Add("[Error] For beatmap: " + entryName + " = " + exeption.Message);
            }
        }
Exemplo n.º 28
0
 public void Dispose()
 {
     _taglibMp3MetadataEditor.Dispose();
 }
Exemplo n.º 29
0
 public void Save()
 {
     TagLib.File save = File;
     save.Save();
     save.Dispose();
 }
Exemplo n.º 30
0
        public async Task SaveAsync(StorageFile file)
        {
            var audioPath = file.Path;

            if (_libraryService.Tracks.Any(p => p.AudioLocalUri == audioPath))
            {
                return;
            }

            #region id3 tags

            var tryAsM4A   = false;
            var fileStream = await file.OpenStreamForReadAsync();

            File tagFile = null;
            try
            {
                tagFile = File.Create(new StreamFileAbstraction(file.Name, fileStream, fileStream));
            }
            catch (Exception e)
            {
                tryAsM4A = e is CorruptFileException;
            }

            if (tryAsM4A)
            {
                //need to reopen (when it fails to open it disposes of the stream
                fileStream = await file.OpenStreamForReadAsync();

                try
                {
                    tagFile = File.Create(new StreamFileAbstraction(
                                              file.Name.Replace(".mp3", ".m4a"),
                                              fileStream,
                                              fileStream));
                }
                catch
                {
                    // ignored
                }
            }

            var tags = tagFile?.Tag;
            fileStream.Dispose();
            tagFile?.Dispose();

            #endregion

            var prop = await file.Properties.GetMusicPropertiesAsync().AsTask().ConfigureAwait(false);

            var track = tags == null?CreateTrack(prop, audioPath) : CreateTrack(prop, tags, audioPath);

            //if no metadata was obtain, then result to using the filename
            if (string.IsNullOrEmpty(track.Title))
            {
                track.Title = file.DisplayName;
            }

            if (string.IsNullOrEmpty(track.AlbumArtist))
            {
                track.AlbumArtist = tags?.FirstAlbumArtist;
            }

            if (_libraryService.Find(track) != null)
            {
                return;
            }

            await _trackSaveService.SaveAsync(track, tags).ConfigureAwait(false);
        }