This abstract class provides a basic framework for reading from and writing to a file, as well as accessing basic tagging and media properties.

This class is agnostic to all specific media types. Its child classes, on the other hand, support the the intricacies of different media and tagging formats. For example, supports the MPEG-4 specificication and Apple's tagging format.

Each file type can be created using its format specific constructors, ie. Mpeg4.File(string), but the preferred method is to use or one of its variants, as it automatically detects the appropriate class from the file extension or provided mime-type.

Наследование: IDisposable
 public ZuneMP3TagContainer(File file)
     : base(file)
 {
     //if we can't find the id3v2 tag we will create it, this will handle cases
     //where we load a tag with id3v1 only
     _tag = (Tag) file.GetTag(TagTypes.Id3v2, true);
 }
Пример #2
0
        public utwor(String path)
        {
            //Console.WriteLine("sciezka = path;");
            sciezka = path;

            //Console.WriteLine("if (!System.IO.File.Exists(path))");
            if (!System.IO.File.Exists(path))
            {
                nazwa = "Błąd: Plik nie istnieje.";
                return;
            }

            //Console.WriteLine("rozszerzenie = System.IO.Path.GetExtension(path).Substring(1);");
            rozszerzenie = System.IO.Path.GetExtension(path).Substring(1);
            nazwa = System.IO.Path.GetFileNameWithoutExtension(path);
            staraNazwa = System.IO.Path.GetFileNameWithoutExtension(path);

            //Console.WriteLine("");
            if (!wspierane_rozszerzenia.Contains(rozszerzenie))
            {
                //nazwa = "Błąd: Nie wspierane rozszerzenie: " + rozszerzenie;
                throw new NotSupportedException("Błąd: Nie wspierane rozszerzenie: " + rozszerzenie);
            }
            else
            {
                //Console.WriteLine("tagi = TagLib.File.Create(path);");
                tagi = TagLib.File.Create(path);
                stareTagi = TagLib.File.Create(path);
                przepisz_tagi();
            }
        }
Пример #3
0
 public Composition(string path, PropertyChangedEventHandler PropertyChanged)
 {
     this.PropertyChanged += PropertyChanged;
     FileInfo = TagLib.File.Create(path);
     if (FileInfo.Tag.Artists.Length == 0)
         Artists = "Unknown artist";
     else
     {
         foreach (string str in FileInfo.Tag.Artists)
         {
             Artists += str;
             Artists += "; ";
         }
         Artists = Artists.Substring(0, Artists.Length - 2);
     }
     if (FileInfo.Tag.Title == null)
         Title = "Unknown title";
     else
         Title = FileInfo.Tag.Title;
     if (FileInfo.Tag.Album == null)
         Album = "Unknown album";
     else
         Album = FileInfo.Tag.Album;
     Name = FileInfo.Name;
     Image = new BitmapImage();
     Image.BeginInit();
     if (FileInfo.Tag.Pictures.Length != 0)
         Image.StreamSource = new MemoryStream(FileInfo.Tag.Pictures[0].Data.Data);
     else
         Image.UriSource = new Uri("Content\\note-blue.png", UriKind.RelativeOrAbsolute);
     Image.EndInit();
 }
Пример #4
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");
                 }
             }
         }
     }
 }
Пример #5
0
        public string Title(string sPath)
        {
            TagLib.File music = TagLib.File.Create(sPath);
            String      title = music.Tag.Title;

            return(title);
        }
