public void bibli_music() { string path = (@"C:\Users\" + Environment.UserName + @"\Music"); FilePaths = Directory.GetFiles(path, "*.mp3", SearchOption.AllDirectories); FilePaths2 = Directory.GetFiles(path, "*.flac", SearchOption.AllDirectories); FilePaths3 = Directory.GetFiles(path, "*.wav", SearchOption.AllDirectories); FilePaths4 = Directory.GetFiles(path, "*.ogg", SearchOption.AllDirectories); string[] z; z = new string[FilePaths.Count() + FilePaths2.Count()]; FilePaths.CopyTo(z, 0); FilePaths2.CopyTo(z, FilePaths.Count()); FilePaths = z; z = new string[FilePaths.Count() + FilePaths3.Count()]; FilePaths.CopyTo(z, 0); FilePaths3.CopyTo(z, FilePaths.Count()); FilePaths = z; z = new string[FilePaths.Count() + FilePaths4.Count()]; FilePaths.CopyTo(z, 0); FilePaths4.CopyTo(z, FilePaths.Count()); FilePaths = z; TagLib.File[] f; f = new TagLib.File[FilePaths.Count()]; for (int i = 0; i < FilePaths.Count(); i++) { f[i] = TagLib.File.Create(FilePaths[i]); } var gridview = new GridView(); this.bibView.View = gridview; gridview.Columns.Add(new GridViewColumn { Header = "Titre", DisplayMemberBinding = new Binding("Title") }); gridview.Columns.Add(new GridViewColumn { Header = "Artiste", DisplayMemberBinding = new Binding("Artiste") }); gridview.Columns.Add(new GridViewColumn { Header = "Album", DisplayMemberBinding = new Binding("Album") }); for (int i = 0; i < FilePaths.Count(); i++) { bibView.Items.Add(new Song() { Title = f[i].Tag.Title, Artiste = f[i].Tag.FirstAlbumArtist, Album = f[i].Tag.Album }); //listView.Items.Add(System.IO.Path.GetFileNameWithoutExtension(((MainWindow)this.Owner).med.chemin[i])); } // }
public Song(TagLib.File file, string path) { tagFile = file; Path = path; int temp = path.LastIndexOf('\\'); FileName = path.Substring(temp+1, path.Length - temp - 1); }
public Media Create(String path) { created = false; int point = path.LastIndexOf('.'); if (point != -1) { String ext = path.Substring(point + 1); foreach (KeyValuePair<MediaType, Tuple<List<String>, object>> dic in AuthorizedExtension) { if (dic.Value.Item1.Contains(ext.ToLower())) { media = new Media(); media.Type = dic.Key; created = true; Debug.Add("Media " + path + " created !"); } } } if (!created) throw new InvalidMediaException(path + " is not a valid media"); try { tag = null; tag = TagLib.File.Create(path); } catch (Exception e) { Debug.Add(e.ToString() + "\n"); } media.AddTags(tag, path); media.CompleteData(AuthorizedExtension[media.Type].Item2); Debug.Add("Media datas completed !"); return media; }
public Mp3File(string path) { FilePath = path; _tagFile = TagLib.File.Create(FilePath); Title = _tagFile.Tag.Title.FixCodepage(); Artist = _tagFile.Tag.FirstPerformer.FixCodepage(); Album = _tagFile.Tag.Album.FixCodepage(); }
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); }
//#############################PUBLICZNE METODY KLASY############################################ /// <summary>Tworzy obiekt Utwór odpowiedający danemu plikowi muzycznemu.</summary> /// <param name="path">Ścieżka pliku.</param> /// <exception cref="FileNotFoundException">Rzucane jeśli podany plik nie istnieje</exception> public Utwor(String path) { if(!File.Exists(path)) throw new FileNotFoundException(path); Sciezka = SciezkaZrodlowa = path; Nazwa = Path.GetFileNameWithoutExtension(path); dane = new DaneUtworu(); tagi = TagLib.File.Create(path); stareTagi = TagLib.File.Create(path); pobierzTagi(); }
public TagLibMediaFile(String pathToFile) { try { file = TagLib.File.Create(pathToFile); } catch (Exception e) { Logging.Error(typeof(TagLibMediaFile), e); } }
public Track(string pPath) { if (System.IO.File.Exists(pPath)) { Path = pPath; File = TagLib.File.Create(Path); } else { throw new System.IO.FileNotFoundException("Diese Datei exsitiert nicht!", pPath); } }
public Mp3File(string path) { _content = File.Create(path); FullName = path; Tags = new Mp3Tags { Album = _content.Tag.Album, Title = _content.Tag.Title, Artist = _content.Tag.FirstPerformer, Genre = _content.Tag.FirstGenre, Track = _content.Tag.Track }; }
/** * Opens a TagLib handle for the specified file * */ public LibraryTagLib(Uri file) { if (file.Scheme != Uri.UriSchemeFile) throw new ArgumentException("Unsupported Uri Schema!"); try { media = TagLib.File.Create(file.LocalPath); } catch (IOException ex) { throw ex; } }
public static MusicInfo CreateMusicInfo(File f, string path) { var mi = new MusicInfo { Album = f.Tag.Album, Artist = f.Tag.FirstAlbumArtist?? f.Tag.FirstPerformer, AudioRate = f.Properties.AudioBitrate, Genres = f.Tag.JoinedGenres, Title = f.Tag.Title ?? Path.GetFileNameWithoutExtension(path), Track = (int) f.Tag.Track, Year = (int) f.Tag.Year, Path = path }; return mi; }
public Mp3Track(string filepath, File tag) { if (filepath == null) throw new ArgumentNullException("filepath", "filepath cannot equal null"); try { File = new FileInfo(filepath); } catch (Exception e) { throw new ArgumentException("An error occured from the passed filepath", "filepath", e); } _filepath = filepath; TrackTitle = string.IsNullOrEmpty(tag.Tag.Title) ? File.Name : tag.Tag.Title.Trim(); AlbumTitle = string.IsNullOrEmpty(tag.Tag.Album) ? "Unknown Album" : tag.Tag.Album.Trim(); TrackNumber = (int) tag.Tag.Track; ArtistName = !tag.Tag.Performers.Any() ? "Unknown Artist" : string.Join(" & ", tag.Tag.Performers); Year = (int) tag.Tag.Year; Genre = tag.Tag.JoinedGenres; Bitrate = tag.Properties.AudioBitrate; Duration = tag.Properties.Duration; }
//Zapisuje dane z obiektu dane do obiektu tagi //Uaktualnia dane w obiekcie stareTagi public override void zapiszTagi() { tagi.Tag.Album = dane.album; tagi.Tag.BeatsPerMinute = dane.bityNaMinute; tagi.Tag.Conductor = dane.dyrygent; tagi.Tag.Genres = dane.gatunek; tagi.Tag.Comment = dane.komentarz; tagi.Tag.DiscCount = dane.liczbaCd; tagi.Tag.TrackCount = dane.liczbaPiosenek; tagi.Tag.Track = dane.numer; tagi.Tag.Disc = dane.numerCd; tagi.Tag.Copyright = dane.prawaAutorskie; tagi.Tag.MusicIpId = dane.puid; tagi.Tag.Year = dane.rok; tagi.Tag.Lyrics = dane.tekstPiosenki; tagi.Tag.Title = dane.tytul; tagi.Tag.Performers = dane.wykonawca; tagi.Tag.AlbumArtists = dane.wykonawcaAlbumu; tagi.Tag.Pictures = dane.zdjecia; tagi.Save(); stareTagi = tagi; logi += "Zapisano nowe tagi." + Environment.NewLine; }
public void TreeScan(string sDir) { foreach (string f in Directory.GetFiles(sDir)) { using (var session = driver.Session()) { soundFileManager = new SoundFileManager(session); try { SoundFile sf = null; TagLib.File file = null; Console.WriteLine("Processing " + f); file = TagLib.File.Create(f); double length = file.Properties.Duration.TotalSeconds; sf = new SoundFile() { Title = file.Tag.Title, Filename = f, Directory = sDir, Comment = file.Tag.Comment, Rating = 0, Filesize = "", Year = (int)file.Tag.Year, Genre = file.Tag.JoinedGenres, Lyrics = file.Tag.Lyrics, Album = file.Tag.Album, Artist = file.Tag.JoinedAlbumArtists, Duration = (int)length, Mime = file.MimeType }; if (file.Tag.Pictures.Any()) { var artwork = file.Tag.Pictures.First(); using (MemoryStream m = new MemoryStream()) { byte[] imageBytes = artwork.Data.Data; // Convert byte[] to Base64 String string base64String = Convert.ToBase64String(imageBytes); sf.Artwork = base64String; imageBytes = null; } } soundFileManager.Add(sf); file = null; sf = null; } catch (Exception uex) { continue; //todo - log and give report } } } foreach (string d in Directory.GetDirectories(sDir)) { TreeScan(d); } }
/// <summary> /// Constructs and initializes a new instance of <see /// cref="BoxHeader" /> by reading it from a specified seek /// position in a specified file. /// </summary> /// <param name="file"> /// A <see cref="TagLib.File" /> object to read the new /// instance from. /// </param> /// <param name="position"> /// A <see cref="long" /> value specifiying the seek position /// in <paramref name="file" /> at which to start reading. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="file" /> is <see langword="null" />. /// </exception> /// <exception cref="CorruptFileException"> /// There isn't enough data in the file to read the complete /// header. /// </exception> public BoxHeader(TagLib.File file, long position) { if (file == null) { throw new ArgumentNullException(nameof(file)); } Box = null; from_disk = true; this.position = position; file.Seek(position); ByteVector data = file.ReadBlock(32); int offset = 0; if (data.Count < 8 + offset) { throw new CorruptFileException("Not enough data in box header."); } header_size = 8; box_size = data.Mid(offset, 4).ToUInt(); BoxType = data.Mid(offset + 4, 4); // If the size is 1, that just tells us we have a // massive ULONG size waiting for us in the next 8 // bytes. if (box_size == 1) { if (data.Count < 8 + offset) { throw new CorruptFileException("Not enough data in box header."); } header_size += 8; offset += 8; box_size = data.Mid(offset, 8).ToULong(); } // UUID has a special header with 16 extra bytes. if (BoxType == Mpeg4.BoxType.Uuid) { if (data.Count < 16 + offset) { throw new CorruptFileException("Not enough data in box header."); } header_size += 16; ExtendedType = data.Mid(offset, 16); } else { ExtendedType = null; } if (box_size > (ulong)(file.Length - position)) { throw new CorruptFileException( $"Box header specified a size of {box_size} bytes but only {file.Length - position} bytes left in the file"); } }
//Przywraca do obiektu dane informacje z obiektu stareTagi public override void przywrocDomyslneTagi() { tagi = stareTagi; pobierzTagi(); logi += "Anulowano modyfikowanie tagów." + Environment.NewLine; }
/// <summary> /// 更名文本。 /// </summary> /// <param name="fileInfo"></param> /// <param name="file"></param> /// <returns></returns> public static string RenameText(FileInfo fileInfo, TagLib.File file) { //string filename = GetTimeName(fileInfo); return(GetTimeName(fileInfo)); }
public void SaveTags() { using (TagLib.File track = TagLib.File.Create(Path)) { if (this.Title != null) { track.Tag.Title = this.Title; } if (this.Artist != null) { if (track.Tag.Performers.Length == 0) { track.Tag.Performers = new string[1] { this.Artist } } ; else { track.Tag.Performers[0] = this.Artist; } if (this.Artist == "") { track.Tag.Performers = new string[0]; } } if (this.Album != null) { track.Tag.Album = this.Album; } if (this.Genre != null) { if (track.Tag.Genres.Length == 0) { track.Tag.Genres = new string[1] { this.Genre } } ; else { track.Tag.Genres[0] = this.Genre; } if (this.Genre == "") { track.Tag.Genres = new string[0]; } } if (this.TrackNumber > 0) { track.Tag.Track = (uint)this.TrackNumber; } if (this.DiscNumber > 0) { track.Tag.Disc = (uint)this.DiscNumber; } try { track.Save(); } catch { MessageBox.Show("Could not save tags: File being used by another process."); } } }
/// <summary> /// Creates a box by reading it from a file given its header /// and handler. /// </summary> /// <param name="file"> /// A <see cref="TagLib.File" /> object containing the file /// to read from. /// </param> /// <param name="header"> /// A <see cref="BoxHeader" /> object containing the header /// of the box to create. /// </param> /// <param name="handler"> /// A <see cref="IsoHandlerBox" /> object containing the /// handler that applies to the new box. /// </param> /// <returns> /// A newly created <see cref="Box" /> object. /// </returns> public static Box CreateBox(TagLib.File file, BoxHeader header, IsoHandlerBox handler) { return(CreateBox(file, header, BoxHeader.Empty, handler, -1)); }
private void ProcessTrack(IDBClient db, string file) { // open the file using taglib try { // work out the compression type from the extension var compression = Compression.Lossy; if (AudioConstants.SUPPORTED_LOSSLESS.Contains(Path.GetExtension(file))) { compression = Compression.Lossless; } File musicFile = File.Create(file); // check whether or not the tag information is valid if (null == musicFile.Tag.Album || null == musicFile.Tag.Title) { _log.Error("Invalid tag information for: " + file); } else { // retrieve the album artist first if (null == _albumArtist) { // find the artist that should be for this album _albumArtist = Database.RetrieveArtistByName(db, musicFile.Tag.AlbumArtists[0]); // check if we have an existing album artist if (null == _albumArtist) { // if not, create one _albumArtist = new Artist(musicFile.Tag.AlbumArtists[0]); } } // have an album to work with if (null == _theAlbum) { // we'll attempt to find an album to add it to _theAlbum = Database.RetrieveAlbumByName(db, musicFile.Tag.Album, compression); // if there isn't an existing album if (null == _theAlbum) { // create a new album _theAlbum = new Album(musicFile.Tag.Album, _albumArtist, musicFile.Tag.FirstGenre, (int)musicFile.Tag.Year, compression); } } else { // make sure we have the right album if (_theAlbum.Title != musicFile.Tag.Album) { // we'll attempt to find an album to add it to or create a new one _theAlbum = Database.RetrieveAlbumByName(db, musicFile.Tag.Album, compression) ?? new Album(musicFile.Tag.Album, _albumArtist, musicFile.Tag.FirstGenre, (int)musicFile.Tag.Year, compression); // if there isn't an existing album } } // initialise the output track Track theTrack; var trackArtists = new List <Artist>(); // special case for tracks that have more than one artist if (musicFile.Tag.Performers.Count() > 1) { foreach (var artist in musicFile.Tag.Performers) { // we'll try with the album artist first var performer = _albumArtist; if (artist != _albumArtist.Name) { performer = Database.RetrieveArtistByName(db, artist) ?? new Artist(artist); } trackArtists.Add(performer); } } else { // we'll try with the album artist first if (musicFile.Tag.FirstPerformer == _albumArtist.Name) { trackArtists.Add(_albumArtist); } else { var performer = Database.RetrieveArtistByName(db, musicFile.Tag.FirstPerformer) ?? new Artist(musicFile.Tag.FirstPerformer); trackArtists.Add(performer); } // check for a track in the local object instead of hitting the DB try { // TODO not sure if this will work with the multiple artists now _theAlbum.Tracks.First( x => (x.TrackNumber == (int)musicFile.Tag.Track && x.Title == musicFile.Tag.Title)); } catch (InvalidOperationException) {} } // update the running tally foreach (var artist in trackArtists) { int result = 0; if (_tally.ContainsKey(artist)) { result = _tally[artist]; } if (0 == result) { _tally.Add(artist, 1); } else { _tally[artist] = ++result; } } // create a new track theTrack = new Track((int)musicFile.Tag.Track, trackArtists, _theAlbum, musicFile.Properties.Duration, musicFile.Tag.Title, file); // add the new track to the album _theAlbum.AddTrack(theTrack); // update the reference in the DB Database.UpdateAddTrack(db, theTrack); } } catch (ArgumentOutOfRangeException e) { _log.Error("Taglib had problem reading: " + file, e); return; } catch (Db4oException e) { _log.Error("DB problem when processing track: " + file, e); } catch (IOException e) { _log.Error("File IO problem when processing track: " + file, e); } }
/// <summary> /// Creates a box by reading it from a file given its /// position in the file and handler. /// </summary> /// <param name="file"> /// A <see cref="TagLib.File" /> object containing the file /// to read from. /// </param> /// <param name="position"> /// A <see cref="long" /> value specifying at what seek /// position in <paramref name="file" /> to start reading. /// </param> /// <param name="handler"> /// A <see cref="IsoHandlerBox" /> object containing the /// handler that applies to the new box. /// </param> /// <returns> /// A newly created <see cref="Box" /> object. /// </returns> public static Box CreateBox(TagLib.File file, long position, IsoHandlerBox handler) { return(CreateBox(file, position, BoxHeader.Empty, handler, -1)); }
/// <summary> /// Creates a box by reading it from a file given its /// position in the file. /// </summary> /// <param name="file"> /// A <see cref="TagLib.File" /> object containing the file /// to read from. /// </param> /// <param name="position"> /// A <see cref="long" /> value specifying at what seek /// position in <paramref name="file" /> to start reading. /// </param> /// <returns> /// A newly created <see cref="Box" /> object. /// </returns> public static Box CreateBox(TagLib.File file, long position) { return(CreateBox(file, position, null)); }
public static void TrackInfoMerge(TrackInfo track, TagLib.File file, bool preferTrackInfo) { // TODO support these as arrays: // Performers[] (track artists), AlbumArtists[], Composers[], Genres[] // Note: this should be kept in sync with the metadata written in SaveTrackMetadataJob.cs if (file != null) { track.Uri = new SafeUri(file.Name); track.MimeType = file.MimeType; track.Duration = file.Properties.Duration; track.BitRate = file.Properties.AudioBitrate; FindTrackMediaAttributes(track, file); track.ArtistName = Choose(file.Tag.JoinedPerformers, track.ArtistName, preferTrackInfo); track.ArtistNameSort = Choose(file.Tag.JoinedPerformersSort, track.ArtistNameSort, preferTrackInfo); track.AlbumTitle = Choose(file.Tag.Album, track.AlbumTitle, preferTrackInfo); track.AlbumTitleSort = Choose(file.Tag.AlbumSort, track.AlbumTitleSort, preferTrackInfo); track.AlbumArtist = Choose(file.Tag.FirstAlbumArtist, track.AlbumArtist, preferTrackInfo); track.AlbumArtistSort = Choose(file.Tag.FirstAlbumArtistSort, track.AlbumArtistSort, preferTrackInfo); track.IsCompilation = IsCompilation(file); track.TrackTitle = Choose(file.Tag.Title, track.TrackTitle, preferTrackInfo); track.TrackTitleSort = Choose(file.Tag.TitleSort, track.TrackTitleSort, preferTrackInfo); track.Genre = Choose(file.Tag.FirstGenre, track.Genre, preferTrackInfo); track.Composer = Choose(file.Tag.FirstComposer, track.Composer, preferTrackInfo); track.Conductor = Choose(file.Tag.Conductor, track.Conductor, preferTrackInfo); track.Grouping = Choose(file.Tag.Grouping, track.Grouping, preferTrackInfo); track.Copyright = Choose(file.Tag.Copyright, track.Copyright, preferTrackInfo); track.Comment = Choose(file.Tag.Comment, track.Comment, preferTrackInfo); track.TrackNumber = Choose((int)file.Tag.Track, track.TrackNumber, preferTrackInfo); track.TrackCount = Choose((int)file.Tag.TrackCount, track.TrackCount, preferTrackInfo); track.DiscNumber = Choose((int)file.Tag.Disc, track.DiscNumber, preferTrackInfo); track.DiscCount = Choose((int)file.Tag.DiscCount, track.DiscCount, preferTrackInfo); track.Year = Choose((int)file.Tag.Year, track.Year, preferTrackInfo); track.Bpm = Choose((int)file.Tag.BeatsPerMinute, track.Bpm, preferTrackInfo); } else { track.MediaAttributes = TrackMediaAttributes.AudioStream; if (track.Uri != null && VideoExtensions.IsMatchingFile(track.Uri.LocalPath)) { track.MediaAttributes = TrackMediaAttributes.VideoStream; } } track.FileSize = Banshee.IO.File.GetSize(track.Uri); track.FileModifiedStamp = Banshee.IO.File.GetModifiedTime(track.Uri); track.LastSyncedStamp = DateTime.Now; if (String.IsNullOrEmpty(track.TrackTitle)) { try { string filename = System.IO.Path.GetFileNameWithoutExtension(track.Uri.LocalPath); if (!String.IsNullOrEmpty(filename)) { track.TrackTitle = filename; } } catch {} } // TODO look for track number in the file name if not set? // TODO could also pull artist/album from folders _iff_ files two levels deep in the MusicLibrary folder // TODO these ideas could also be done in an extension that collects such hacks }
public static void TrackInfoMerge(TrackInfo track, TagLib.File file) { TrackInfoMerge(track, file, false); }
/// <summary> /// Constructs and initializes a new instance of <see /// cref="IsoMetaBox" /> with a provided header and /// handler by reading the contents from a specified file. /// </summary> /// <param name="header"> /// A <see cref="BoxHeader" /> object containing the header /// to use for the new instance. /// </param> /// <param name="file"> /// A <see cref="TagLib.File" /> object to read the contents /// of the box from. /// </param> /// <param name="handler"> /// A <see cref="IsoHandlerBox" /> object containing the /// handler that applies to the new instance. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="file" /> is <see langword="null" />. /// </exception> public IsoMetaBox(BoxHeader header, TagLib.File file, IsoHandlerBox handler) : base(header, file, handler) { children = LoadChildren(file); }
public void bibli_picture() { string path = (@"C:\Users\" + Environment.UserName + @"\Pictures"); FilePaths = Directory.GetFiles(path, "*.jpg", SearchOption.AllDirectories); FilePaths2 = Directory.GetFiles(path, "*.png", SearchOption.AllDirectories); FilePaths3 = Directory.GetFiles(path, "*.gif", SearchOption.AllDirectories); FilePaths4 = Directory.GetFiles(path, "*.bmp", SearchOption.AllDirectories); string[] z; z = new string[FilePaths.Count() + FilePaths2.Count()]; FilePaths.CopyTo(z, 0); FilePaths2.CopyTo(z, FilePaths.Count()); FilePaths = z; z = new string[FilePaths.Count() + FilePaths3.Count()]; FilePaths.CopyTo(z, 0); FilePaths3.CopyTo(z, FilePaths.Count()); FilePaths = z; z = new string[FilePaths.Count() + FilePaths4.Count()]; FilePaths.CopyTo(z, 0); FilePaths4.CopyTo(z, FilePaths.Count()); FilePaths = z; TagLib.File[] f; f = new TagLib.File[FilePaths.Count()]; for (int i = 0; i < FilePaths.Count(); i++) { f[i] = TagLib.File.Create(FilePaths[i]); } var gridview = new GridView(); this.bibView.View = gridview; gridview.Columns.Add(new GridViewColumn { Header = "Titre", DisplayMemberBinding = new Binding("Title") }); bibView.Items.Clear(); for (int i = 0; i < FilePaths.Count(); i++) { bibView.Items.Add(new Video() { Title = System.IO.Path.GetFileNameWithoutExtension(FilePaths[i]) }); } }
/// <summary> /// Creates a box by reading it from a file given its header /// and handler. /// </summary> /// <param name="file"> /// A <see cref="TagLib.File" /> object containing the file /// to read from. /// </param> /// <param name="header"> /// A <see cref="BoxHeader" /> object containing the header /// of the box to create. /// </param> /// <returns> /// A newly created <see cref="Box" /> object. /// </returns> public static Box CreateBox(TagLib.File file, BoxHeader header) { return(CreateBox(file, header, null)); }
/// <summary> /// Constructs and initializes a new instance of <see /// cref="MovieIdTag" /> by reading the contents of a raw /// RIFF list from a specified position in a <see /// cref="TagLib.File"/>. /// </summary> /// <param name="file"> /// A <see cref="TagLib.File" /> object containing the file /// from which the contents of the new instance is to be /// read. /// </param> /// <param name="position"> /// A <see cref="long" /> value specify at what position to /// read the list. /// </param> /// <param name="length"> /// A <see cref="int" /> value specifying the number of bytes /// to read. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="file" /> is <see langword="null" />. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="position" /> is less than zero or greater /// than the size of the file. /// </exception> public MovieIdTag(TagLib.File file, long position, int length) : base(file, position, length) { }
/// <summary> /// Creates a box by reading it from a file given its header, /// parent header, handler, and index in its parent. /// </summary> /// <param name="file"> /// A <see cref="TagLib.File" /> object containing the file /// to read from. /// </param> /// <param name="header"> /// A <see cref="BoxHeader" /> object containing the header /// of the box to create. /// </param> /// <param name="parent"> /// A <see cref="BoxHeader" /> object containing the header /// of the parent box. /// </param> /// <param name="handler"> /// A <see cref="IsoHandlerBox" /> object containing the /// handler that applies to the new box. /// </param> /// <param name="index"> /// A <see cref="int" /> value containing the index of the /// new box in its parent. /// </param> /// <returns> /// A newly created <see cref="Box" /> object. /// </returns> private static Box CreateBox(TagLib.File file, BoxHeader header, BoxHeader parent, IsoHandlerBox handler, int index) { // The first few children of an "stsd" are sample // entries. if (parent.BoxType == BoxType.Stsd && parent.Box is IsoSampleDescriptionBox && index < (parent.Box as IsoSampleDescriptionBox).EntryCount) { if (handler != null && handler.HandlerType == BoxType.Soun) { return(new IsoAudioSampleEntry(header, file, handler)); } else if (handler != null && handler.HandlerType == BoxType.Vide) { return(new IsoVisualSampleEntry(header, file, handler)); } else if (handler != null && handler.HandlerType == BoxType.Alis) { if (header.BoxType == BoxType.Text) { return(new TextBox(header, file, handler)); } else if (header.BoxType == BoxType.Url) { return(new UrlBox(header, file, handler)); } // This could be anything, so just parse it return(new UnknownBox(header, file, handler)); } else { return(new IsoSampleEntry(header, file, handler)); } } // Standard items... ByteVector type = header.BoxType; if (type == BoxType.Mvhd) { return(new IsoMovieHeaderBox(header, file, handler)); } else if (type == BoxType.Stbl) { return(new IsoSampleTableBox(header, file, handler)); } else if (type == BoxType.Stsd) { return(new IsoSampleDescriptionBox(header, file, handler)); } else if (type == BoxType.Stco) { return(new IsoChunkOffsetBox(header, file, handler)); } else if (type == BoxType.Co64) { return(new IsoChunkLargeOffsetBox(header, file, handler)); } else if (type == BoxType.Hdlr) { return(new IsoHandlerBox(header, file, handler)); } else if (type == BoxType.Udta) { return(new IsoUserDataBox(header, file, handler)); } else if (type == BoxType.Meta) { return(new IsoMetaBox(header, file, handler)); } else if (type == BoxType.Ilst) { return(new AppleItemListBox(header, file, handler)); } else if (type == BoxType.Data) { return(new AppleDataBox(header, file, handler)); } else if (type == BoxType.Esds) { return(new AppleElementaryStreamDescriptor( header, file, handler)); } else if (type == BoxType.Free || type == BoxType.Skip) { return(new IsoFreeSpaceBox(header, file, handler)); } else if ((type == BoxType.Mean || type == BoxType.Name) && header.DataSize >= 4) { return(new AppleAdditionalInfoBox(header, file, handler)); } // If we still don't have a tag, and we're inside an // ItemListBox, load the box as an AnnotationBox // (Apple tag item). if (parent.BoxType == BoxType.Ilst) { return(new AppleAnnotationBox(header, file, handler)); } // Nothing good. Go generic. return(new UnknownBox(header, file, handler)); }
/// <summary> /// Constructs and initializes a new instance of <see /// cref="IsoMetaBox" /> with a provided header and /// handler by reading the contents from a specified file. /// </summary> /// <param name="header"> /// A <see cref="BoxHeader" /> object containing the header /// to use for the new instance. /// </param> /// <param name="file"> /// A <see cref="TagLib.File" /> object to read the contents /// of the box from. /// </param> /// <param name="handler"> /// A <see cref="IsoHandlerBox" /> object containing the /// handler that applies to the new instance. /// </param> public IsoFreeSpaceBox(BoxHeader header, TagLib.File file, IsoHandlerBox handler) : base(header, handler) { padding = DataSize; }
public bool Process(FileInfo file) { TagLib.File f = null; try { f = TagLib.File.Create(new TagLib.File.LocalFileAbstraction(file.OriginalFullPath)); } catch { return(false); } string tag = ""; switch (Tag) { case MediaTag.AudioAlbum: tag = f.Tag.Album; break; case MediaTag.AudioAlbumArtists: tag = (Arguments != -1) ? f.Tag.AlbumArtists [Arguments] : string.Join(",", f.Tag.AlbumArtists); break; case MediaTag.AudioComposers: tag = (Arguments != -1) ? f.Tag.Composers [Arguments] : string.Join(",", f.Tag.Composers); break; case MediaTag.AudioCopyright: case MediaTag.VideoCopyright: tag = f.Tag.Copyright; break; case MediaTag.AudioDisc: tag = f.Tag.Disc.ToString(); break; case MediaTag.AudioDiscCount: tag = f.Tag.DiscCount.ToString(); break; case MediaTag.AudioGenres: case MediaTag.VideoGenres: tag = (Arguments != -1) ? f.Tag.Genres [Arguments] : string.Join(",", f.Tag.Genres); break; case MediaTag.AudioPerformers: tag = (Arguments != -1) ? f.Tag.Performers [Arguments] : string.Join(",", f.Tag.Performers); break; case MediaTag.AudioTitle: case MediaTag.VideoTitle: tag = f.Tag.Title; break; case MediaTag.AudioTrack: tag = f.Tag.Track.ToString(); break; case MediaTag.AudioTrackCount: tag = f.Tag.TrackCount.ToString(); break; case MediaTag.AudioYear: case MediaTag.VideoYear: tag = f.Tag.Year.ToString(); break; case MediaTag.AudioDuration: case MediaTag.VideoDuration: tag = f.Properties.Duration.ToString("hh:mm:ss"); break; case MediaTag.AudioCodec: foreach (var codec in f.Properties.Codecs) { if (codec.MediaTypes == TagLib.MediaTypes.Audio) { tag = codec.Description; } } break; case MediaTag.AudioSamplerate: tag = f.Properties.AudioSampleRate.ToString(); break; case MediaTag.AudioBitrate: tag = f.Properties.AudioBitrate.ToString(); break; case MediaTag.AudioBitsPerSample: tag = f.Properties.BitsPerSample.ToString(); break; case MediaTag.AudioChannels: tag = f.Properties.AudioChannels.ToString(); break; case MediaTag.ImageWidth: tag = f.Properties.PhotoWidth.ToString(); break; case MediaTag.ImageHeight: tag = f.Properties.PhotoHeight.ToString(); break; case MediaTag.ImageQuality: tag = f.Properties.PhotoQuality.ToString(); break; case MediaTag.ImageCodec: foreach (var codec in f.Properties.Codecs) { if (codec.MediaTypes == TagLib.MediaTypes.Audio) { tag = codec.Description; } } break; case MediaTag.VideoWidth: tag = f.Properties.VideoWidth.ToString(); break; case MediaTag.VideoHeight: tag = f.Properties.VideoHeight.ToString(); break; case MediaTag.VideoCodec: foreach (var codec in f.Properties.Codecs) { if (codec.MediaTypes == TagLib.MediaTypes.Video) { tag = codec.Description; } } break; } f.Dispose(); string fn = Path.GetFileNameWithoutExtension(file.ChangedFilename); string ext = Path.GetExtension(file.ChangedFilename); file.ChangedFilename = Position == OnePointPosition.StartPoint ? $"{tag}{fn}{ext}" : (Position == OnePointPosition.EndPoint ? $"{fn}{tag}{ext}" : $"{tag}{fn}{tag}{ext}"); return(true); }
public TrackInfo() { _attributes = new List<CUELine>(); _fileInfo = null; }
public 弹窗提示(int parameter, Color color, int Other_parameters, string file) { InitializeComponent(); 模板一.Visibility = Visibility.Collapsed; 模板二.Visibility = Visibility.Collapsed; 模板三.Visibility = Visibility.Collapsed; 模板四.Visibility = Visibility.Collapsed; 模板五.Visibility = Visibility.Collapsed; 单文件.Background = new SolidColorBrush(color); if (parameter == 0) { 模板一.Visibility = Visibility.Visible; } else if (parameter == 1) { 模板二.Visibility = Visibility.Visible; if (Other_parameters == 0) { 提示.Text = "共扫描到了" + Other_parameters + "首歌曲,似乎神马也木有扫描到(#°Д°)"; } else { 提示.Text = "共扫描到了" + Other_parameters + "首歌曲"; } } else if (parameter == 2) { TagLib.File Read_information = TagLib.File.Create(file); 文件名称.Text = System.IO.Path.GetFileName(file); 歌曲名称.Text = Read_information.Tag.Title; for (int i = 0; i < Read_information.Tag.Artists.Length; i++) { if (i > 0) { 歌手信息.Text += ";" + Read_information.Tag.Artists[i]; } else { 歌手信息.Text = Read_information.Tag.Artists[i]; } } 专辑信息.Text = Read_information.Tag.Album; 音频比特.Text = Read_information.Properties.AudioBitrate + " kbps"; 音频频道.Text = Convert.ToString(Read_information.Properties.AudioChannels) + " 声道"; 音频采样.Text = Convert.ToString(Read_information.Properties.AudioSampleRate) + " Hz"; 播放时长.Text = Convert.ToString(Read_information.Properties.Duration); 文件描述.Text = Read_information.Properties.Description; 文件路径.Text = file; if (Read_information.Tag.Lyrics != null) { 嵌入歌词.Text = "有内嵌歌词"; } else { 嵌入歌词.Text = "没有嵌入歌词"; } if (Read_information.Tag.Pictures != null && Read_information.Tag.Pictures.Length != 0) { 专辑图片.Text = "有专辑图片"; } else { 专辑图片.Text = "没有专辑图片"; } System.IO.FileInfo f = new FileInfo(file); 文件大小.Text = GetFileSize(f.Length); 文件类型.Text = System.IO.Path.GetExtension(file); 创建日期.Text = f.CreationTimeUtc.ToString(); 修改日期.Text = f.LastWriteTimeUtc.ToString(); 模板三.Visibility = Visibility.Visible; } else if (parameter == 3) { PlaySound(@"C:\Windows\media\Windows Proximity Notification.wav", 0, 1); 模板四.Visibility = Visibility.Visible; 提示2.Text = file; } else if (parameter == 4) { PlaySound(@"C:\Windows\media\Windows Proximity Notification.wav", 0, 1); 模板五.Visibility = Visibility.Visible; 问题.Text = file; } 动画播放("打开"); }
public FileTagTools(string file_path) { if (System.IO.File.Exists(file_path)) audioFile = TagLib.File.Create(file_path); }
/// <summary> /// Searches for an audio header in a <see cref="TagLib.File" /// /> starting at a specified position and searching through /// a specified number of bytes. /// </summary> /// <param name="header"> /// A <see cref="AudioHeader" /> object in which the found /// header will be stored. /// </param> /// <param name="file"> /// A <see cref="TagLib.File" /> object to search. /// </param> /// <param name="position"> /// A <see cref="long" /> value specifying the seek position /// in <paramref name="file" /> at which to start searching. /// </param> /// <param name="length"> /// A <see cref="int" /> value specifying the maximum number /// of bytes to search before aborting. /// </param> /// <returns> /// A <see cref="bool" /> value indicating whether or not a /// header was found. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="file" /> is <see langword="null" />. /// </exception> public static bool Find(out AudioHeader header, TagLib.File file, long position, int length) { if (file == null) { throw new ArgumentNullException("file"); } long end = position + length; header = AudioHeader.Unknown; file.Seek(position); ByteVector buffer = file.ReadBlock(3); if (buffer.Count < 3) { return(false); } do { file.Seek(position + 3); buffer = buffer.Mid(buffer.Count - 3); buffer.Add(file.ReadBlock( (int)File.BufferSize)); for (int i = 0; i < buffer.Count - 3 && (length < 0 || position + i < end); i++) { if (buffer[i] == 0xFF && buffer[i + 1] >= 0xF0) // 0xFFF { try { BitStream bits = new BitStream(buffer.Mid(i, 7).Data); // 12 bits sync header bits.ReadInt32(12); // 1 bit mpeg 2/4 bits.ReadInt32(1); // 2 bits layer bits.ReadInt32(2); // 1 bit protection absent bits.ReadInt32(1); // 2 bits profile object type bits.ReadInt32(2); // 4 bits sampling frequency index int samplerateindex = bits.ReadInt32(4); if (samplerateindex >= sample_rates.Length) { return(false); } long samplerate = sample_rates[samplerateindex]; // 1 bit private bit bits.ReadInt32(1); // 3 bits channel configuration int channelconfigindex = bits.ReadInt32(3); if (channelconfigindex >= channels.Length) { return(false); } // 4 copyright bits bits.ReadInt32(4); // 13 bits frame length long framelength = bits.ReadInt32(13); // double check framelength if (framelength < 7) { return(false); } // 11 bits buffer fullness bits.ReadInt32(11); // 2 bits number of raw data blocks in frame int numberofframes = bits.ReadInt32(2) + 1; long numberofsamples = numberofframes * 1024; long bitrate = framelength * 8 * samplerate / numberofsamples; header = new AudioHeader(channels[channelconfigindex], (int)bitrate, (int)samplerate, (int)numberofsamples, numberofframes); return(true); } catch (CorruptFileException) { } } } position += File.BufferSize; } while (buffer.Count > 3 && (length < 0 || position < end)); return(false); }
/// <summary> /// Constructs and initializes a new instance of <see /// cref="AppleAdditionalInfoBox" /> with a provided header /// and handler by reading the contents from a specified /// file. /// </summary> /// <param name="header"> /// A <see cref="BoxHeader" /> object containing the header /// to use for the new instance. /// </param> /// <param name="file"> /// A <see cref="TagLib.File" /> object to read the contents /// of the box from. /// </param> /// <param name="handler"> /// A <see cref="IsoHandlerBox" /> object containing the /// handler that applies to the new instance. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="file" /> is <see langword="null" />. /// </exception> public AppleAdditionalInfoBox(BoxHeader header, TagLib.File file, IsoHandlerBox handler) : base(header, file, handler) { Data = file.ReadBlock(DataSize); }
/// <summary> /// Searches for an audio header in a <see cref="TagLib.File" /// /> starting at a specified position and searching to the /// end of the file. /// </summary> /// <param name="header"> /// A <see cref="AudioHeader" /> object in which the found /// header will be stored. /// </param> /// <param name="file"> /// A <see cref="TagLib.File" /> object to search. /// </param> /// <param name="position"> /// A <see cref="long" /> value specifying the seek position /// in <paramref name="file" /> at which to start searching. /// </param> /// <returns> /// A <see cref="bool" /> value indicating whether or not a /// header was found. /// </returns> /// <remarks> /// Searching to the end of the file can be very, very slow /// especially for corrupt or non-MPEG files. It is /// recommended to use <see /// cref="Find(AudioHeader,TagLib.File,long,int)" /> /// instead. /// </remarks> public static bool Find(out AudioHeader header, TagLib.File file, long position) { return(Find(out header, file, position, -1)); }
/// <summary> /// Constructs and initializes a new instance of <see /// cref="AppleElementaryStreamDescriptor" /> with a provided /// header and handler by reading the contents from a /// specified file. /// </summary> /// <param name="header"> /// A <see cref="BoxHeader" /> object containing the header /// to use for the new instance. /// </param> /// <param name="file"> /// A <see cref="TagLib.File" /> object to read the contents /// of the box from. /// </param> /// <param name="handler"> /// A <see cref="IsoHandlerBox" /> object containing the /// handler that applies to the new instance. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="file" /> is <see langword="null" />. /// </exception> /// <exception cref="CorruptFileException"> /// Valid data could not be read. /// </exception> public AppleElementaryStreamDescriptor(BoxHeader header, TagLib.File file, IsoHandlerBox handler) : base(header, file, handler) { /* ES_Descriptor Specifications * Section 7.2.6.5 http://ecee.colorado.edu/~ecen5653/ecen5653/papers/ISO%2014496-1%202004.PDF */ ByteVector box_data = file.ReadBlock(DataSize); DecoderConfig = new ByteVector(); int offset = 0; // Elementary Stream Descriptor Tag if ((DescriptorTag)box_data[offset++] != DescriptorTag.ES_DescrTag) { throw new CorruptFileException("Invalid Elementary Stream Descriptor, missing tag."); } // We have a descriptor tag. Check that the remainder of the tag is at least [Base (3 bytes) + DecoderConfigDescriptor (15 bytes) + SLConfigDescriptor (3 bytes) + OtherDescriptors] bytes long uint es_length = ReadLength(box_data, ref offset); uint min_es_length = 3 + 15 + 3; // Base minimum length if (es_length < min_es_length) { throw new CorruptFileException("Insufficient data present."); } StreamId = box_data.Mid(offset, 2).ToUShort(); offset += 2; // Done with ES_ID stream_dependence_flag = ((byte)((box_data[offset] >> 7) & 0x1) == 0x1 ? true : false); // 1st bit URL_flag = ((byte)((box_data[offset] >> 6) & 0x1) == 0x1 ? true : false); // 2nd bit ocr_stream_flag = ((byte)((box_data[offset] >> 5) & 0x1) == 0x1 ? true : false); // 3rd bit StreamPriority = (byte)(box_data[offset++] & 0x1F); // Last 5 bits and we're done with this byte if (stream_dependence_flag) { min_es_length += 2; // We need 2 more bytes if (es_length < min_es_length) { throw new CorruptFileException("Insufficient data present."); } dependsOn_ES_ID = box_data.Mid(offset, 2).ToUShort(); offset += 2; // Done with stream dependence } if (URL_flag) { min_es_length += 2; // We need 1 more byte if (es_length < min_es_length) { throw new CorruptFileException("Insufficient data present."); } URLlength = box_data[offset++]; // URL Length min_es_length += URLlength; // We need URLength more bytes if (es_length < min_es_length) { throw new CorruptFileException("Insufficient data present."); } URLstring = box_data.Mid(offset, URLlength).ToString(); // URL name offset += URLlength; // Done with URL name } if (ocr_stream_flag) { min_es_length += 2; // We need 2 more bytes if (es_length < min_es_length) { throw new CorruptFileException("Insufficient data present."); } OCR_ES_Id = box_data.Mid(offset, 2).ToUShort(); offset += 2; // Done with OCR } while (offset < DataSize) // Loop through all trailing Descriptors Tags { DescriptorTag tag = (DescriptorTag)box_data[offset++]; switch (tag) { case DescriptorTag.DecoderConfigDescrTag: // DecoderConfigDescriptor { // Check that the remainder of the tag is at least 13 bytes long (13 + DecoderSpecificInfo[] + profileLevelIndicationIndexDescriptor[]) if (ReadLength(box_data, ref offset) < 13) { throw new CorruptFileException("Could not read data. Too small."); } // Read a lot of good info. ObjectTypeId = box_data[offset++]; StreamType = (byte)(box_data[offset] >> 2); // First 6 bits upStream = ((byte)((box_data[offset++] >> 1) & 0x1) == 0x1 ? true : false); // 7th bit and we're done with the stream bits BufferSizeDB = box_data.Mid(offset, 3).ToUInt(); offset += 3; // Done with bufferSizeDB max_bitrate = box_data.Mid(offset, 4).ToUInt(); offset += 4; // Done with maxBitrate average_bitrate = box_data.Mid(offset, 4).ToUInt(); offset += 4; // Done with avgBitrate // If there's a DecoderSpecificInfo[] array at the end it'll pick it up in the while loop } break; case DescriptorTag.DecSpecificInfoTag: // DecoderSpecificInfo { // The rest of the info is decoder specific. uint length = ReadLength(box_data, ref offset); DecoderConfig = box_data.Mid(offset, (int)length); offset += (int)length; // We're done with the config } break; case DescriptorTag.SLConfigDescrTag: // SLConfigDescriptor { // The rest of the info is SL specific. uint length = ReadLength(box_data, ref offset); offset += (int)length; // Skip the rest of the descriptor as reported in the length so we can move onto the next one } break; case DescriptorTag.Forbidden_00: case DescriptorTag.Forbidden_FF: throw new CorruptFileException("Invalid Descriptor tag."); default: { /* TODO: Should we handle other optional descriptor tags? * ExtensionDescriptor extDescr[0 .. 255]; * LanguageDescriptor langDescr[0 .. 1]; * IPI_DescPointer ipiPtr[0 .. 1]; * IP_IdentificationDataSet ipIDS[0 .. 1]; * QoS_Descriptor qosDescr[0 .. 1]; */ uint length = ReadLength(box_data, ref offset); // Every descriptor starts with a length offset += (int)length; // Skip the rest of the descriptor as reported in the length so we can move onto the next one break; } } } }
/// <summary>Reads the album and artist data from specified media file or folder. Adds it to the <see cref="mAlbums"/> collection, and if it does so, also adds it to <paramref name="addedAlbums"/>.</summary> /// <param name="filePathPattern">Use null to use the ID3 tags instead</param> /// <returns>The <see cref="Album"/> that was added to <see cref="mAlbums"/>, or <c>null</c> if none could be read.</returns> private void ReadMediaFile(FileSystemInfo file, Regex filePathPattern, IList <Album> addedAlbums) { if (file is DirectoryInfo && filePathPattern == null) //If a DirectoryInfo is used, then the filePathPattern must have ended in \. { throw new ArgumentException("Directories are only supported for pattern matching, not ID3 tags", "file"); } Dispatcher.BeginInvoke(DispatcherPriority.DataBind, new ThreadStart(delegate { ProgressText = "Searching... " + file.Name; })); string artistName = null; string albumName = null; int? embeddedArtIndex = null; if (filePathPattern == null) { //Read ID3 Tags TagLib.File fileTags = null; try { fileTags = TagLib.File.Create(file.FullName, TagLib.ReadStyle.None); if (fileTags.Tag.AlbumArtists.Length == 0) { artistName = String.Join(" / ", fileTags.Tag.Performers); } else { artistName = String.Join(" / ", fileTags.Tag.AlbumArtists); } albumName = fileTags.Tag.Album; embeddedArtIndex = EmbeddedArtHelpers.GetEmbeddedFrontCoverIndex(fileTags); } catch (Exception e) { System.Diagnostics.Trace.WriteLine("TagLib# could not get artist and album information for file: " + file.FullName); System.Diagnostics.Trace.Indent(); System.Diagnostics.Trace.WriteLine(e.Message); System.Diagnostics.Trace.Unindent(); return; //If this media file couldn't be read, just go on to the next one. } finally { if (fileTags != null) { fileTags.Mode = TagLib.File.AccessMode.Closed; } } } else { //Read from file path Match match = filePathPattern.Match(file.FullName); if (match.Success) { artistName = match.Groups["artist"].Value; albumName = match.Groups["album"].Value; } } if (!(String.IsNullOrEmpty(artistName) && String.IsNullOrEmpty(albumName))) //No point adding it if no artist or album could be found. { string basePath; if (file is FileInfo) { basePath = ((FileInfo)file).DirectoryName; } else { System.Diagnostics.Debug.Assert(file is DirectoryInfo, "Expecting file to be one of FileInfo or DirectoryInfo"); basePath = ((DirectoryInfo)file).FullName; } Album album = new Album(basePath, artistName, albumName); if (embeddedArtIndex.HasValue) { //Read the picture from the data album.SetArtFile(EmbeddedArtHelpers.GetEmbeddedFilePath(file.FullName, embeddedArtIndex.Value)); } Dispatcher.Invoke(DispatcherPriority.DataBind, new ThreadStart(delegate { if (mAlbums.Add(album)) { addedAlbums.Add(album); } })); } }
//######################################METODY POMOCNICZE KLASY###################################### protected override void resetujTagi() { tagi = TagLib.File.Create(Sciezka); stareTagi = TagLib.File.Create(Sciezka); }
public void Scan() { Dictionary <string, TrackInfoCache> cache = new Dictionary <string, TrackInfoCache>(); foreach (TrackInfoCache localTrackInfo in this.collectionManager.LocalTrackInfos) { cache[localTrackInfo.Filename] = localTrackInfo; } //using (var transaction = this.collectionManager.BeginTransaction()) //{ string[] files; if (Directory.Exists(this.collectionManager.Settings.MusicDirectory)) { files = Directory.GetFiles(this.collectionManager.Settings.MusicDirectory, "*", SearchOption.AllDirectories) .Where(f => f.EndsWith(".flac") || f.EndsWith(".mp3")) .ToArray(); } else { files = new string[0]; } int processed = 0; foreach (string file in files) { TrackInfoCache trackInfo; FileInfo fileInfo = new FileInfo(file); if (!cache.TryGetValue(file, out trackInfo) || trackInfo.LastWriteTime != fileInfo.LastWriteTime.Ticks) { if (trackInfo == null) { trackInfo = new TrackInfoCache(); } trackInfo.Filename = file; trackInfo.RelativeFilename = trackInfo.Filename.Substring(this.collectionManager.Settings.MusicDirectory.Length).Trim('\\').Trim('/'); trackInfo.LastWriteTime = fileInfo.LastWriteTime.Ticks; using (TagLib.File mediaFile = TagLib.File.Create(file)) { trackInfo.Artist = mediaFile.Tag.JoinedPerformers; trackInfo.AlbumArtist = mediaFile.Tag.JoinedAlbumArtists; trackInfo.Album = mediaFile.Tag.Album; trackInfo.Disc = (int)mediaFile.Tag.Disc; trackInfo.DiscCount = (int)mediaFile.Tag.DiscCount; trackInfo.Track = (int)mediaFile.Tag.Track; trackInfo.TrackCount = (int)mediaFile.Tag.TrackCount; trackInfo.Title = mediaFile.Tag.Title; trackInfo.Genre = mediaFile.Tag.JoinedGenres; trackInfo.Year = (int)mediaFile.Tag.Year; } this.collectionManager.Save(trackInfo); } this.LocalCollection.Add(trackInfo); ++processed; ProgressChangedEventArgs eventArgs = new ProgressChangedEventArgs((double)processed / files.Length); this.OnProgressChanged(eventArgs); if (eventArgs.Cancel) { return; } } //transaction.Commit(); //} }
public string[] getInfo(string mupath) { // 목록에 아무것도 없는 상태에서 음악 로드시 // 플레이하던 곡이 끝날 때 // 곡 선택시 string[] Info = new string[3]; string artists = ""; finfo = TagLib.File.Create(mupath); if (finfo.Tag.Title != null) Info[0] = finfo.Tag.Title; else { string mName = mupath.Substring(mupath.LastIndexOf("\\") + 1); Info[0] = mName; } if (finfo.Tag.Artists.Length != 0) { foreach (string artist in finfo.Tag.Artists) { artists = artists + artist + ", "; } artists = artists.Substring(0, artists.LastIndexOf(",")); Info[1] = artists; } else Info[1] = "(none)"; if (finfo.Tag.Album != null) Info[2] = finfo.Tag.Album; else Info[2] = "(none)"; return Info; }
private void PlaySong(int songIndex) { //Create Wave _waveOutDevice = new WaveOut(); ISampleProvider sampleProvider; try { sampleProvider = CreateInputStream(_songFiles.ElementAt(songIndex)); } catch (Exception createException) { sampleProvider = CreateInputStream(_songFiles.First()); lbSongs.SelectedIndex = 0; } //Length of the song lblTotalTime.Text = string.Format("{0:00}:{1:00}", (int)_audioFileReader.TotalTime.TotalMinutes, _audioFileReader.TotalTime.Seconds); //Set name and description string path; try { path = _songFiles.ElementAt(songIndex); } catch (Exception) { path = _songFiles.First(); } TagLib.File file = TagLib.File.Create(path); lblPerformer.Text = file.Tag.FirstPerformer; lblTitle.Text = file.Tag.Title; lblAlbum.Text = file.Tag.Album; lblYear.Text = file.Tag.Year.ToString(); lblGenre.Text = file.Tag.FirstGenre; //Set artwork TagLib.IPicture pic; MemoryStream stream; Bitmap image; if (file.Tag.Pictures.Length > 0) { pic = file.Tag.Pictures[0]; stream = new MemoryStream(pic.Data.Data); image = new Bitmap(stream); new Bitmap(stream); pbSongImg.Image = image; } else { pbSongImg.Image = null; } //Play song :P _waveOutDevice.Init(sampleProvider); _setVolumeDelegate(volumeSlider.Volume); _waveOutDevice.Play(); }
private void Search_button(object sender, TextChangedEventArgs e) { TextBox objtext = (TextBox)sender; string txt = objtext.Text; bibView.Items.Clear(); TagLib.File[] f; f = new TagLib.File[FilePaths.Count()]; for (int i = 0; i < FilePaths.Count(); i++) { f[i] = TagLib.File.Create(FilePaths[i]); } var gridview = new GridView(); this.bibView.View = gridview; if (comboBox.SelectedIndex == 0) { gridview.Columns.Add(new GridViewColumn { Header = "Titre", DisplayMemberBinding = new Binding("Title") }); gridview.Columns.Add(new GridViewColumn { Header = "Artiste", DisplayMemberBinding = new Binding("Artiste") }); gridview.Columns.Add(new GridViewColumn { Header = "Album", DisplayMemberBinding = new Binding("Album") }); if (this.Owner != null) { for (int i = 0; i < FilePaths.Count(); ++i) { if (System.IO.Path.GetFileNameWithoutExtension(FilePaths[i]).Contains(txt) || txt.Equals("")) bibView.Items.Add(new Song() { Title = System.IO.Path.GetFileNameWithoutExtension(FilePaths[i]), Artiste = f[i].Tag.FirstAlbumArtist, Album = f[i].Tag.Album }); } } } else if (comboBox.SelectedIndex == 1) { gridview.Columns.Add(new GridViewColumn { Header = "Titre", DisplayMemberBinding = new Binding("Title") }); gridview.Columns.Add(new GridViewColumn { Header = "Durée", DisplayMemberBinding = new Binding("Duree") }); if (this.Owner != null) { for (int i = 0; i < FilePaths.Count(); ++i) { if (System.IO.Path.GetFileNameWithoutExtension(FilePaths[i]).Contains(txt) || txt.Equals("")) bibView.Items.Add(new Video() { Title = System.IO.Path.GetFileNameWithoutExtension(FilePaths[i]), Duree = f[i].Properties.Duration.ToString("g") }); } } } else { gridview.Columns.Add(new GridViewColumn { Header = "Titre", DisplayMemberBinding = new Binding("Title") }); if (this.Owner != null) { for (int i = 0; i < FilePaths.Count(); ++i) { if (System.IO.Path.GetFileNameWithoutExtension(FilePaths[i]).Contains(txt) || txt.Equals("")) bibView.Items.Add(new Video() { Title = System.IO.Path.GetFileNameWithoutExtension(FilePaths[i]) }); } } } if (txt.Equals("")) select_box(); }
private static void renameMusic() { FolderBrowserDialog Folder_Browser_Dialog = main.get_folderbrowserdialog(); if (Folder_Browser_Dialog != null) { int fileCount = Directory.GetFiles(Folder_Browser_Dialog.SelectedPath, "*.mp3").Count(); int currentCount = 0; main.max_progressbar(fileCount, main.ProgressBar); main.update_progressbar(0, main.ProgressBar); main.change_status("0/" + fileCount, msgType.message); foreach (string file in Directory.GetFiles(Folder_Browser_Dialog.SelectedPath, "*.mp3")) { try { using (TagLib.File mp3 = TagLib.File.Create(file)) { string fileName = string.Empty; if (mp3.Tag.AlbumArtists.Length > 0 || (mp3.Tag.AlbumArtists.Length < 0 && mp3.Tag.JoinedPerformers.Length > 0)) { List <string> cArtists = new List <string>(); if (mp3.Tag.JoinedPerformers.Contains('/')) { cArtists = mp3.Tag.JoinedPerformers.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).ToList(); } else if (mp3.Tag.JoinedPerformers.Contains(';')) { cArtists = mp3.Tag.JoinedPerformers.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList(); } else if (mp3.Tag.JoinedPerformers.Length > 0) { cArtists.Add(mp3.Tag.JoinedPerformers); } if (mp3.Tag.AlbumArtists.Length > 0) { fileName = mp3.Tag.AlbumArtists[0]; } foreach (string cArtist in cArtists) { switch (cArtists.IndexOf(cArtist)) { case 0: if (string.IsNullOrEmpty(fileName)) { fileName = cArtist; } else { fileName += " ft. " + cArtist; } break; case 1: fileName += " & " + cArtist; break; default: fileName += ", " + cArtist; break; } } fileName += " - ";; } fileName += mp3.Tag.Title; try { File.Move(file, Folder_Browser_Dialog.SelectedPath + "/" + fileName + ".mp3"); main.log("Renamed --> " + fileName, msgType.message); } catch (Exception e) { if (e.HResult == -2146232800) { main.log("File Exists --> " + fileName, msgType.warning); } else { main.log("Couldn't Rename --> " + fileName + Environment.NewLine + e.ToString(), msgType.error); } } } currentCount += 1; main.change_status(currentCount + "/" + fileCount, msgType.message); main.update_progressbar(main.get_progressbar_value(main.ProgressBar) + 1, main.ProgressBar); } catch (Exception ex) { main.log(file + Environment.NewLine + "\t" + ex.ToString(), msgType.error); } } main.change_status("Done", msgType.success); } }
public void MoveTo(string path) { System.IO.File.Move(_content.Name, path); _content = File.Create(path); }
public static NameValueCollection Analyze(TagLib.File fileInfo) { NameValueCollection tags = new NameValueCollection(); var xiph = (TagLib.Ogg.XiphComment)fileInfo.GetTag(TagLib.TagTypes.Xiph); var ape = (TagLib.Ape.Tag)fileInfo.GetTag(TagLib.TagTypes.Ape); var asf = (TagLib.Asf.Tag)fileInfo.GetTag(TagLib.TagTypes.Asf); if (xiph != null) { foreach (string tag in xiph) { foreach (string value in xiph.GetField(tag)) { if (!IsKnownXiphTag(tag)) { tags.Add(tag, value); } } } } else if (ape != null) { foreach (string tag in ape) { foreach (string value in ape.GetItem(tag).ToStringArray()) { if (!IsKnownApeTag(tag)) { tags.Add(tag, value); } } } } else if (asf != null) { foreach (ContentDescriptor desc in asf.ExtendedContentDescriptionObject) { if (desc != null && desc.Type == DataType.Unicode && desc.Name.StartsWith("foobar2000/")) { tags.Add(desc.Name.Substring("foobar2000/".Length), desc.ToString()); } } } else { //if (audioSource is CUETools.Codecs.ALAC.ALACReader) //tags = (audioSource as CUETools.Codecs.ALAC.ALACReader).Tags; } // TODO: enumerate dash atoms somehow? //TagLib.Mpeg4.AppleTag apple = (TagLib.Mpeg4.AppleTag)fileInfo.GetTag(TagLib.TagTypes.Apple); //if (apple != null) //{ // tags = new NameValueCollection(); // foreach (TagLib.Mpeg4.Box tag in apple) // if (tag.BoxType == "----") // foreach (string value in apple.GetDashBox(tag.) // tags.Add(tag, value); //} return(tags); }
static async Task CreateCustomLevelFromFile(Download download) { download.Status = "Uploading File"; TagLib.File tagFile = TagLib.File.Create(download.FilePath); string artistName = "Unknown"; string trackName = "Unknown"; byte[] imageData = null; var invalids = System.IO.Path.GetInvalidFileNameChars(); if (tagFile.Tag.FirstPerformer != null) { artistName = String.Join("_", tagFile.Tag.FirstPerformer.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.'); } if (tagFile.Tag.Title != null) { trackName = String.Join("_", tagFile.Tag.Title.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.'); } else { trackName = System.IO.Path.GetFileNameWithoutExtension(download.FilePath); } if (tagFile.Tag.Pictures.Count() > 0) { if (tagFile.Tag.Pictures[0].Data.Data != null) { imageData = tagFile.Tag.Pictures[0].Data.Data; } } download.Artist = artistName; download.Title = trackName; string fileName = "[BSD] " + trackName + " - " + artistName; if (!Properties.Settings.Default.overwriteExisting) { if (((!Properties.Settings.Default.automaticExtraction) && (File.Exists(Properties.Settings.Default.outputDirectory + @"\" + fileName + ".zip"))) || ((Properties.Settings.Default.automaticExtraction) && (Directory.Exists(Properties.Settings.Default.outputDirectory + @"\" + fileName)))) { download.Status = "Already Exists"; download.IsAlive = false; return; } } byte[] bytes = System.IO.File.ReadAllBytes(download.FilePath); string boundary = "----WebKitFormBoundaryaA38RFcmCeKFPOms"; var content = new MultipartFormDataContent(boundary); content.Add(new ByteArrayContent(bytes), "audio_file", download.FileName); if (imageData != null) { var imageContent = new ByteArrayContent(imageData); imageContent.Headers.Remove("Content-Type"); imageContent.Headers.Add("Content-Disposition", "form-data; name=\"cover_art\"; filename=\"cover\""); imageContent.Headers.Add("Content-Type", "image/jpeg"); content.Add(imageContent); } content.Add(new StringContent(trackName), "audio_metadata_title"); content.Add(new StringContent(artistName), "audio_metadata_artist"); content.Add(new StringContent(download.Difficulties), "difficulties"); content.Add(new StringContent(download.GameModes), "modes"); content.Add(new StringContent(download.SongEvents), "events"); content.Add(new StringContent(download.Environment), "environment"); content.Add(new StringContent(download.ModelVersion), "system_tag"); var response = await httpClient.PostAsync("https://beatsage.com/beatsaber_custom_level_create", content, cts.Token); var responseString = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseString); JObject jsonString = JObject.Parse(responseString); string levelID = (string)jsonString["id"]; Console.WriteLine(levelID); await CheckDownload(levelID, trackName, artistName, download); }
private void GetTracksFromFolders() { var extensions = new List <string> { ".mp3", ".flac" }; var index = Math.Max(tracks.Count, 1); foreach ( var files in folders .Select(folder => Directory .GetFiles(folder, "*.*", SearchOption.AllDirectories) .Where(f => extensions.IndexOf(Path.GetExtension(f)) >= 0))) { foreach (var file in files) { var artists = ""; var album = ""; var title = ""; int duration; try { var tagFile = File.Create(file); duration = (int)tagFile.Properties.Duration.TotalMilliseconds; artists = string.Join(", ", tagFile.Tag.Performers); album = tagFile.Tag.Album ?? ""; title = tagFile.Tag.Title ?? ""; } catch (Exception) { try { var extension = file.Split('.').Last(); if (extension.Equals("mp3")) { var reader = new Mp3FileReader(file); duration = (int)reader.TotalTime.TotalMilliseconds; } else { var reader = new FlacReader(file); duration = (int)reader.TotalTime.TotalMilliseconds; } } catch (Exception) { continue; } } if (duration > 10 * 60 * 1000) { continue; } if (tracks.ContainsKey(file)) { continue; } var track = new Track { Id = index++, IsSpotifyTrack = false, HasMetaData = title.Length != 0, TrackName = title, Artist = artists, Album = album, TrackPath = file, TotalTime = duration, Location = file }; tracks.Add(file, track); } } }
public void CreateFileInstance(string filepath) { FileInstance = TagLib.File.Create(filepath); }
public void OpenCUE(TextReader sr) { string pathAudio = null; string lineStr, command, fileType; bool fileIsBinary = false; int timeRelativeToFileStart, absoluteFileStartTime = 0; int fileTimeLengthSamples = 0, fileTimeLengthFrames = 0, i; TagLib.File _trackFileInfo = null; bool seenFirstFileIndex = false; bool isAudioTrack = true; List<IndexInfo> indexes = new List<IndexInfo>(); IndexInfo indexInfo; SourceInfo sourceInfo; TrackInfo trackInfo = null; int trackNumber = 0; using (sr) { while ((lineStr = sr.ReadLine()) != null) { CUELine line = new CUELine(lineStr); if (line.Params.Count > 0) { command = line.Params[0].ToUpper(); if (command == "FILE") { fileType = line.Params[2].ToUpper(); fileIsBinary = (fileType == "BINARY") || (fileType == "MOTOROLA"); if (fileIsBinary) { if (!_hasEmbeddedCUESheet && _sourcePaths.Count == 0) { try { if (_isArchive) pathAudio = FileLocator.LocateFile(_archiveCUEpath, line.Params[1], _archiveContents); else pathAudio = FileLocator.LocateFile(_inputDir, line.Params[1], null); fileIsBinary = (pathAudio == null); } catch { } } } if (!fileIsBinary) { if (_sourcePaths.Count != 0 && !seenFirstFileIndex) throw new Exception("Double FILE in CUE sheet: \"" + line.Params[1] + "\"."); if (!_hasEmbeddedCUESheet) { if (_isArchive) pathAudio = FileLocator.LocateFile(_archiveCUEpath, line.Params[1], _archiveContents); else pathAudio = FileLocator.LocateFile(_inputDir, line.Params[1], null); } else { pathAudio = _inputPath; if (_sourcePaths.Count > 0) throw new Exception("Extra file in embedded CUE sheet: \"" + line.Params[1] + "\"."); } if (pathAudio == null) { throw new Exception("Unable to locate file \"" + line.Params[1] + "\"."); //fileTimeLengthFrames = 75 * 60 * 70;; //fileTimeLengthSamples = fileTimeLengthFrames * 588; //if (_hasEmbeddedCUESheet) // _fileInfo = null; //else // _trackFileInfo = null; } else { // Wierd case: audio file after data track with only index 00 specified. if (!isAudioTrack && _sourcePaths.Count == 0 && indexes.Count > 0 && indexes[indexes.Count - 1].Index == 0) { indexInfo.Track = indexes[indexes.Count - 1].Track; indexInfo.Index = 1; indexInfo.Time = indexes[indexes.Count - 1].Time + 150; indexes.Add(indexInfo); absoluteFileStartTime += 150; } TagLib.File fileInfo; _sourcePaths.Add(pathAudio); absoluteFileStartTime += fileTimeLengthFrames; fileTimeLengthSamples = GetSampleLength(pathAudio, out fileInfo); if ((fileTimeLengthSamples % 588) == 492 && _config.truncate4608ExtraSamples) { _truncated4608 = true; fileTimeLengthSamples -= 4608; } fileTimeLengthFrames = (int)((fileTimeLengthSamples + 587) / 588); if (_hasEmbeddedCUESheet) _fileInfo = fileInfo; else _trackFileInfo = fileInfo; } seenFirstFileIndex = false; } } else if (command == "TRACK") { isAudioTrack = line.Params[2].ToUpper() == "AUDIO"; trackNumber = int.Parse(line.Params[1]); if (trackNumber != _toc.TrackCount + 1) throw new Exception("Invalid track number"); // Disabled this check: fails on Headcandy test image //if (isAudioTrack && _sourcePaths.Count == 0) // throw new Exception("No FILE seen before TRACK"); _toc.AddTrack(new CDTrack((uint)trackNumber, 0, 0, isAudioTrack, false)); if (isAudioTrack) { trackInfo = new TrackInfo(); _tracks.Add(trackInfo); } } else if (command == "INDEX") { timeRelativeToFileStart = CDImageLayout.TimeFromString(line.Params[2]); if (!seenFirstFileIndex) { if (timeRelativeToFileStart != 0) throw new Exception("First index must start at file beginning."); seenFirstFileIndex = true; if (isAudioTrack) { if (_tracks.Count > 0 && _trackFileInfo != null) _tracks[_tracks.Count - 1]._fileInfo = _trackFileInfo; _trackFileInfo = null; sourceInfo.Path = pathAudio; sourceInfo.Offset = 0; sourceInfo.Length = (uint)fileTimeLengthSamples; _sources.Add(sourceInfo); if ((fileTimeLengthSamples % 588) != 0) { sourceInfo.Path = null; sourceInfo.Offset = 0; sourceInfo.Length = (uint)((fileTimeLengthFrames * 588) - fileTimeLengthSamples); _sources.Add(sourceInfo); _paddedToFrame = true; } } } else { if (fileIsBinary) { fileTimeLengthFrames = timeRelativeToFileStart + 150; sourceInfo.Path = null; sourceInfo.Offset = 0; sourceInfo.Length = 150 * 588; _sources.Add(sourceInfo); //throw new Exception("unexpected BINARY directive"); } else { if (timeRelativeToFileStart > fileTimeLengthFrames) throw new Exception(string.Format("TRACK {0} INDEX {1} is at {2}, which is past {3} - the end of source file {4}", trackNumber, line.Params[1], CDImageLayout.TimeToString((uint)timeRelativeToFileStart), CDImageLayout.TimeToString((uint)fileTimeLengthFrames), pathAudio)); } } indexInfo.Track = trackNumber; indexInfo.Index = Int32.Parse(line.Params[1]); indexInfo.Time = absoluteFileStartTime + timeRelativeToFileStart; indexes.Add(indexInfo); } else if (!isAudioTrack) { // Ignore lines belonging to data tracks } else if (command == "PREGAP") { if (seenFirstFileIndex) throw new Exception("Pregap must occur at the beginning of a file."); int pregapLength = CDImageLayout.TimeFromString(line.Params[1]); indexInfo.Track = trackNumber; indexInfo.Index = 0; indexInfo.Time = absoluteFileStartTime; indexes.Add(indexInfo); sourceInfo.Path = null; sourceInfo.Offset = 0; sourceInfo.Length = (uint)pregapLength * 588; _sources.Add(sourceInfo); absoluteFileStartTime += pregapLength; } else if (command == "POSTGAP") { throw new Exception("POSTGAP command isn't supported."); } //else if ((command == "REM") && // (line.Params.Count >= 3) && // (line.Params[1].Length >= 10) && // (line.Params[1].Substring(0, 10).ToUpper() == "REPLAYGAIN")) //{ // // Remove ReplayGain lines //} else if ((command == "REM") && (line.Params.Count == 3) && (line.Params[1].ToUpper() == "ACCURATERIPID")) { _accurateRipId = line.Params[2]; } //else if ((command == "REM") && // (line.Params.Count == 3) && // (line.Params[1].ToUpper() == "SHORTEN")) //{ // fileTimeLengthFrames -= General.TimeFromString(line.Params[2]); //} //else if ((command == "REM") && // (line.Params.Count == 3) && // (line.Params[1].ToUpper() == "LENGTHEN")) //{ // fileTimeLengthFrames += General.TimeFromString(line.Params[2]); //} else { if (trackInfo != null) { trackInfo.Attributes.Add(line); } else { if (line.Params.Count > 2 && !line.IsQuoted[1] && (line.Params[0].ToUpper() == "TITLE" || line.Params[0].ToUpper() == "ARTIST" || (line.Params[0].ToUpper() == "REM" && (line.Params[1].ToUpper() == "GENRE" || line.Params[1].ToUpper() == "COMMENT") && line.Params.Count > 3 && !line.IsQuoted[2]))) { CUELine modline = new CUELine(); int nParams = line.Params[0].ToUpper() == "REM" ? 2 : 1; for (int iParam = 0; iParam < nParams; iParam++) { modline.Params.Add(line.Params[iParam]); modline.IsQuoted.Add(false); } string s = line.Params[nParams]; for (int iParam = nParams + 1; iParam < line.Params.Count; iParam++) s += " " + line.Params[iParam]; modline.Params.Add(s); modline.IsQuoted.Add(true); line = modline; } _attributes.Add(line); } } } } sr.Close(); } if (_tracks.Count == 0) throw new Exception("File must contain at least one audio track."); // Add dummy index 01 for data track if (!_toc[_toc.TrackCount].IsAudio && indexes[indexes.Count - 1].Index == 0) { fileTimeLengthFrames += 152 * 75; indexInfo.Track = trackNumber; indexInfo.Index = 1; indexInfo.Time = absoluteFileStartTime + fileTimeLengthFrames; indexes.Add(indexInfo); } // Add dummy track for calculation purposes indexInfo.Track = trackNumber + 1; indexInfo.Index = 1; indexInfo.Time = absoluteFileStartTime + fileTimeLengthFrames; indexes.Add(indexInfo); // Calculate the length of each index for (i = 0; i < indexes.Count - 1; i++) { if (indexes[i + 1].Time - indexes[i].Time < 0) throw new Exception("Indexes must be in chronological order."); if ((indexes[i + 1].Track != indexes[i].Track || indexes[i + 1].Index != indexes[i].Index + 1) && (indexes[i + 1].Track != indexes[i].Track + 1 || indexes[i].Index < 1 || indexes[i + 1].Index > 1)) throw new Exception("Indexes must be in chronological order."); if (indexes[i].Index == 1 && (i == 0 || indexes[i - 1].Index != 0)) _toc[indexes[i].Track].AddIndex(new CDTrackIndex(0U, (uint)indexes[i].Time)); _toc[indexes[i].Track].AddIndex(new CDTrackIndex((uint)indexes[i].Index, (uint)indexes[i].Time)); } // Calculate the length of each track for (int iTrack = 1; iTrack <= _toc.TrackCount; iTrack++) { _toc[iTrack].Start = _toc[iTrack][1].Start; _toc[iTrack].Length = iTrack == _toc.TrackCount ? (uint)indexes[indexes.Count - 1].Time - _toc[iTrack].Start : _toc[iTrack + 1].IsAudio ? _toc[iTrack + 1][1].Start - _toc[iTrack].Start : _toc[iTrack + 1][0].Start - _toc[iTrack].Start; } // Store the audio filenames, generating generic names if necessary _hasSingleFilename = _sourcePaths.Count == 1; _singleFilename = _hasSingleFilename ? Path.GetFileName(_sourcePaths[0]) : "Range.wav"; _hasHTOAFilename = (_sourcePaths.Count == (TrackCount + 1)); _htoaFilename = _hasHTOAFilename ? Path.GetFileName(_sourcePaths[0]) : "00.wav"; _hasTrackFilenames = !_hasEmbeddedCUESheet && !_hasSingleFilename && (_sourcePaths.Count == TrackCount || _hasHTOAFilename); for (i = 0; i < TrackCount; i++) { _trackFilenames.Add(_hasTrackFilenames ? Path.GetFileName( _sourcePaths[i + (_hasHTOAFilename ? 1 : 0)]) : String.Format("{0:00}.wav", i + 1)); } if (!_hasEmbeddedCUESheet && _hasSingleFilename) { _fileInfo = _tracks[0]._fileInfo; _tracks[0]._fileInfo = null; } taglibMetadata = new CUEMetadata(TOC.TOCID, (int)TOC.AudioTracks); taglibMetadata.Artist = GetCommonTag(file => file.Tag.JoinedAlbumArtists) ?? GetCommonTag(file => file.Tag.JoinedPerformers) ?? ""; taglibMetadata.Title = GetCommonTag(file => file.Tag.Album) ?? ""; taglibMetadata.Year = GetCommonTag(file => file.Tag.Year != 0 ? file.Tag.Year.ToString() : null) ?? ""; taglibMetadata.Genre = GetCommonTag(file => file.Tag.JoinedGenres) ?? ""; taglibMetadata.Comment = GetCommonTag(file => file.Tag.Comment) ?? ""; taglibMetadata.TotalDiscs = GetCommonTag(file => file.Tag.DiscCount != 0 ? file.Tag.DiscCount.ToString() : null) ?? ""; taglibMetadata.DiscNumber = GetCommonTag(file => file.Tag.Disc != 0 ? file.Tag.Disc.ToString() : null) ?? ""; taglibMetadata.ReleaseDate = GetCommonTag(file => file.Tag.ReleaseDate) ?? ""; taglibMetadata.Country = GetCommonTag(file => file.Tag.MusicBrainzReleaseCountry) ?? ""; taglibMetadata.Label = GetCommonTag(file => file.Tag.Publisher) ?? ""; taglibMetadata.LabelNo = GetCommonTag(file => file.Tag.CatalogNo) ?? ""; taglibMetadata.DiscName = GetCommonTag(file => file.Tag.DiscSubtitle) ?? ""; for (i = 0; i < TrackCount; i++) { TrackInfo track = _tracks[i]; taglibMetadata.Tracks[i].Artist = (_hasTrackFilenames && track._fileInfo != null ? track._fileInfo.Tag.JoinedPerformers : _hasEmbeddedCUESheet && _fileInfo != null ? Tagging.TagListToSingleValue(Tagging.GetMiscTag(_fileInfo, String.Format("cue_track{0:00}_ARTIST", i + 1))) : null) ?? ""; taglibMetadata.Tracks[i].Title = (_hasTrackFilenames && track._fileInfo != null ? track._fileInfo.Tag.Title : _hasEmbeddedCUESheet && _fileInfo != null ? Tagging.TagListToSingleValue(Tagging.GetMiscTag(_fileInfo, String.Format("cue_track{0:00}_TITLE", i + 1))) : null) ?? ""; taglibMetadata.Tracks[i].Comment = (_hasTrackFilenames && track._fileInfo != null ? track._fileInfo.Tag.Title : _hasEmbeddedCUESheet && _fileInfo != null ? Tagging.TagListToSingleValue(Tagging.GetMiscTag(_fileInfo, String.Format("cue_track{0:00}_COMMENT", i + 1))) : null) ?? ""; } cueMetadata = new CUEMetadata(TOC.TOCID, (int)TOC.AudioTracks); cueMetadata.Artist = General.GetCUELine(_attributes, "PERFORMER"); cueMetadata.Title = General.GetCUELine(_attributes, "TITLE"); cueMetadata.Barcode = General.GetCUELine(_attributes, "CATALOG"); cueMetadata.Year = General.GetCUELine(_attributes, "REM", "DATE"); cueMetadata.DiscNumber = General.GetCUELine(_attributes, "REM", "DISCNUMBER"); cueMetadata.TotalDiscs = General.GetCUELine(_attributes, "REM", "TOTALDISCS"); cueMetadata.Genre = General.GetCUELine(_attributes, "REM", "GENRE"); cueMetadata.Comment = General.GetCUELine(_attributes, "REM", "COMMENT"); cueMetadata.ReleaseDate = General.GetCUELine(_attributes, "REM", "RELEASEDATE"); cueMetadata.Country = General.GetCUELine(_attributes, "REM", "COUNTRY"); cueMetadata.Label = General.GetCUELine(_attributes, "REM", "LABEL"); cueMetadata.LabelNo = General.GetCUELine(_attributes, "REM", "CATALOGNUMBER"); cueMetadata.DiscName = General.GetCUELine(_attributes, "REM", "DISCSUBTITLE"); for (i = 0; i < Tracks.Count; i++) { cueMetadata.Tracks[i].Artist = General.GetCUELine(Tracks[i].Attributes, "PERFORMER"); cueMetadata.Tracks[i].Title = General.GetCUELine(Tracks[i].Attributes, "TITLE"); cueMetadata.Tracks[i].ISRC = General.GetCUELine(Tracks[i].Attributes, "ISRC"); } // Now, TOC.TOCID might change!!! if (_config.fillUpCUE) { cueMetadata.Merge(taglibMetadata, _config.overwriteCUEData); for (i = 0; i < TrackCount; i++) { if (cueMetadata.Tracks[i].Title == "" && _hasTrackFilenames) cueMetadata.Tracks[i].Title = Path.GetFileNameWithoutExtension(_trackFilenames[i]).TrimStart(" .-_0123456789".ToCharArray()); } } CUELine cddbDiscIdLine = General.FindCUELine(_attributes, "REM", "DISCID"); _cddbDiscIdTag = cddbDiscIdLine != null && cddbDiscIdLine.Params.Count == 3 ? cddbDiscIdLine.Params[2] : null; if (_cddbDiscIdTag == null) _cddbDiscIdTag = GetCommonMiscTag("DISCID"); if (_accurateRipId == null) _accurateRipId = GetCommonMiscTag("ACCURATERIPID"); if (_eacLog == null && _logFiles != null && _logFiles.Count > 0) { foreach (CUEToolsSourceFile sf in _logFiles) { CDImageLayout tocFromLog1 = LogToTocParser.LogToToc(this._toc, sf.contents); if (tocFromLog1 != null && tocFromLog1.TOCID == _toc.TOCID) { if (_eacLog == null) _eacLog = sf.contents; else { _eacLog = null; break; } } } } if (_eacLog == null && _logFiles != null && _logFiles.Count > 0) { CUEToolsSourceFile selectedLogFile = ChooseFile(_logFiles, _defaultLog, false); _eacLog = selectedLogFile != null ? selectedLogFile.contents : null; } CDImageLayout tocFromLog = _eacLog == null ? null : LogToTocParser.LogToToc(this._toc, _eacLog); if (tocFromLog == null) { string tocPath = Path.ChangeExtension(InputPath, ".toc"); if (File.Exists(tocPath)) { tocFromLog = LogToTocParser.LogToToc(this._toc, new StreamReader(tocPath, CUESheet.Encoding).ReadToEnd()); } } // use pregaps from log if (tocFromLog != null) { //int srcNo = (int) _toc[_toc.FirstAudio].LastIndex - (PreGapLength == 0 ? 1 : 0); if (PreGapLength < tocFromLog.Pregap) { PreGapLength = tocFromLog.Pregap; //srcNo ++; } int trNo; for (trNo = 1; trNo < tocFromLog.AudioTracks && trNo < _toc.AudioTracks; trNo++) { if (_toc[_toc.FirstAudio + trNo].Pregap < tocFromLog[tocFromLog.FirstAudio + trNo].Pregap) _toc[_toc.FirstAudio + trNo].Pregap = tocFromLog[tocFromLog.FirstAudio + trNo].Pregap; } //if (_toc[_toc.FirstAudio].Length > tocFromLog[tocFromLog.FirstAudio].Length) //{ // uint offs = _toc[_toc.FirstAudio].Length - tocFromLog[tocFromLog.FirstAudio].Length; // _toc[_toc.FirstAudio].Length -= offs; // sourceInfo = _sources[srcNo]; // sourceInfo.Length -= offs * 588; // _sources[srcNo] = sourceInfo; // for (i = _toc.FirstAudio + 1; i <= _toc.TrackCount; i++) // { // _toc[i].Start -= offs; // for (int j = 0; j <= _toc[i].LastIndex; j++) // if (i != _toc.FirstAudio + 1 || j != 0 || _toc[i][0].Start == _toc[i][1].Start) // _toc[i][j].Start -= offs; // } //} //for (trNo = 1; trNo < tocFromLog.AudioTracks && trNo < _toc.AudioTracks; trNo++) //{ // srcNo ++; // if (_toc[_toc.FirstAudio + trNo].Length > tocFromLog[tocFromLog.FirstAudio + trNo].Length) // { // uint offs = _toc[_toc.FirstAudio + trNo].Length - tocFromLog[tocFromLog.FirstAudio + trNo].Length; // _toc[_toc.FirstAudio + trNo].Length -= offs; // sourceInfo = _sources[srcNo]; // sourceInfo.Length -= offs * 588; // _sources[srcNo] = sourceInfo; // for (i = _toc.FirstAudio + trNo + 1; i <= _toc.TrackCount; i++) // { // _toc[i].Start -= offs; // for (int j = 0; j <= _toc[i].LastIndex; j++) // if (i != _toc.FirstAudio + trNo + 1 || j != 0 || _toc[i][0].Start == _toc[i][1].Start) // _toc[i][j].Start -= offs; // } // } //} } // use data track length from log if (tocFromLog != null) { if (tocFromLog.AudioTracks == _toc.AudioTracks && tocFromLog.TrackCount == tocFromLog.AudioTracks + 1 && !tocFromLog[tocFromLog.TrackCount].IsAudio) { DataTrackLength = tocFromLog[tocFromLog.TrackCount].Length; _toc[_toc.TrackCount].Start = tocFromLog[_toc.TrackCount].Start; _toc[_toc.TrackCount][0].Start = tocFromLog[_toc.TrackCount].Start; _toc[_toc.TrackCount][1].Start = tocFromLog[_toc.TrackCount].Start; } if (_toc.TrackCount == _toc.AudioTracks && tocFromLog.TrackCount == tocFromLog.AudioTracks && tocFromLog.TrackCount > _toc.TrackCount) { int dtracks = tocFromLog.TrackCount - _toc.TrackCount; bool matches = true; for (int iTrack = 1; iTrack <= _toc.TrackCount; iTrack++) if (tocFromLog[iTrack + dtracks].Length != _toc[iTrack].Length) matches = false; if (matches) { for (int iTrack = 1; iTrack <= dtracks; iTrack++) { _toc.InsertTrack(new CDTrack((uint)iTrack, 0, 0, false, false)); tocFromLog[iTrack].IsAudio = false; } tocFromLog.FirstAudio += dtracks; tocFromLog.AudioTracks -= (uint)dtracks; } } if (tocFromLog.AudioTracks == _toc.AudioTracks && tocFromLog.TrackCount == _toc.TrackCount && tocFromLog.FirstAudio == _toc.FirstAudio && tocFromLog.TrackCount == tocFromLog.FirstAudio + tocFromLog.AudioTracks - 1) { //DataTrackLength = tocFromLog[1].Length; uint delta = tocFromLog[_toc.FirstAudio].Start - _toc[_toc.FirstAudio].Start; for (int itr = 1; itr < _toc.FirstAudio; itr++) { _toc[itr].Start = tocFromLog[itr].Start; _toc[itr].Length = tocFromLog[itr].Length; } for (int itr = _toc.FirstAudio; itr <= _toc.TrackCount; itr++) { _toc[itr].Start += delta; for (int j = 0; j <= _toc[itr].LastIndex; j++) _toc[itr][j].Start += delta; } } } // use data track length range from cddbId if (DataTrackLength == 0 && _cddbDiscIdTag != null) { uint cddbDiscIdNum; if (uint.TryParse(_cddbDiscIdTag, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out cddbDiscIdNum) && (cddbDiscIdNum & 0xff) == _toc.AudioTracks + 1) { if (_toc.TrackCount == _toc.AudioTracks) _toc.AddTrack(new CDTrack((uint)_toc.TrackCount + 1, _toc.Length + 152 * 75, 0, false, false)); uint lengthFromTag = ((cddbDiscIdNum >> 8) & 0xffff); _minDataTrackLength = (lengthFromTag + _toc[1].Start / 75) * 75 - _toc.Length; } } _arVerify = new AccurateRipVerify(_toc, proxy); if (_eacLog != null) { sr = new StringReader(_eacLog); bool isEACLog = false; int trNo = 1; while ((lineStr = sr.ReadLine()) != null) { if (isEACLog && trNo <= TrackCount) { string[] s = { "Copy CRC ", "CRC копии" }; string[] s1 = { "CRC" }; string[] n = lineStr.Split(s, StringSplitOptions.None); uint crc; if (n.Length == 2 && uint.TryParse(n[1], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out crc)) _arVerify.CRCLOG(trNo++, crc); else if (n.Length == 1) { n = lineStr.Split(s1, StringSplitOptions.None); if (n.Length == 2 && n[0].Trim() == "" && uint.TryParse(n[1], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out crc)) _arVerify.CRCLOG(trNo++, crc); } } else if (lineStr.StartsWith("Exact Audio Copy") || lineStr.StartsWith("EAC extraction logfile")) isEACLog = true; } if (trNo == 2) { _arVerify.CRCLOG(0, _arVerify.CRCLOG(1)); if (TrackCount > 1) _arVerify.CRCLOG(1, 0); } } LoadAlbumArt(_tracks[0]._fileInfo ?? _fileInfo); ResizeAlbumArt(); if (_config.embedAlbumArt || _config.CopyAlbumArt) _albumArt.ForEach(t => _padding += _albumArt[0].Data.Count); if (_config.embedLog && _eacLog != null) _padding += _eacLog.Length; cueMetadata.Id = TOC.TOCID; taglibMetadata.Id = TOC.TOCID; // TODO: It should also be set when assigning a DataTrack!!! }
public void bibli_video() { string path = (@"C:\Users\" + Environment.UserName + @"\Videos"); FilePaths = Directory.GetFiles(path, "*.mp4", SearchOption.AllDirectories); FilePaths2 = Directory.GetFiles(path, "*.mkv", SearchOption.AllDirectories); FilePaths3 = Directory.GetFiles(path, "*.avi", SearchOption.AllDirectories); FilePaths4 = Directory.GetFiles(path, "*.m4v", SearchOption.AllDirectories); string[] z; z = new string[FilePaths.Count() + FilePaths2.Count()]; FilePaths.CopyTo(z, 0); FilePaths2.CopyTo(z, FilePaths.Count()); FilePaths = z; z = new string[FilePaths.Count() + FilePaths3.Count()]; FilePaths.CopyTo(z, 0); FilePaths3.CopyTo(z, FilePaths.Count()); FilePaths = z; z = new string[FilePaths.Count() + FilePaths4.Count()]; FilePaths.CopyTo(z, 0); FilePaths4.CopyTo(z, FilePaths.Count()); FilePaths = z; TagLib.File[] f; f = new TagLib.File[FilePaths.Count()]; for (int i = 0; i < FilePaths.Count(); i++) { f[i] = TagLib.File.Create(FilePaths[i]); } var gridview = new GridView(); this.bibView.View = gridview; gridview.Columns.Add(new GridViewColumn { Header = "Titre", DisplayMemberBinding = new Binding("Title") }); gridview.Columns.Add(new GridViewColumn { Header = "Durée", DisplayMemberBinding = new Binding("Duree") }); for (int i = 0; i < FilePaths.Count(); i++) { bibView.Items.Add(new Video() { Title = f[i].Tag.Title, Duree = f[i].Properties.Duration.ToString("g") }); //listView.Items.Add(System.IO.Path.GetFileNameWithoutExtension(((MainWindow)this.Owner).med.chemin[i])); } }
/// <summary> /// Call this method to play track. Returns false if not playable /// </summary> /// <param name="error"></param> /// <returns></returns> private bool InitializeForPlay(out string error) { if (_initialized) { error = string.Empty; return(true); } if (string.IsNullOrWhiteSpace(_model.Location)) { error = _nonf[4]; return(false); } if (!System.IO.File.Exists(_model.Location)) { error = "file does not exist"; return(false); } try { _v = File.Create(_model.Location); } catch (Exception e) { error = e.Message; return(false); } try { _waveOut = new WaveOut(); } catch (Exception e) { error = e.Message; return(false); } try { _reader = new Mp3FileReader(_model.Location); _waveOut.Init(_reader); //_waveOut.Play(); } catch (Exception e) { error = e.Message; return(false); } if (_v == null) { error = _nonf[0]; return(false); } if (_v.PossiblyCorrupt) { error = _nonf[2]; return(false); // } if (_v.MimeType != "taglib/mp3") { error = _nonf[3]; return(false); } error = "Succesfully initiated player for file"; _initialized = true; return(true); }
/// <summary> /// Constructs and initializes a new instance of <see /// cref="FileParser" /> for a specified file. /// </summary> /// <param name="file"> /// A <see cref="TagLib.File" /> object to perform operations /// on. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="file" /> is <see langword="null" />. /// </exception> /// <exception cref="CorruptFileException"> /// <paramref name="file" /> does not start with a /// "<c>ftyp</c>" box. /// </exception> public FileParser (TagLib.File file) { if (file == null) throw new ArgumentNullException ("file"); this.file = file; first_header = new BoxHeader (file, 0); if (first_header.BoxType != "ftyp") throw new CorruptFileException ( "File does not start with 'ftyp' box."); }
/// <summary> /// Constructs and initializes a new instance of <see /// cref="EndTag" /> for a specified <see cref="TagLib.File" /// />. /// </summary> /// <param name="file"> /// A <see cref="TagLib.File" /> object on which the new /// instance will perform its operations. /// </param> /// <remarks> /// Constructing a new instance does not automatically read /// the contents from the disk. <see cref="Read" /> must be /// called to read the tags. /// </remarks> public EndTag(TagLib.File file) : base() { this.file = file; }
private BitmapImage CreateCover(File metaData) { if (metaData.Tag.IsEmpty || metaData.Tag.Pictures.Length == 0) return null; var picture = metaData.Tag.Pictures[0]; MemoryStream mstream = new MemoryStream(picture.Data.Data); mstream.Seek(0, SeekOrigin.Begin); BitmapImage bitmap; lock (this) { try { bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.StreamSource = mstream; bitmap.EndInit(); bitmap.Freeze(); } catch (Exception e) { bitmap = null; } } return bitmap; }
public void Save() { _file.Save(); if (!string.IsNullOrEmpty(NewName)) { var path = _file.Name.Substring(0, _file.Name.LastIndexOf(@"\")); path = path + @"\" + NewName + ".mp3"; System.IO.File.Move(_file.Name, path); _file = File.Create(path); } }
public Mp3File(File file) { _file = file; }
/// <summary> /// Constructs and initializes a new instance of <see /// cref="StartTag" /> for a specified <see /// cref="TagLib.File" />. /// </summary> /// <param name="file"> /// A <see cref="TagLib.File" /> object on which the new /// instance will perform its operations. /// </param> /// <remarks> /// Constructing a new instance does not automatically read /// the contents from the disk. <see cref="Read" /> must be /// called to read the tags. /// </remarks> public StartTag(TagLib.File file) : base() { this.file = file; }
// Загрузка редактора private void Form_TagEditor_Load(object sender, EventArgs e) { fl_loading = true; Load_TagsList(); if (File.Exists(File_Path)) { //Tag_File = new UltraID3(); //Tag_File.Read(File_Path); Tag_File = TagLib.File.Create(File_Path); Load_FileTags(); string Ext = Path.GetExtension(File_Path).ToLower(); if (Ext != ".mp3") { TagsActive = false; memoEdit_Comments.Text = "Файл \"" + Ext +"\" не содержит тегов!"; } else TagsActive = true; } else { TagsActive = false; Tag_File = null; ResaultMsg = "Файл не найден: " + File_Path; memoEdit_Comments.Text = "Файл не найден!"; TE_FilePath.Text = Path.GetFileName(File_Path); TE_FilePath.ToolTip = File_Path; TE_Artist.Text = ""; TE_Name.Text = ""; } fl_loading = false; Test_IsDataChanged(); TE_FilePath.DeselectAll(); }