Create() public static method

Creates a new instance of a File subclass for a specified file abstraction, guessing the mime-type from the file's extension and using the average read style.
/// The file could not be read due to corruption. /// /// The file could not be read because the mime-type could /// not be resolved or the library does not support an /// internal feature of the file crucial to its reading. ///
public static Create ( IFileAbstraction abstraction ) : File
abstraction IFileAbstraction /// A object to use when /// reading to and writing from the current instance. ///
return File
Exemplo n.º 1
0
        internal Result <List <MusicFileTag> > LoadMusicFilesFromRoot(string root)
        {
            var musicFileTags = new List <MusicFileTag>();
            var foldersList   = new List <string>();

            foldersList.Add(root);
            // add subfolders
            foldersList.AddRange(this.GetSubfolders(root));

            Regex reg = new Regex(@"^((?!\._).)*$");

            foreach (var folder in foldersList)
            {
                var folderContent = Directory.GetFiles(folder, "*.mp3")
                                    .Where(path => reg.IsMatch(path))
                                    .ToList();

                foreach (var file in folderContent)
                {
                    try
                    {
                        var tagInfo = File.Create(file);
                        musicFileTags.Add(MusicFileTag.ConvertTagToMusicFileTag(tagInfo.Tag, tagInfo.Name));
                    }
                    catch (CorruptFileException e)
                    {
                        return(HandleError(file, e));
                    }
                }
            }

            return(new Result <List <MusicFileTag> >(musicFileTags, Status.Success));
        }
Exemplo n.º 2
0
        private async Task TagAudioFile(Video video, string filePath, CancellationToken cancellationToken)
        {
            // Try to extract artist/title from video title
            if (!TryExtractArtistAndTitle(video.Title, out var artist, out var title))
            {
                return;
            }

            // Try to get tags
            var tagsJson = await TryGetTagsJsonAsync(artist !, title !, cancellationToken);

            // Try to get picture
            var picture = await TryGetPictureAsync(video, cancellationToken);

            // Extract information
            var resolvedArtist    = tagsJson?["artist-credit"]?.FirstOrDefault()?["name"]?.Value <string>();
            var resolvedTitle     = tagsJson?["title"]?.Value <string>();
            var resolvedAlbumName = tagsJson?["releases"]?.FirstOrDefault()?["title"]?.Value <string>();

            // Inject tags
            var taggedFile = File.Create(filePath);

            taggedFile.Tag.Performers = new[] { resolvedArtist ?? artist ?? "" };
            taggedFile.Tag.Title      = resolvedTitle ?? title ?? "";
            taggedFile.Tag.Album      = resolvedAlbumName ?? "";
            taggedFile.Tag.Pictures   = picture != null ? new[] { picture } : Array.Empty <IPicture>();
            taggedFile.Save();
        }
Exemplo n.º 3
0
        public static void Write(string path, Track track)
        {
            using (var file = File.Create(path))
            {
                file.Tag.Title      = track.Title;
                file.Tag.Performers = new[] { track.Artist.Name };
                if (track.Album.Artist != null)
                {
                    file.Tag.AlbumArtists = new[] { track.Album.Artist.Name };
                }
                file.Tag.Genres     = new[] { track.Genre };
                file.Tag.Album      = track.Album.Title;
                file.Tag.Track      = (uint)track.TrackNumber;
                file.Tag.TrackCount = (uint)(track.Album.GetNumberOfTracksOnDisc(track.DiscNumber) ?? 0);
                file.Tag.Disc       = (uint)track.DiscNumber;
                file.Tag.DiscCount  = (uint)(track.Album.GetTotalDiscs() ?? 0);
                file.Tag.Year       = (uint)track.Year;
                file.Tag.Copyright  = CopyrightText;
                file.Tag.Comment    = CopyrightText;


                file.Save();
            }

            string fileName = null;
        }