Пример #6
0
        private void SetNameFromMetaData(MetaData md)
        {
            bool title  = !String.IsNullOrEmpty(md.Tag.Title);
            bool artist = !String.IsNullOrEmpty(md.Tag.FirstPerformer);

            if (title && artist)
            {
                Name = md.Tag.FirstPerformer + " - " + md.Tag.Title;
            }
            else if (!String.IsNullOrEmpty(md.Tag.FirstAlbumArtist) && title)
            {
                Name = md.Tag.FirstAlbumArtist + " - " + md.Tag.Title;
            }
            else if (!title && artist)
            {
                Name = md.Tag.FirstPerformer + " - " +
                       // ReSharper disable once AssignNullToNotNullAttribute
                       Regex.Replace(input: System.IO.Path.GetFileNameWithoutExtension(Path), pattern: @"[\d-]", replacement: "", options: RegexOptions.Multiline)
                       .TrimStart();
            }
            else
            {
                Name = "Unknown Artist - " +
                       // ReSharper disable once AssignNullToNotNullAttribute
                       Regex.Replace(input: System.IO.Path.GetFileNameWithoutExtension(Path), pattern: @"[\d-]", replacement: "", options: RegexOptions.Multiline)
                       .TrimStart();
            }

            //Flacs seem to stay for some reason, manually remove.
            Name = Name.Replace(".flac", "");
            //Remove the brackets left over on duplicate files in Windows.
            Name = Name.Replace("()", "");
        }
        public async Task <ContentResult> Upload()
        {
            string     url    = "http://webapplication5020160822045658.azurewebsites.net/api/Account/upload3";
            HttpClient client = new HttpClient();
            string     token  = Request.Cookies["access_token"].Value;

            client.DefaultRequestHeaders.Add("access_token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjU4Zjg1ZjRjLTY4ZTAtNDQ2NC04ZjhlLWQyNTU5NTk0NDg0NyIsImVtYWlsIjoiZmpqIn0.5y4MRuONaoK1QsJ_BEzoiOG01bqKsW7__kaLs2_3cU4");
            var         file        = Request.Files["file"];
            var         stream      = file.InputStream;
            HttpContent fileContent = new StreamContent(stream);

            TagLib.File myFile = TagLib.File.Create(new HttpPostedFileAbstraction(file));
            MultipartFormDataContent mulContent = new MultipartFormDataContent("----ferfefjeofjfjejf");

            fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
            mulContent.Add(fileContent, "file", file.FileName);
            int duration = (myFile.Properties.Duration.Minutes * 60 + myFile.Properties.Duration.Minutes) * 1000;

            duration += myFile.Properties.Duration.Milliseconds;
            mulContent.Add(new StringContent(duration.ToString()), "song_duration");
            mulContent.Add(new StringContent(myFile.Tag.Title), "song_name");
            mulContent.Add(new StringContent(myFile.Tag.Performers.FirstOrDefault()), "author");
            HttpResponseMessage response;

            response = await client.PostAsync(new Uri(url), mulContent);

            // response.EnsureSuccessStatusCode();
            string result = await response.Content.ReadAsStringAsync();

            return(Content(result));
        }
Пример #8
0
        // GET: Upload
        public ActionResult Upload()
        {
            IndexViewModel invm        = new IndexViewModel();
            List <ivm>     ivm         = new List <ivm>();
            DateTime       from_date   = DateTime.Now.AddDays(-1);
            DateTime       to_date     = DateTime.Now;
            List <String>  todaysFiles = new List <String>();

            foreach (String file in Directory.GetDirectories(@"\\51-DBA\radio\Music\", "*.*", SearchOption.AllDirectories))
            {
                DirectoryInfo di = new DirectoryInfo(file);
                if (di.LastWriteTime >= from_date)
                {
                    todaysFiles.Add(file);
                }
            }

            foreach (var item in todaysFiles)
            {
                string[] files = Directory.GetFiles(@"\\" + item, "*.*", SearchOption.AllDirectories).ToArray();
                foreach (var song in files)
                {
                    TrackList index = new TrackList();
                    if (song.Contains(".mp3") || song.Contains(".flac") || song.Contains(".m4a") || song.Contains(".m4p") || song.Contains(".wma") || song.Contains(".aiff") || song.Contains(".wav") || song.Contains(".alac") ||
                        song.Contains(".ogg")) //|| item.Contains(".png") || item.Contains(".jpg"))
                    {
                        TagLib.File file = TagLib.File.Create(song);
                        index.Location = "/music/" + file.Name.Substring(23);
                        var checkentries = db.TrackLists.FirstOrDefault(x => x.Location == index.Location);
                        if (checkentries == null)
                        {
                            index.Title       = file.Tag.Title;
                            index.Album       = file.Tag.Album;
                            index.TrackNumber = checked ((int?)file.Tag.Track);
                            index.Artist      = file.Tag.FirstPerformer;
                            index.Duration    = file.Properties.Duration.ToString();
                            index.Genre       = file.Tag.FirstGenre;
                            index.TimeAdded   = DateTime.Now;
                            db.TrackLists.Add(index);
                            db.SaveChanges();
                        }
                    }
                }
            }

            var sidebar = db.PlaylistNames.Select(x => x.PlaylistName1).Distinct().ToList();

            foreach (var item in sidebar)
            {
                playlist pl = new playlist();
                pl.Playlist = item;

                invm.PlayList.Add(pl);
            }

            invm.PlayList  = invm.PlayList.ToList();
            invm.indexview = invm.indexview.ToList();
            return(RedirectToAction("Index", "Home"));
        }
Пример #9
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);
            }
        }
        public static BitmapSource GetPicture(string path)
        {
            TL.File      media = TL.File.Create(path);
            BitmapSource bs    = getPic(media.Tag);

            media.Dispose();
            return(bs);
        }
Пример #11
0
        static void LogWarnings(string filename, File file)
        {
            if (!file.PossiblyCorrupt)
                return;

            foreach (var reason in file.CorruptionReasons)
                Log.WarnFormat("{0} is possibly corrupt: {1}", filename, reason);
        }
Пример #12
0
 // Constructor
 public Metadata(string filename)
 {
     file = TagLib.File.Create(filename);
     if (file == null || file.Tag == null || file.Properties.MediaTypes != TagLib.MediaTypes.Audio)
     {
         throw new System.Exception(System.String.Format(string_error_load, filename));
     }
 }
Пример #13
0
 private void TrySetId3Tag()
 {
     using (var mp3File = File.Create(filePath))
     {
         SetTags(mp3File);
         mp3File.Save();
     }
 }
        public void CheckXmp(File file, int i)
        {
            var tag = file.GetTag(TagTypes.XMP) as XmpTag;

            Assert.IsNotNull(tag, $"XMP Tag not contained: index {i}");

            Assert.AreEqual("test description", tag.Comment);
        }
Пример #15
0
 public void RemoveTags()
 {
     using (var mp3File = File.Create(filePath))
     {
         mp3File.RemoveTags(TagTypes.AllTags);
         mp3File.Save();
     }
 }
Пример #16
0
 private void RemoveAllTags(string path)
 {
     using (var tagLibFile = TagLibFile.Create(path))
     {
         tagLibFile.RemoveTags(TagTypes.AllTags);
         tagLibFile.Save();
     }
 }
Пример #17
0
 public static void SetInterpret(this TagLib.File item, string newInterpret)
 {
     if (newInterpret != null)
     {
         item.Tag.Performers = new string[] { newInterpret }
     }
     ;
 }
Пример #18
0
 public static void SetGenre(this TagLib.File item, string newGenre)
 {
     if (newGenre != null)
     {
         item.Tag.Genres = new string[] { newGenre }
     }
     ;
 }
Пример #19
0
        private string MediaMetadataHandlerReader()
        {
            TagLib.File file = TagLib.File.Create(FilePath);

            Metadata = file.Tag.Copyright.ToString();

            return(Metadata);
        }
Пример #20
0
        private void FillInTheTag(TagLib.File tagFile)
        {
            var tag = tagFile.Tag;

            Creator  = tag.FirstPerformer;
            Title    = tag.Title;
            Duration = tagFile.Properties.Duration.Milliseconds;
        }
Пример #21
0
 public FileEntryClass(string file)
 {
     TagLib.File audiofile = TagLib.File.Create(file);
     Tag      = audiofile.Tag;
     filename = Path.GetFileName(file);
     filepath = file;
     duration = audiofile.Properties.Duration;
 }
Пример #22
0
 private static string GetTitle(TagLib.File tagFile)
 {
     if (!string.IsNullOrEmpty(tagFile.Tag.Title))
     {
         return(tagFile.Tag.Title);
     }
     return(tagFile.Name);
 }
        public void CheckJpegComment(File file, int i)
        {
            var tag = file.GetTag(TagTypes.JpegComment) as JpegCommentTag;

            Assert.IsNotNull(tag, $"JpegTag Tag not contained: index {i}");

            Assert.AreEqual("Created with GIMP", tag.Comment, $"index {i}");
        }
Пример #24
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);
            }
        }
Пример #25
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,
         };
     }));
 }