Exemplo n.º 4
0
        public static void Write(FileType fileType, string path, Track track)
        {
            ImageFile artworkFile = null;
            var       url         = track.Album.CoverUri.ToString();

            if (ImageCache.Instance.HasItem(url) && ImageCache.Instance.Get(url) != null)
            {
                artworkFile = ImageCache.Instance.Get(track.Album.CoverUri.ToString());
            }

            using (var file = File.Create(new File.LocalFileAbstraction(path), fileType.MimeType, ReadStyle.Average))
            {
                file.Tag.Title      = track.Title;
                file.Tag.Performers = new[] { track.Artist.Name };
                if (track.Album.Artist != null)
                {
                    file.Tag.AlbumArtists = new[] { track.Album.Artist.Name };
                }
                file.Tag.Genres     = new[] { track.Genre };
                file.Tag.Album      = track.Album.Title;
                file.Tag.Track      = (uint)track.TrackNumber;
                file.Tag.TrackCount = (uint)(track.Album.GetNumberOfTracksOnDisc(track.DiscNumber) ?? 0);
                file.Tag.Disc       = (uint)track.DiscNumber;
                file.Tag.DiscCount  = (uint)(track.Album.GetTotalDiscs() ?? 0);
                file.Tag.Year       = (uint)track.Year;
                file.Tag.Copyright  = CopyrightText;
                file.Tag.Comment    = CopyrightText;
                if (artworkFile != null)
                {
                    file.Tag.Pictures = new IPicture[] { new Picture(new ByteVector(artworkFile.Data)) };
                }

                file.Save();
            }


            string fileName = null;

            switch (Program.DefaultSettings.Settings.AlbumArtworkSaveFormat)
            {
            case AlbumArtworkSaveFormat.DontSave:
                break;

            case AlbumArtworkSaveFormat.AsCover:
                fileName = artworkFile?.FileType.Append("cover");
                break;

            case AlbumArtworkSaveFormat.AsArtistAlbum:
                fileName = artworkFile?.FileType.Append($"{track.Artist} - {track.Album.Title}");
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
            if (fileName != null && artworkFile != null)
            {
                var parentDir = Path.GetDirectoryName(path);
                SysFile.WriteAllBytes(Path.Combine(parentDir, fileName), artworkFile.Data);
            }
        }
Exemplo n.º 5
0
        internal Result <List <MusicFileTag> > LoadMusicFilesFromList(List <string> folderContent)
        {
            var musicFileTags = new List <MusicFileTag>();

            foreach (var file in folderContent)
            {
                try
                {
                    // make sure only *.mp3 files are processed
                    FileInfo info = new FileInfo(file);
                    if (info.Extension != ".mp3")
                    {
                        continue;
                    }

                    var tagInfo = File.Create(file);
                    musicFileTags.Add(MusicFileTag.ConvertTagToMusicFileTag(tagInfo.Tag, tagInfo.Name));
                }
                catch (CorruptFileException e)
                {
                    return(HandleError(file, e));
                }
            }

            return(new Result <List <MusicFileTag> >(musicFileTags, Status.Success));
        }
Exemplo n.º 6
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.º 7
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.º 8
0
 public override void LoadCover()
 {
     using (var tl = File.Create(new TagLibFileAbstraction(Item)))
     {
         InitCover(tl.Tag);
     }
 }
Exemplo n.º 9
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);
        }
        private File SaveToFile(string filePath, byte stars, List <Performer> performers, string album, uint trackNo, uint year,
                                string comment, string[] genres)
        {
            var file = File.Create(filePath);
            var tag  = file.TagTypes != TagTypes.Id3v2 ? file.Tag : file.GetTag(TagTypes.Id3v2);

            var rating = tag.GetPopularimeterFrame();

            if (rating != null)
            {
                rating.Rating = stars;
            }
            if (performers != null)
            {
                tag.Performers =
                    performers.Select(performer => performer.ToString()).Where(p => p != null).ToArray();
            }
            tag.Album = album;
            if (trackNo != 0)
            {
                tag.Track = trackNo;
            }
            if (year != 0)
            {
                tag.Year = year;
            }
            tag.Comment = comment;
            tag.Genres  = genres;

            return(SaveToFile(file, tag));
        }