Пример #26
0
        private static void ResizeWithGraphicsMagick(ResizeOptions options, File originalTags)
        {
            var    newSize = ComputeNewImageSize(options, originalTags);
            string exePath;

            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                var pathCodeBase = Assembly.GetExecutingAssembly().CodeBase.Substring(8);                       // strip leading "file:///"
                Console.WriteLine("DEBUG: pathCodeBase={0}", pathCodeBase);
                exePath = Path.Combine(Path.GetDirectoryName(pathCodeBase), "gm", "gm.exe");
            }
            else
            {
                exePath = "/usr/bin/gm";
            }
            Console.WriteLine("DEBUG: exePath={0}", exePath);
            string arguments;

            if (originalTags.Properties != null && originalTags.Properties.Description == "PNG File")
            {
                // Ensure opaque white background and no transparency as well as adjusting the size of the image
                arguments =
                    $"convert \"{options.FileName}\" -background white -extent 0x0 +matte -scale {newSize.Width}x{newSize.Height} \"{options.Output}\"";
            }
            else
            {
                arguments =
                    $"convert \"{options.FileName}\" -scale {newSize.Width}x{newSize.Height} \"{options.Output}\"";
            }
            Console.WriteLine("DEBUG: arguments={0}", arguments);
            var proc = new Process
            {
                StartInfo =
                {
                    FileName               = exePath,
                    Arguments              = arguments,
                    UseShellExecute        = false,            // enables CreateNoWindow
                    CreateNoWindow         = true,             // don't need a DOS box
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                }
            };

            proc.Start();
            proc.WaitForExit();
            var standardOutput = proc.StandardOutput.ReadToEnd();
            var standardError  = proc.StandardError.ReadToEnd();

            Console.WriteLine("GraphicsMagic exit code = {0}", proc.ExitCode);
            Console.WriteLine("GraphicsMagic stderr");
            Console.WriteLine("--------------------");
            Console.WriteLine(standardError);
            Console.WriteLine("================================");
            Console.WriteLine("GraphicsMagic stdout");
            Console.WriteLine("--------------------");
            Console.WriteLine(standardOutput);
            Console.WriteLine("================================");
        }
Пример #27
0
        public static void Write(string path, Track track)
        {
            AlbumArtFile artworkFile = null;

            if (AlbumArtCache.Instance.HasItem(track.Album.CoverUri.ToString()))
            {
                artworkFile = AlbumArtCache.Instance.Get(track.Album.CoverUri.ToString());
            }

            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;
                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);
            }
        }
Пример #28
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);
        }
Пример #29
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();
     }
 }
Пример #30
0
        public MusicFile(string path)
        {
            string extension = System.IO.Path.GetExtension(path);
            if (extension == null || !_musicExtensions.Contains(extension.ToLower()))
                throw new UnsupportedFormatException();

            _file = File.Create(path);
            Path = path;
        }
Пример #31
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);
        }
        public void Init()
        {
            files = new File[count];

            for (int i = 0; i < count; i++)
            {
                files[i] = File.Create(GetSampleFilename(i));
            }
        }
 public void SetValues(string fileInfo)
 {
     if (System.IO.File.Exists(fileInfo))
     {
         _isMulti = false;
         _file    = File.Create(fileInfo);
         SetValues();
     }
 }
Пример #34
0
 public get_details(string path)
 {
     try
     {
         if (path != "")
             file = TagLib.File.Create(path);
     }
     catch { }
 }
Пример #35
0
 private void setImage(ref TagLib.File tgFile)
 {
     if (tgFile.Tag.Pictures.Length > 0)
     {
         image = Path.Combine(Resources.imagesDirectory, name);
         var pixmap = Image.FromStream(new MemoryStream(tgFile.Tag.Pictures[0].Data.Data));
         pixmap.Save(image, ImageFormat.Png);
     }
 }
Пример #36
0
        private async Task ReadTags(TagLib.File tagFile)
        {
            Tag tags = tagFile.GetTag(TagTypes.Id3v2);

            Title  = tags.Title;
            Artsit = tags.Performers.FirstOrDefault();
            Album  = tags.Album;
            Cover  = await tags.Pictures[0].ToBitmapImage(new Size(120, 120));
        }
Пример #37
0
 public Picture(File.IFileAbstraction abstraction)
 {
     if (abstraction == null)
     {
         throw new ArgumentNullException("abstraction");
     }
     this.Data = ByteVector.FromFile(abstraction);
     this.FillInMimeFromData();
     this.Description = abstraction.Name;
 }