Exemplo n.º 11
0
        private async Task InjectAudioTagsAsync(
            Video video,
            string filePath,
            CancellationToken cancellationToken = default)
        {
            if (!TryExtractArtistAndTitle(video.Title, out var artist, out var title))
            {
                return;
            }

            var tagsJson = await TryGetMusicBrainzTagsJsonAsync(artist !, title !, cancellationToken);

            var picture = await TryGetPictureAsync(video, cancellationToken);

            var resolvedArtist    = tagsJson?["artist-credit"]?.FirstOrDefault()?["name"]?.Value <string>();
            var resolvedTitle     = tagsJson?["title"]?.Value <string>();
            var resolvedAlbumName = tagsJson?["releases"]?.FirstOrDefault()?["title"]?.Value <string>();

            var file = File.Create(filePath);

            file.Tag.Performers = new[] { resolvedArtist ?? artist ?? "" };
            file.Tag.Title      = resolvedTitle ?? title ?? "";
            file.Tag.Album      = resolvedAlbumName ?? "";

            file.Tag.Pictures = picture != null
                ? new[] { picture }
                : Array.Empty <IPicture>();

            file.Save();
        }
Exemplo n.º 12
0
        public void TestWriteFlacUid()
        {
            var flacFile = string.Format("{0}\\{1:N}.flac", Path.GetTempPath(), Guid.NewGuid());

            System.IO.File.Copy(@"TestData\hei.flac", flacFile, true);

            var file = File.Create(flacFile);

            Metadata metadata = (Metadata)file.GetTag(TagTypes.FlacMetadata, true);

            XiphComment xiphComment = (XiphComment)metadata.Tags.First();

            xiphComment.SetField("SW-AlbumUid", Guid.NewGuid().ToString("N"));
            file.Save();
            //metadata.SetTextFrame((ReadOnlyByteVector) "UFID", "http://www.id3.org/dummy/ufid.html", Guid.NewGuid().ToString("N"));

            //file.Save();

            //File actualFile = File.Create(mp3File);

            //metadata = (Tag)actualFile.GetTag(TagTypes.Id3v2, true);
            //// Get the private frame, create if necessary.
            //var frame = metadata.GetFrames().FirstOrDefault(f => f.FrameId == "UFID");
            //frame.Should().NotBeNull();

            System.IO.File.Delete(flacFile);
        }
        public void Rewrite()
        {
            for (int i = 0; i < count; i++)
            {
                var tmp = Utils.CreateTmpFile(GetSampleFilename(i), GetTmpFilename(i));

                tmp.Save();

                tmp = File.Create(GetTmpFilename(i));

                if ((TagTypes.TiffIFD & contained_types[i]) != 0)
                {
                    CheckExif(tmp, i);
                }

                if ((TagTypes.XMP & contained_types[i]) != 0)
                {
                    CheckXmp(tmp, i);
                }

                if ((TagTypes.JpegComment & contained_types[i]) != 0)
                {
                    CheckJpegComment(tmp, i);
                }
            }
        }
Exemplo n.º 14
0
        public TrackFull ReadTrack(int id, string path)
        {
            using (File file = File.Create(new File.LocalFileAbstraction(path))) {
                MediaFormat mf = IdentifyFormat(file);
                if (mf == MediaFormat.Unknown)
                {
                    return(null);
                }

                Tag tag = file.Tag;
                return(new TrackFull {
                    Id = id,
                    TrackNumber = tag.Track,
                    FileName = Path.GetFileName(path),
                    Title = tag.Title,
                    Artist = tag.FirstPerformer,
                    Year = tag.Year,
                    Album = tag.Album,
                    AlbumArtist = tag.FirstAlbumArtist,
                    Genre = tag.FirstGenre,
                    Length = (long)Math.Round(file.Properties.Duration.TotalSeconds),
                    MediaFormat = mf,
                    Bitrate = file.Properties.AudioBitrate
                });
            }
        }