Пример #38
0
        public static void Clean()
        {
            try
            {
                ChannelProps.Clear();
                fileTag = null;
            }
            catch (Exception)
            {

            }
        }
Пример #39
0
 public FileParser(TagLib.File file)
 {
     if (file == null)
     {
         throw new ArgumentNullException("file");
     }
     this.file = file;
     this.first_header = new BoxHeader(file, 0L);
     if (this.first_header.BoxType != "ftyp")
     {
         throw new CorruptFileException("File does not start with 'ftyp' box.");
     }
 }
Пример #40
0
        private TagLib.File m_TagLibFile; // TagLibSharp file object

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="Filename">
        /// A <see cref="System.String"/> containing the path to the Ogg Vorbis file this instance represents
        /// </param>
        public OggFile(string Filename)
        {
            // Check that the file exists
            if (!(System.IO.File.Exists(Filename))) { throw new OggFileReadException("File not found", Filename); }
            // Load the relevant objects
            m_Filename = Filename;
            try
            {
                m_CSVorbisFile = new VorbisFile(m_Filename);
            }
            catch (Exception ex)
            {
                throw new OggFileReadException("Unable to open file for data reading\n" + ex.Message, Filename);
            }
            try
            {
                m_TagLibFile = TagLib.File.Create(m_Filename);
            }
            catch (TagLib.UnsupportedFormatException ex)
            {
                throw new OggFileReadException("Unsupported format (not an ogg?)\n" + ex.Message, Filename);
            }
            catch (TagLib.CorruptFileException ex)
            {
                throw new OggFileCorruptException(ex.Message, Filename, "Tags");
            }

            // Populate some other info shizzle and do a little bit of sanity checking
            m_Streams = m_CSVorbisFile.streams();
            if (m_Streams<=0) { throw new OggFileReadException("File doesn't contain any logical bitstreams", Filename); }
            // Assuming <0 is for whole file and >=0 is for specific logical bitstreams
            m_Bitrate = m_CSVorbisFile.bitrate(-1);
            m_LengthTime = (int)m_CSVorbisFile.time_total(-1);
            // Figure out the ALFormat of the stream
            m_Info = m_CSVorbisFile.getInfo();	// Get the info of the first stream, assuming all streams are the same? Dunno if this is safe tbh
            if (m_Info[0] == null) { throw new OggFileReadException("Unable to determine Format{FileInfo.Channels} for first bitstream", Filename); }
            if (m_TagLibFile.Properties.AudioBitrate==16) {
                m_Format = (m_Info[0].channels)==1 ? ALFormat.Mono16 : ALFormat.Stereo16; // This looks like a fudge, but I've seen it a couple of times (what about the other formats I wonder?)
            }
            else
            {
                m_Format = (m_Info[0].channels)==1 ? ALFormat.Mono8 : ALFormat.Stereo8;
            }

            // A grab our first instance of the file so we're ready to play
            m_CSVorbisFileInstance = m_CSVorbisFile.makeInstance();
        }
Пример #41
0
        public void initialize(Song song)
        {
            if (song.usingTagLib) {

                metaFile = song.tagFile;

                this.Text = song.ToString();
                textBox_Title.Text = metaFile.Tag.Title;
                textBox_Artist.Text = metaFile.Tag.FirstPerformer;
                if (metaFile.Tag.Genres.Length > 0)
                    textBox_Genre.Text = metaFile.Tag.Genres[0];
                foreach (String genre in metaFile.Tag.Genres)
                    textBox_Genre.Text += "; " + genre;
                textBox_Album.Text = metaFile.Tag.Album;
                textBox_Year.Text = "" + metaFile.Tag.Year;
                textBox_Comments.Text = metaFile.Tag.Comment;

                button_SaveChanges.Enabled = true;

            } else if (song.usingId3Tag && !song.fileCorrupted) {

                id3Tag = song.id3Tag;

                this.Text = song.ToString();
                textBox_Title.Text = id3Tag.Title.Value;
                textBox_Artist.Text = id3Tag.Artists.Value;
                textBox_Genre.Text = id3Tag.Genre.Value;
                textBox_Album.Text = id3Tag.Album.Value;
                textBox_Year.Text = "" + id3Tag.Year.Value;
                foreach (CommentFrame comment in id3Tag.Comments)
                    textBox_Comments.Text += comment.Comment + "\n";

                button_SaveChanges.Enabled = true;

            } else {
                //initialized = false;

                textBox_Title.Text = null;
                textBox_Artist.Text = null;
                textBox_Genre.Text = null;
                textBox_Album.Text = null;
                textBox_Year.Text = null;
                textBox_Comments.Text = null;

                button_SaveChanges.Enabled = false;
            }
        }