Exemplo n.º 15
0
        private void MaybeInit()
        {
            if (initialized)
            {
                return;
            }

            try
            {
                using (var tl = File.Create(new TagLibFileAbstraction(Item)))
                {
                    try
                    {
                        duration = tl.Properties.Duration;
                        if (duration.Value.TotalSeconds < 0.1)
                        {
                            duration = null;
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug("Failed to transpose Properties props", ex);
                    }

                    try
                    {
                        var t = tl.Tag;
                        SetProperties(t);
                        //InitCover(t);
                    }
                    catch (Exception ex)
                    {
                        Debug("Failed to transpose Tag props", ex);
                    }
                }

                initialized = true;

                Server.UpdateFileCache(this);
            }
            catch (CorruptFileException ex)
            {
                Debug(
                    "Failed to read meta data via taglib for file " + Item.FullName, ex);
                initialized = true;
            }
            catch (UnsupportedFormatException ex)
            {
                Debug(
                    "Failed to read meta data via taglib for file " + Item.FullName, ex);
                initialized = true;
            }
            catch (Exception ex)
            {
                Warn(
                    "Unhandled exception reading meta data for file " + Item.FullName,
                    ex);
            }
        }
Exemplo n.º 16
0
 public void RemoveTags()
 {
     using (var mp3File = File.Create(filePath))
     {
         mp3File.RemoveTags(TagTypes.AllTags);
         mp3File.Save();
     }
 }
Exemplo n.º 17
0
 private void RemoveAllTags(string path)
 {
     using (var tagLibFile = TagLibFile.Create(path))
     {
         tagLibFile.RemoveTags(TagTypes.AllTags);
         tagLibFile.Save();
     }
 }
Exemplo n.º 18
0
 private void TrySetId3Tag()
 {
     using (var mp3File = File.Create(filePath))
     {
         SetTags(mp3File);
         mp3File.Save();
     }
 }
Exemplo n.º 19
0
 private IEnumerable <RebuildWalkResult> ScanFiles()
 {
     return(_dirWalker.Walk(_sourceDir, fp =>
     {
         if (fp.IsMediaFile())
         {
             TagLibFile tLFile;
             try
             {
                 tLFile = TagLibFile.Create(fp);
             }
             catch (Exception e)
             {
                 Console.WriteLine($"{e.GetType()}: {e.Message}");
                 return new RebuildWalkResult
                 {
                     IsValidToMove = false,
                     IsMediaFile = true,
                     OldPath = fp,
                 };
             }
             var filename = Path.GetFileName(fp);
             var album = _fileSystemHelpers.MakeStringPathSafe(tLFile.Tag.Album ?? "");
             var artistTag = string.Join(", ", tLFile.Tag.AlbumArtists).Trim();
             if (string.IsNullOrWhiteSpace(artistTag))
             {
                 artistTag = string.Join(", ", tLFile.Tag.Artists).Trim();
             }
             if (string.IsNullOrWhiteSpace(artistTag))
             {
                 artistTag = string.Join(", ", tLFile.Tag.Performers).Trim();
             }
             var artist = _fileSystemHelpers.MakeStringPathSafe(artistTag);
             var newPath = "";
             var isValid = !string.IsNullOrWhiteSpace(album) && !string.IsNullOrWhiteSpace(artist);
             if (isValid)
             {
                 newPath = Path.Combine(_outDir, artist, album, filename);
             }
             return new RebuildWalkResult
             {
                 Album = album,
                 Artist = artist,
                 IsValidToMove = isValid,
                 OldPath = fp,
                 NewPath = newPath,
                 IsMediaFile = true,
                 RequiresMove = fp != newPath
             };
         }
         return new RebuildWalkResult
         {
             IsValidToMove = false,
             IsMediaFile = false,
             OldPath = fp,
         };
     }));
 }
Exemplo n.º 20
0
        public static void Write(string serviceName, Track completedTrack, TrackFile trackFile, AlbumArtworkSaveFormat saveFormat, string path, bool writeWatermarkTags)
        {
            // Get album artwork from cache
            ImageCacheEntry albumArtwork = null;
            var             smid         = completedTrack.Album.GetSmid(serviceName).ToString();

            if (ImageCache.Instance.HasItem(smid))
            {
                albumArtwork = ImageCache.Instance.Get(smid);
            }

            // Write track tags
            var track = completedTrack;

            using (var file = File.Create(new File.LocalFileAbstraction(path),
                                          trackFile.FileType.MimeType, ReadStyle.Average))
            {
                file.Tag.Title      = track.Title;
                file.Tag.Performers = new[] { track.Artist.Name };
                if (track.Album.Artist != null)
                {
                    file.Tag.AlbumArtists = new[] { track.Album.Artist.Name };
                }
                if (track.Genre != null)
                {
                    file.Tag.Genres = new[] { track.Genre };
                }
                file.Tag.Album      = track.Album.Title;
                file.Tag.Track      = (uint)track.TrackNumber;
                file.Tag.TrackCount = (uint)(track.Album.GetNumberOfTracksOnDisc(track.DiscNumber) ?? 0);
                file.Tag.Disc       = (uint)track.DiscNumber;
                file.Tag.DiscCount  = (uint)(track.Album.GetTotalDiscs() ?? 0);
                file.Tag.Year       = (uint)track.Year;
                if (writeWatermarkTags)
                {
                    file.Tag.Comment = WatermarkText;
                }
                if (albumArtwork != null)
                {
                    file.Tag.Pictures = new IPicture[] { new TagLib.Picture(new ByteVector(albumArtwork.Data)) };
                }

                file.Save();
            }

            // Write album artwork to file if requested
            if (albumArtwork == null)
            {
                return;
            }
            string parentDirectory;

            if (saveFormat != AlbumArtworkSaveFormat.DontSave &&
                (parentDirectory = Path.GetDirectoryName(path)) != null)
            {
                WriteArtworkFile(parentDirectory, saveFormat, track, albumArtwork);
            }
        }
 public void SetValues(string fileInfo)
 {
     if (System.IO.File.Exists(fileInfo))
     {
         _isMulti = false;
         _file    = File.Create(fileInfo);
         SetValues();
     }
 }
        public void Init()
        {
            files = new File[count];

            for (int i = 0; i < count; i++)
            {
                files[i] = File.Create(GetSampleFilename(i));
            }
        }
Exemplo n.º 23
0
        public void Iim_Keywords()
        {
            var file = File.Create(TestPath.Samples + "sample_iptc1.jpg");
            var tag  = file.GetTag(TagTypes.XMP) as XmpTag;

            Assert.IsNotNull(tag, "tag");

            CollectionAssert.AreEqual(new[] { "kw1", "kw2", "kw3 " }, tag.Keywords);
        }
        private void UpdateDBThread()
        {
            log.Debug("Database Update: Starting Database update thread");
            _processCount = 0;
            _audioFiles   = 0;

            OpenConnection();
            while ((fileThread.ThreadState == ThreadState.Running || _processCount < files.Count) && !_abortScan)
            {
                if (_processCount == files.Count || files.Count == 0)
                {
                    continue;
                }
                string fileName = files[_processCount].FullName;
                if (Util.IsAudio(fileName))
                {
                    _audioFiles++;
                    try
                    {
                        ByteVector.UseBrokenLatin1Behavior = true;
                        File file = File.Create(fileName);
                        AddSong(file);
                    }
                    catch (CorruptFileException)
                    {
                        log.Warn("FolderScan: Ignoring track {0} - Corrupt File!", fileName);
                    }
                    catch (UnsupportedFormatException)
                    {
                        log.Warn("FolderScan: Ignoring track {0} - Unsupported format!", fileName);
                    }
                }
                _processCount++;
            }

            CloseConnection();
            _scanHasRun = true;

            DateTime stopTime = DateTime.Now;

            _ts = stopTime - _startTime;
            float fSecsPerTrack = ((float)_ts.TotalSeconds / files.Count);

            _trackPerSecSummary = "";
            if (files.Count > 0)
            {
                _trackPerSecSummary = string.Format(localisation.ToString("Settings", "DBScanTrackSummary"), fSecsPerTrack);
            }

            log.Info(
                "Database Update: Music database update done.  Processed {0} tracks in: {1:d2}:{2:d2}:{3:d2}{4}",
                _audioFiles, _ts.Hours, _ts.Minutes, _ts.Seconds, _trackPerSecSummary);

            log.Debug("Database Update: Ending Database Update thread");
        }
Exemplo n.º 25
0
        public static void DumpTrackMetadata(IO.FileStream file, string mimetype)
        {
            // Load up the file using TagLib
            File tagFile;

            try
            {
                tagFile = File.Create(new StreamFileAbstraction(file.Name, file, null), mimetype, ReadStyle.Average);
            }
            catch (UnsupportedFormatException)
            {
                Console.Error.WriteLine("*** The file format is not supported.");
                return;
            }

            if (tagFile.PossiblyCorrupt)
            {
                Console.Error.WriteLine("*** The file is possibly corrupt. Reasons:");
                Console.Error.WriteLine("    {0}", String.Join(",", tagFile.CorruptionReasons));
            }

            // Fetch the metadata from the file
            if (tagFile.TagTypesOnDisk.HasFlag(TagTypes.Xiph))
            {
                Console.WriteLine("-----------------");
                Console.WriteLine("Found XIPH Tags");
                DumpXiphMetadata(tagFile);
            }
            if (tagFile.TagTypesOnDisk.HasFlag(TagTypes.Id3v2))
            {
                Console.WriteLine("-----------------");
                Console.WriteLine("Found ID3v2");
                DumpId3V2Metadata(tagFile);
            }
            if (tagFile.TagTypesOnDisk.HasFlag(TagTypes.Id3v1))
            {
                Console.WriteLine("-----------------");
                Console.WriteLine("Found ID3v1 Tags");
                //ReadId3V1Metadata(result, tagFile);
            }
            else if (tagFile.TagTypes.HasFlag(TagTypes.Asf))
            {
                //ReadAsfMetadata(result, tagFile);
            }
            else
            {
                //throw new DolomiteInternalException(null, "The file format is not supported.",
                //    String.Format("Mimetype {0} was read correctly, no supported TagTypesOnDisk are available. TagTypes: {1}",
                //        mimetype, tagFile.TagTypesOnDisk));
            }

            // Read the codec details and, optionally, the album art
            //DumpCodecDetails(tagFile);
            //ReadPictureDetails(result, tagFile);
        }
Exemplo n.º 26
0
 /// <exception cref="FileException">Throws when mp3 file could not be loaded.</exception>
 public void Reload()
 {
     try
     {
         this.mp3File = File.Create(this.WishedFilePath);
     }
     catch (UnsupportedFormatException)
     {
         throw new FileException(string.Format(Resources.TagLibMp3File_Exception_InvalidFilePath, this.WishedFilePath));
     }
 }
Exemplo n.º 27
0
 /// <exception cref="FileException">Throws when mp3 file could not be loaded.</exception>
 public TagLibMp3File(string paramFilePath)
 {
     try
     {
         this.mp3File = File.Create(paramFilePath);
     }
     catch (UnsupportedFormatException)
     {
         throw new FileException(Resources.TagLibMp3File_Exception_InvalidFilePath, string.Format(Resources.TagLibMp3File_Inner_Exception_InvalidFilePath, paramFilePath));
     }
 }
Exemplo n.º 28
0
        public void ParseXmp()
        {
            var file = File.Create(sample_file, "taglib/jpeg", ReadStyle.Average) as TagLib.Image.File;

            Assert.IsNotNull(file, "file");

            var tag = file.ImageTag;

            Assert.IsNotNull(tag, "ImageTag");
            Assert.AreEqual("SONY ", tag.Make);
            Assert.AreEqual("DSLR-A330", tag.Model);
        }
Exemplo n.º 29
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.º 30
0
        public void SetAudioFileAndTag(Stream stream, string fileName)
        {
            //Create a simple file and simple file abstraction
            var simpleFile            = new SimpleFile(fileName, stream);
            var simpleFileAbstraction = new SimpleFileAbstraction(simpleFile);

            /////////////////////

            //Create a taglib file from the simple file abstraction
            _songFile = File.Create(simpleFileAbstraction);
            _tag      = _songFile.Tag;
        }