Пример #42
0
        void PopulateFromId3v2(File file, Tag tag)
        {
            if (!file.TagTypes.HasFlag(TagTypes.Id3v2))
                return;

            var id3v2 = (TagLib.Id3v2.Tag)file.GetTag(TagTypes.Id3v2);

            tag.ImageData = GetImageData(id3v2);

            // ID3v2 Tags Reference: http://id3.org/id3v2.4.0-frames
            tag.InitialKey = GetTextFrame(id3v2, "TKEY") ?? GetUserTextFrame(id3v2, "Initial key");
            tag.Artist = JoinPerformers(id3v2.Performers);
            tag.Title = id3v2.Title;
            tag.Year = ToStringOrDefault(id3v2.Year);
            tag.Genre = id3v2.JoinedGenres;
            tag.Publisher = GetTextFrame(id3v2, "TPUB") ?? GetUserTextFrame(id3v2, "Publisher");
            tag.Bpm = ToStringOrDefault(id3v2.BeatsPerMinute) ?? GetUserTextFrame(id3v2, "BPM (beats per minute)");
        }
Пример #43
0
        public void ReadTags(string filePath)
        {
            ChannelProps.Clear();
            fileTag = TagLib.File.Create(filePath);

            ChannelProps.Add(((double)fileTag.Properties.AudioSampleRate/1000).ToString());
            ChannelProps.Add(fileTag.Properties.AudioBitrate.ToString());
            ChannelProps.Add(fileTag.Properties.AudioChannels.ToString());
            ChannelProps.Add(String.Format("{0:D2}:{1:D2}:{2:D2}", (int)fileTag.Properties.Duration.TotalHours,
                fileTag.Properties.Duration.Minutes, fileTag.Properties.Duration.Seconds));

            TagLib.Id3v1.Tag id3v1 = fileTag.GetTag(TagLib.TagTypes.Id3v1) as TagLib.Id3v1.Tag;
            TagLib.Id3v2.Tag id3v2 = fileTag.GetTag(TagLib.TagTypes.Id3v2) as TagLib.Id3v2.Tag;
            TagLib.Mpeg4.AppleTag apple = fileTag.GetTag(TagLib.TagTypes.Apple) as TagLib.Mpeg4.AppleTag;
            TagLib.Ape.Tag ape = fileTag.GetTag(TagLib.TagTypes.Ape) as TagLib.Ape.Tag;
            TagLib.Asf.Tag asf = fileTag.GetTag(TagLib.TagTypes.Asf) as TagLib.Asf.Tag;
            TagLib.Ogg.XiphComment ogg = fileTag.GetTag(TagLib.TagTypes.Xiph) as TagLib.Ogg.XiphComment;
        }
Пример #44
0
 public Tag(File file, long position)
 {
     if (file == null)
     {
         throw new ArgumentNullException("file");
     }
     file.Mode = File.AccessMode.Read;
     if ((position < 0L) || (position > (file.Length - 0x80L)))
     {
         throw new ArgumentOutOfRangeException("position");
     }
     file.Seek(position);
     ByteVector data = file.ReadBlock(0x80);
     if (!data.StartsWith(FileIdentifier))
     {
         throw new CorruptFileException("ID3v1 data does not start with identifier.");
     }
     this.Parse(data);
 }
Пример #45
0
        private static bool fixup_album_artist(File tagfile)
        {
            bool perform_save = false;
            string [] album_artists = tagfile.Tag.AlbumArtists;
            string album_artists_merged = string.Join(",", album_artists);
            album_artists_merged = normalizename(album_artists_merged);

            string[] contributing_artists = tagfile.Tag.Performers;
            string contributing_artists_merged = string.Join(",", contributing_artists);
            contributing_artists_merged = normalizename(contributing_artists_merged);

            string[] composers = tagfile.Tag.Composers;
            string composers_merged = string.Join(",", composers);
            composers_merged = normalizename(composers_merged);

            if (album_artists_merged=="")
            {
                string [] new_album_artists = null;
                if (contributing_artists_merged!="")
                {
                    new_album_artists = tagfile.Tag.Performers;
                }
                else if (composers_merged != "")
                {
                    new_album_artists = tagfile.Tag.Composers;
                }

                if (new_album_artists!=null)
                {
                    Console.WriteLine("    album artist -> \"{0}\"", contributing_artists_merged);
                    tagfile.Tag.AlbumArtists = tagfile.Tag.Performers;
                    perform_save = true;
                }
            }
            return perform_save;
        }
Пример #46
0
 public EndTag(TagLib.File file)
 {
     this.file = file;
 }
Пример #47
0
        /// <summary>
        ///   Based on the Options set, use the correct version for ID3
        ///   Eventually remove V1 or V2 tags, if set in the options
        /// </summary>
        /// <param name = "File"></param>
        public static File FormatID3Tag(File file)
        {
            if (file.MimeType == "taglib/mp3")
              {
            Tag id3v2_tag = file.GetTag(TagTypes.Id3v2) as Tag;
            if (id3v2_tag != null && Options.MainSettings.ID3V2Version > 0)
              id3v2_tag.Version = (byte)Options.MainSettings.ID3V2Version;

            // Remove V1 Tags, if checked or "Save V2 only checked"
            if (Options.MainSettings.RemoveID3V1 || Options.MainSettings.ID3Version == 2)
              file.RemoveTags(TagTypes.Id3v1);

            // Remove V2 Tags, if checked or "Save V1 only checked"
            if (Options.MainSettings.RemoveID3V2 || Options.MainSettings.ID3Version == 1)
              file.RemoveTags(TagTypes.Id3v2);

            // Remove V2 Tags, if Ape checked
            if (Options.MainSettings.ID3V2Version == 0)
            {
              file.RemoveTags(TagTypes.Id3v2);
            }
            else
            {
              file.RemoveTags(TagTypes.Ape);
            }
              }
              return file;
        }
Пример #48
0
 public void Init()
 {
     file = File.Create (sample24unsynchronization_file);
 }
Пример #49
0
		public static Picture CreateFromFile (File.IFileAbstraction abstraction)
		{
			return new Picture (abstraction);
		}
 public ZuneWMATagContainer(File file)
     : base(file)
 {
     _file = file;
     _tag = (Tag)file.GetTag(TagTypes.Asf);
 }
Пример #51
0
        /// <summary>
        /// Reset the OggFile (reload from disk).
        /// Useful if tags have changed externally, or to reset the internal position pointer to replay the file from the beginning
        /// SeekToTime(0) is the preferred method of moving the internal pointer to the beginning however however
        /// </summary>		
        public void ResetFile()
        {
            try
            {
                // Grab a fresh instance of the file
                m_CSVorbisFileInstance = m_CSVorbisFile.makeInstance();

                m_TagLibFile = null;
                m_TagLibFile = TagLib.File.Create(m_Filename);
            }
            catch (Exception ex)
            {
                throw new Exception("Unable to reload OggFile [" + m_Filename + "]", ex);
            }
        }
Пример #52
0
 public void Dispose()
 {
     m_TagLibFile.Dispose();
     m_TagLibFile = null;
     m_CSVorbisFile.Dispose();
     m_CSVorbisFile = null;
 }
        /// <summary>
        ///   Adds the song to the database
        /// </summary>
        /// <param name = "file"></param>
        private void AddSong(File file)
        {
            string artist = "";
              string[] artists = file.Tag.Performers;
              if (artists.Length > 0)
              {
            artist = FormatMultipleEntry(string.Join(";", artists));
              }

              string albumartist = "";
              string[] albumartists = file.Tag.AlbumArtists;
              if (albumartists.Length > 0)
              {
            albumartist = FormatMultipleEntry(string.Join(";", albumartists));
              }

              string genre = "";
              string[] genres = file.Tag.Genres;
              if (genres.Length > 0)
              {
            genre = FormatMultipleEntry(string.Join(";", genres));
              }

              string title = file.Tag.Title == null ? "" : file.Tag.Title.Trim();

              string sql =
            String.Format(
              @"insert into tracks (strPath, strArtist, strAlbumArtist, strAlbum, strGenre, strTitle, iTrack, iNumTracks, iYear, iRating, iDisc, iNumDisc, strLyrics)
                          values ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', {6}, {7}, {8}, {9}, {10}, {11}, '{12}' )",
              Util.RemoveInvalidChars(file.Name), Util.RemoveInvalidChars(artist), Util.RemoveInvalidChars(albumartist),
              Util.RemoveInvalidChars(file.Tag.Album), Util.RemoveInvalidChars(genre), Util.RemoveInvalidChars(title),
              file.Tag.Track, file.Tag.TrackCount, file.Tag.Year, 0,
              file.Tag.Disc, file.Tag.DiscCount, "");

              ExecuteDirectSQL(sql);

              AddArtist(Util.RemoveInvalidChars(artist));
              AddAlbumArtist(Util.RemoveInvalidChars(albumartist));
              AddGenre(Util.RemoveInvalidChars(genre));
        }
 public void SetValues(string fileInfo)
 {
     if (System.IO.File.Exists(fileInfo))
     {
         _isMulti = false;
         _file = File.Create(fileInfo);
         SetValues();
     }
 }
 private File SaveToFile(File file, Tag tag)
 {
     if (Id3Handler.Save(file, _file))
     {
         if (checkBoxRename.Checked)
         {
             var filename =
                 Helper.RenameFile(new BaseInfoTag(tag.JoinedPerformers, tag.FirstPerformer, tag.Album,
                     tag.Title,
                     _file.Name));
             if (filename != Actiontype.Exception.ToString() &&
                 filename != Actiontype.Already.ToString())
                 return File.Create(filename);
         }
         return file;
     }
     return null;
 }
Пример #56
0
 public TestFile(File.IFileAbstraction abstraction)
     : base(abstraction)
 {
 }
Пример #57
0
 public void Init()
 {
     file = File.Create("samples/sample_both.mp3");
 }
Пример #58
0
        //private SongInfo GetLyricsAndSongInfoByVK(File audioFile, string fileName)
        //{
        //    var authorize = new VkAuthorization();
        //    var api = authorize.Authorize();
        //    var songLyricsAndInfoGetter = new IVkAudioService(api);
        //    var titleEncoded = audioFile.Tag.Title.ToUtf8();
        //    var artistEncoded = audioFile.Tag.Artists.ConvertStringArrayToString().ToUtf8();
        //    if (string.IsNullOrEmpty(titleEncoded) == false)
        //    {
        //        var info = songLyricsAndInfoGetter.GetSongInfo(artistEncoded + " " + titleEncoded);
        //        if (info != null)
        //        {
        //            return info;
        //        }
        //    }
        //    if (string.IsNullOrEmpty(fileName) == false)
        //    {
        //        var info = songLyricsAndInfoGetter.GetSongInfo(fileName);
        //        if (info != null)
        //        {
        //            return info;
        //        }
        //    }
        //    return null;
        //}
        private string SongAlbumPicturePathToDb(File audioFile, string saveSongCoverPath, string songId,
            string songAlbumPicturePathToDb, string titleVk, string artistVk, string filename, ref string content)
        {
            if (audioFile.Tag.Pictures.Any())
            {
                SongPictureGetter.GetAndSavePictureByTag(audioFile.Tag, saveSongCoverPath, songId);
            }
            else
            {
                var trackInfo = SongPictureGetter.GetPictureByWebService(audioFile.Tag, titleVk, artistVk, filename);

                if (trackInfo != null)
                {
                    songAlbumPicturePathToDb = trackInfo.PicturePath;
                    content = trackInfo.Content;
                }
            }
            return songAlbumPicturePathToDb;
        }
Пример #59
0
 public void Init()
 {
     file = File.Create(sample_file);
 }
Пример #60
-1
 private static bool fixup_title(string filename, File tagfile)
 {
     bool perform_save = false;
     string title = tagfile.Tag.Title;
     if (novalue(title))
     {
         string newtitle = System.IO.Path.GetFileNameWithoutExtension(filename);
         tagfile.Tag.Title = newtitle;
         perform_save = true;
         Console.WriteLine("    title -> \"{0}\"", newtitle);
     }
     return perform_save;
 }