/// <summary> /// copy constructor /// </summary> /// <param name="tag"></param> public MusicTag(MusicTag tag) { if (tag == null) return; Artist = tag.Artist; Album = tag.Album; Genre = tag.Genre; Title = tag.Title; Comment = tag.Comment; Year = tag.Year; Duration = tag.Duration; Track = tag.Track; TimesPlayed = tag.m_TimesPlayed; Rating = tag.Rating; BitRate = tag.BitRate; Composer = tag.Composer; CoverArtImageBytes = tag.CoverArtImageBytes; AlbumArtist = tag.AlbumArtist; Lyrics = tag.Lyrics; Comment = tag.Comment; ReplayGainTrack = tag.ReplayGainTrack; ReplayGainTrackPeak = tag.ReplayGainTrackPeak; ReplayGainAlbum = tag.ReplayGainAlbum; ReplayGainAlbumPeak = tag.ReplayGainAlbumPeak; DateTimePlayed = tag.DateTimePlayed; DateTimeModified = tag.DateTimeModified; }
/// <summary> /// copy constructor /// </summary> /// <param name="tag"></param> public MusicTag(MusicTag tag) { if (tag == null) { return; } Artist = tag.Artist; Album = tag.Album; Genre = tag.Genre; Title = tag.Title; Comment = tag.Comment; Year = tag.Year; Duration = tag.Duration; Track = tag.Track; TimesPlayed = tag.m_TimesPlayed; Rating = tag.Rating; BitRate = tag.BitRate; Composer = tag.Composer; CoverArtImageBytes = tag.CoverArtImageBytes; AlbumArtist = tag.AlbumArtist; Lyrics = tag.Lyrics; Comment = tag.Comment; ReplayGainTrack = tag.ReplayGainTrack; ReplayGainTrackPeak = tag.ReplayGainTrackPeak; ReplayGainAlbum = tag.ReplayGainAlbum; ReplayGainAlbumPeak = tag.ReplayGainAlbumPeak; DateTimePlayed = tag.DateTimePlayed; DateTimeModified = tag.DateTimeModified; }
// Filename is a full path+file public FolderThumbCreator(string Filename, MusicTag FileTag) { lock (_filename) { _filename = Filename; _filetag = FileTag; work = new Work(new DoWorkHandler(this.PerformRequest)); work.ThreadPriority = ThreadPriority.Lowest; GlobalServiceProvider.Get<IThreadPool>().Add(work, QueuePriority.Low); } }
/// <summary> /// copy constructor /// </summary> /// <param name="tag"></param> public MusicTag(MusicTag tag) { if (tag == null) { return; } Artist = tag.Artist; Album = tag.Album; Genre = tag.Genre; Title = tag.Title; Comment = tag.Comment; Year = tag.Year; Duration = tag.Duration; Track = tag.Track; TimesPlayed = tag.m_TimesPlayed; Rating = tag.Rating; BitRate = tag.BitRate; Composer = tag.Composer; CoverArtImageBytes = tag.CoverArtImageBytes; AlbumArtist = tag.AlbumArtist; Lyrics = tag.Lyrics; Comment = tag.Comment; ReplayGainTrack = tag.ReplayGainTrack; ReplayGainTrackPeak = tag.ReplayGainTrackPeak; ReplayGainAlbum = tag.ReplayGainAlbum; ReplayGainAlbumPeak = tag.ReplayGainAlbumPeak; MusicBrainzArtistId = tag.MusicBrainzArtistId; MusicBrainzDiscId = tag.MusicBrainzDiscId; MusicBrainzReleaseArtistId = tag.MusicBrainzReleaseArtistId; MusicBrainzReleaseCountry = tag.MusicBrainzReleaseCountry; MusicBrainzReleaseGroupId = tag.MusicBrainzReleaseGroupId; MusicBrainzReleaseId = tag.MusicBrainzReleaseId; MusicBrainzReleaseStatus = tag.MusicBrainzReleaseStatus; MusicBrainzReleaseType = tag.MusicBrainzReleaseType; MusicBrainzTrackId = tag.MusicBrainzTrackId; DateTimePlayed = tag.DateTimePlayed; DateTimeModified = tag.DateTimeModified; }
/// <summary> /// Takes a list of tracks supplied by last.fm and matches them to tracks in the database /// </summary> /// <param name="tracks">List of last FM tracks to check</param> /// <param name="tag">Tags of track we are looking up</param> /// <returns>List of matched songs from input that exist in the users database</returns> private static List<Song> GetSimilarTracksInDatabase(IEnumerable<LastFMSimilarTrack> tracks, MusicTag tag) { // list contains songs which exist in users collection var dbTrackListing = new List<Song>(); var filter = BuildAutoDJFilter(_autoDJFilter, tag); if (!string.IsNullOrEmpty(filter)) { Log.Debug("Applying filter: {0}", filter); } //identify which are available in users collection (ie. we can use they for auto DJ mode) foreach (var strSql in tracks.Select(track => String.Format("select * from tracks where strartist like '%| {0} |%' and strTitle = '{1}' {2}", DatabaseUtility.RemoveInvalidChars(track.ArtistName), DatabaseUtility.RemoveInvalidChars(track.TrackTitle), filter))) { List<Song> trackListing; MusicDatabase.Instance.GetSongsBySQL(strSql, out trackListing); dbTrackListing.AddRange(trackListing); } // only add track that already exists in playlist if there is no alternative if (_avoidDuplicates && dbTrackListing.Count(track => !InPlaylist(track.FileName)) > 1) { dbTrackListing = dbTrackListing.Where(track => !InPlaylist(track.FileName)).ToList(); } return _allowMultipleVersions ? dbTrackListing : dbTrackListing.GroupBy(t => new {t.Artist, t.Title}).Select(y => y.First()).ToList(); }
/// <summary> /// Read MusicTag information from cueFakeTrack /// Not thread safe! /// </summary> /// <param name="cueFakeTrackFileName">Cue fake track file name</param> /// <returns>MusicTag filled with cue track information</returns> public static MusicTag CueFakeTrackFile2MusicTag(string cueFakeTrackFileName) { lock (cacheLock) { // This metod called twice for each single file. So, cache data! if (cueFakeTrackFileName == cueFakeTrackFileNameCache) { return(musicTagCache); } cueFakeTrackFileNameCache = cueFakeTrackFileName; // Cache CueSheet to pervent parsing it for each track in the album CueFakeTrack cueFakeTrack = parseCueFakeTrackFileName(cueFakeTrackFileName); if (cueSheetCacheFileNameCache != cueFakeTrack.CueFileName) { cueSheetCache = new CueSheet(cueFakeTrack.CueFileName); cueSheetCacheFileNameCache = cueFakeTrack.CueFileName; } int trackPosition = cueFakeTrack.TrackNumber - cueSheetCache.Tracks[0].TrackNumber; Track track = cueSheetCache.Tracks[trackPosition]; musicTagCache = new MusicTag(); if (track.TrackNumber < cueSheetCache.Tracks[cueSheetCache.Tracks.Length - 1].TrackNumber) { Track nextTrack = cueSheetCache.Tracks[trackPosition + 1]; musicTagCache.Duration = cueIndexToIntTime(nextTrack.Indices[0]) - cueIndexToIntTime(track.Indices[0]); } string fname = Path.Combine(Path.GetDirectoryName(cueFakeTrack.CueFileName), track.DataFile.Filename); try { if (fname != cacheFName) { TagLib.File file = TagLib.File.Create(fname); tagCache = new TagCache(); tagCache.CopyTags(file); } cacheFName = fname; musicTagCache.FileType = tagCache.FileType; musicTagCache.Codec = tagCache.Codec; musicTagCache.Year = tagCache.Year; musicTagCache.BitRate = tagCache.BitRate; musicTagCache.DiscID = tagCache.DiscId; musicTagCache.DiscTotal = tagCache.DiscTotal; musicTagCache.Channels = tagCache.Channels; musicTagCache.SampleRate = tagCache.SampleRate; musicTagCache.BitRateMode = tagCache.BitRateMode; if (musicTagCache.Duration == 0) { musicTagCache.Duration = tagCache.Duration - cueIndexToIntTime(track.Indices[0]); } } catch (Exception) { // If we end up here this means that we were not able to read the file // Most probably because of taglib-sharp not supporting the audio file // For example DTS file format has no Tags, but can be replayed by BASS // Use MediaInfo to read the properties if (fname != cacheFName) { tagCache = new TagCache(); if (tagCache.CopyMediaInfo(fname)) { musicTagCache.FileType = tagCache.FileType; musicTagCache.Codec = tagCache.Codec; musicTagCache.BitRate = tagCache.BitRate; musicTagCache.Channels = tagCache.Channels; musicTagCache.SampleRate = tagCache.SampleRate; musicTagCache.BitRateMode = tagCache.BitRateMode; if (musicTagCache.Duration == 0) { musicTagCache.Duration = tagCache.Duration - cueIndexToIntTime(track.Indices[0]); } } } cacheFName = fname; } // In case of having a multi file Cue sheet, we're not able to get the duration // from the index entries. use MediaInfo then if (musicTagCache.Duration == 0) { try { var logger = GlobalServiceProvider.Get <MediaInfo.ILogger>(); var mi = new MediaInfoWrapper(fname, logger); if (!mi.MediaInfoNotloaded) { mi.WriteInfo(); musicTagCache.Duration = (int?)mi.BestAudioStream?.Duration.TotalSeconds ?? 0; } } catch (Exception ex1) { Log.Warn("CueFakeTrackFile2MusicTag: Exception retrieving duration for file {0}. {1}", fname, ex1.Message); } } if (string.IsNullOrEmpty(musicTagCache.Artist)) { // if track has a performer set use this value for artist tag // else use global performer defined for cue sheet if (!string.IsNullOrEmpty(track.Performer)) { musicTagCache.Artist = track.Performer; } else { musicTagCache.Artist = cueSheetCache.Performer; } } if (string.IsNullOrEmpty(musicTagCache.Album)) { musicTagCache.Album = cueSheetCache.Title; } if (string.IsNullOrEmpty(musicTagCache.AlbumArtist)) { if (!string.IsNullOrEmpty(cueSheetCache.Performer)) { musicTagCache.AlbumArtist = cueSheetCache.Performer; musicTagCache.HasAlbumArtist = true; } else { musicTagCache.HasAlbumArtist = false; } } // let tagged genre override cuesheet genre if (string.IsNullOrEmpty(musicTagCache.Genre) && !string.IsNullOrEmpty(cueSheetCache.Genre)) { musicTagCache.Genre = cueSheetCache.Genre; } // let tagged year override cuesheet year if (musicTagCache.Year == 0 && cueSheetCache.Year != 0) { musicTagCache.Year = cueSheetCache.Year; } // let tagged composer override cuesheet songwriter if (string.IsNullOrEmpty(musicTagCache.Composer) && !string.IsNullOrEmpty(cueSheetCache.Songwriter)) { musicTagCache.Composer = cueSheetCache.Songwriter; } // in case we were not able to read the file type via taglib, we will get it vai extension if (string.IsNullOrEmpty(musicTagCache.FileType)) { var extension = Path.GetExtension(fname); if (extension != null) { musicTagCache.FileType = extension.Substring(1).ToLowerInvariant(); } } musicTagCache.FileName = cueFakeTrackFileName; musicTagCache.Title = track.Title; musicTagCache.Track = track.TrackNumber; musicTagCache.TrackTotal = cueSheetCache.Tracks.Length; return(musicTagCache); } }
private void GetTrackTags() { if (CurrentTrackTag != null) { PreviousTrackTag = CurrentTrackTag; } bool isInternetStream = Util.Utils.IsAVStream(CurrentTrackFileName) && !Util.Utils.IsLastFMStream(CurrentTrackFileName); if (isInternetStream && _usingBassEngine) { NextTrackTag = null; return; } PlayListItem currentItem = PlaylistPlayer.GetCurrentItem(); PlayListItem nextItem = PlaylistPlayer.GetNextItem(); if (currentItem != null) { CurrentTrackTag = (MusicTag)currentItem.MusicTag; } else { CurrentTrackTag = null; } if (nextItem != null) { NextTrackTag = (MusicTag)nextItem.MusicTag; } else { NextTrackTag = null; } }
private void UpdateSimilarTrackWorker(string filename, MusicTag tag) { if (tag == null) return; lstSimilarTracks.Clear(); List<LastFMSimilarTrack> tracks; try { Log.Debug("GUIMusicPlayingNow: Calling Last.FM to get similar Tracks"); tracks = LastFMLibrary.GetSimilarTracks(tag.Title, tag.Artist); } catch (Exception ex) { Log.Error("Error getting similar tracks in now playing"); Log.Error(ex); return; } Log.Debug("GUIMusicPlayingNow: Number of similar tracks returned from Last.FM: {0}", tracks.Count); var dbTracks = GetSimilarTracksInDatabase(tracks); for (var i = 0; i < 3; i++) { if (dbTracks.Count > 0) { var trackNo = Randomizer.Next(0, dbTracks.Count); var song = dbTracks[trackNo]; var t = song.ToMusicTag(); var item = new GUIListItem { AlbumInfoTag = song, MusicTag = tag, IsFolder = false, Label = song.Title, Path = song.FileName }; item.AlbumInfoTag = song; item.MusicTag = t; GUIMusicBaseWindow.SetTrackLabels(ref item, MusicSort.SortMethod.Album); dbTracks.RemoveAt(trackNo); // remove song after adding to playlist to prevent the same sone being added twice if (g_Player.currentFileName != filename) return; // track has changed since request so ignore lstSimilarTracks.Add(item); } } Log.Debug("GUIMusicPlayingNow: Tracks returned after matching Last.FM results with database tracks: {0}", lstSimilarTracks.Count); }
/// <summary> /// Returns the Tags of an AV Stream /// </summary> /// <returns></returns> public MusicTag GetStreamTags() { MusicTag tag = new MusicTag(); if (_tagInfo == null) { return tag; } // So let's filter it out ourself string title = _tagInfo.title; int streamUrlIndex = title.IndexOf("';StreamUrl="); if (streamUrlIndex > -1) { title = _tagInfo.title.Substring(0, streamUrlIndex); } tag.Album = _tagInfo.album; tag.Artist = _tagInfo.artist; tag.Title = title; tag.Genre = _tagInfo.genre; try { tag.Year = Convert.ToInt32(_tagInfo.year); } catch (FormatException) { tag.Year = 0; } return tag; }
private void PlaybackStateChanged(object sender, BassAudioEngine.PlayState oldState, BassAudioEngine.PlayState newState) { if (_visParam.VisHandle != 0) { Log.Debug("SoniqueViz: BassPlayer_PlaybackStateChanged from {0} to {1}", oldState.ToString(), newState.ToString()); if (newState == BassAudioEngine.PlayState.Playing) { RenderStarted = false; trackTag = TagReader.TagReader.ReadTag(Bass.CurrentFile); if (trackTag != null) { _songTitle = String.Format("{0} - {1}", trackTag.Artist, trackTag.Title); } else { _songTitle = " "; } _mediaInfo.SongTitle = _songTitle; _mediaInfo.SongFile = Bass.CurrentFile; _OldCurrentFile = Bass.CurrentFile; BassVis.BASSVIS_SetPlayState(_visParam, BASSVIS_PLAYSTATE.Play); } else if (newState == BassAudioEngine.PlayState.Paused) { BassVis.BASSVIS_SetPlayState(_visParam, BASSVIS_PLAYSTATE.Pause); } else if (newState == BassAudioEngine.PlayState.Ended) { BassVis.BASSVIS_SetPlayState(_visParam, BASSVIS_PLAYSTATE.Stop); RenderStarted = false; } } }
/// <summary> /// Read MusicTag information from cueFakeTrack /// Not thread safe! /// </summary> /// <param name="cueFakeTrackFileName">Cue fake track file name</param> /// <returns>MusicTag filled with cue track information</returns> public static MusicTag CueFakeTrackFile2MusicTag(string cueFakeTrackFileName) { lock (cacheLock) { // This metod called twice for each one file. So, cache data! if (cueFakeTrackFileName == cueFakeTrackFileNameCache) { return(musicTagCache); } cueFakeTrackFileNameCache = cueFakeTrackFileName; // Cache CueSheet to pervent parsing it for each track in the album CueFakeTrack cueFakeTrack = parseCueFakeTrackFileName(cueFakeTrackFileName); if (cueSheetCacheFileNameCache != cueFakeTrack.CueFileName) { cueSheetCache = new CueSheet(cueFakeTrack.CueFileName); cueSheetCacheFileNameCache = cueFakeTrack.CueFileName; } int trackPosition = cueFakeTrack.TrackNumber - cueSheetCache.Tracks[0].TrackNumber; Track track = cueSheetCache.Tracks[trackPosition]; musicTagCache = new MusicTag(); if (track.TrackNumber < cueSheetCache.Tracks[cueSheetCache.Tracks.Length - 1].TrackNumber) { Track nextTrack = cueSheetCache.Tracks[trackPosition + 1]; musicTagCache.Duration = cueIndexToIntTime(nextTrack.Indices[0]) - cueIndexToIntTime(track.Indices[0]); } string fname = Path.Combine(Path.GetDirectoryName(cueFakeTrack.CueFileName), track.DataFile.Filename); try { if (fname != cacheFName) { tagCache = TagLib.File.Create(fname); } cacheFName = fname; musicTagCache.FileType = tagCache.MimeType; musicTagCache.Year = (int)tagCache.Tag.Year; musicTagCache.BitRate = tagCache.Properties.AudioBitrate; musicTagCache.DiscID = (int)tagCache.Tag.Disc; musicTagCache.DiscTotal = (int)tagCache.Tag.DiscCount; ; if (musicTagCache.Duration == 0) { musicTagCache.Duration = (int)tagCache.Properties.Duration.TotalSeconds - cueIndexToIntTime(track.Indices[0]); } } catch (Exception ex) { Log.Warn("CueFakeTrackFile2MusicTag: Exception reading file {0}. {1}", fname, ex.Message); } // In case of having a multi file Cue sheet, we're not able to get the duration // from the index entries. use MediaInfo then if (musicTagCache.Duration == 0) { try { MediaInfo mi = new MediaInfo(); mi.Open(fname); int durationms = 0; int.TryParse(mi.Get(StreamKind.General, 0, "Duration"), out durationms); musicTagCache.Duration = durationms / 1000; mi.Close(); } catch (Exception ex1) { Log.Warn("CueFakeTrackFile2MusicTag: Exception retrieving duration for file {0}. {1}", fname, ex1.Message); } } if (string.IsNullOrEmpty(musicTagCache.Artist)) { // if track has a performer set use this value for artist tag // else use global performer defined for cue sheet if (!string.IsNullOrEmpty(track.Performer)) { musicTagCache.Artist = track.Performer; } else { musicTagCache.Artist = cueSheetCache.Performer; } } if (string.IsNullOrEmpty(musicTagCache.Album)) { musicTagCache.Album = cueSheetCache.Title; } if (string.IsNullOrEmpty(musicTagCache.AlbumArtist)) { if (!string.IsNullOrEmpty(cueSheetCache.Performer)) { musicTagCache.AlbumArtist = cueSheetCache.Performer; musicTagCache.HasAlbumArtist = true; } else { musicTagCache.HasAlbumArtist = false; } } // let tagged genre override cuesheet genre if (string.IsNullOrEmpty(musicTagCache.Genre) && !string.IsNullOrEmpty(cueSheetCache.Genre)) { musicTagCache.Genre = cueSheetCache.Genre; } // let tagged year override cuesheet year if (musicTagCache.Year == 0 && cueSheetCache.Year != 0) { musicTagCache.Year = cueSheetCache.Year; } // let tagged composer override cuesheet songwriter if (string.IsNullOrEmpty(musicTagCache.Composer) && !string.IsNullOrEmpty(cueSheetCache.Songwriter)) { musicTagCache.Composer = cueSheetCache.Songwriter; } //musicTagCache.CoverArtImageBytes = pics[0].Data.Data; musicTagCache.FileName = cueFakeTrackFileName; musicTagCache.Title = track.Title; musicTagCache.Track = track.TrackNumber; musicTagCache.TrackTotal = cueSheetCache.Tracks.Length; return(musicTagCache); } }
private void UpdateVariousArtist(MusicTag tag) { string currentDir = Path.GetDirectoryName(tag.FileName); // on first cal, set the directory name if (_previousDirectory == null) { _previousDirectory = currentDir; } if (_previousMusicTag == null) { _previousMusicTag = tag; } if (_previousDirectory.ToLowerInvariant() == currentDir.ToLowerInvariant()) { // already have detected Various artists in this folder. no further checking needed if (_foundVariousArtist) { return; } // Is the Artist different and also no different AlbumArtist set? if (_previousMusicTag.Artist != tag.Artist && !tag.HasAlbumArtist) { _foundVariousArtist = true; return; } } else { if (_foundVariousArtist) { // Let's add the "Various Artist" to the albumArtist table string varArtist = "| Various Artists | "; strSQL = string.Format("insert into albumartist (strAlbumArtist) values('{0}')", varArtist); DirectExecute(strSQL); List<SongMap> songs = new List<SongMap>(); GetSongsByPath(_previousDirectory, ref songs); foreach (SongMap map in songs) { int id = map.m_song.Id; strSQL = string.Format("update tracks set strAlbumArtist = '| Various Artists | ' where idTrack={0}", id); DirectExecute(strSQL); // Now we need to remove the Artist of the song from the AlbumArtist table, // if he's not an AlbumArtist in a different album Song song = map.m_song as Song; string[] strAlbumArtistSplit = song.AlbumArtist.Split(new char[] {'|'}); foreach (string strTmp in strAlbumArtistSplit) { string strAlbumArtist = strTmp.Trim(trimChars); DatabaseUtility.RemoveInvalidChars(ref strAlbumArtist); strSQL = string.Format("select strAlbumArtist from tracks where strAlbumArtist like '%| {0} |%'", strAlbumArtist); if (DirectExecute(strSQL).Rows.Count < 1) { // No AlbumArtist entry found, so let's remove this artist from albumartist strSQL = String.Format("delete from albumartist where strAlbumArtist like '%{0}%'", strAlbumArtist); DirectExecute(strSQL); } } } } _previousMusicTag = tag; _previousDirectory = currentDir; _foundVariousArtist = false; } }
private void AddMultipleValueFields(MusicTag tag) { try { string strSQL; string strMultiValueFieldValue = ""; foreach (string field in _multipleValueFields) { // split up the multiple value field strMultiValueFieldValue = GetMultipleValueFieldValue(tag, field).Trim(new char[] {'|', ' '}); string[] splittedFields = strMultiValueFieldValue.Split(new char[] {';', '|'}); foreach (string s in splittedFields) { // ATTENTION: We need to use the 'like' operator instead of '=' to have case insensitive searching strSQL = String.Format("select {0} from {1} where {0} like '{2}'", GetMultipleValueField(field), GetMultipleValueTable(field), s == "" ? " " : s.Trim()); if (DirectExecute(strSQL).Rows.Count < 1) { // Insert the Artist strSQL = String.Format("insert into {1} ({0}) values ('{2}')", GetMultipleValueField(field), GetMultipleValueTable(field), s == "" ? " " : s.Trim()); DirectExecute(strSQL); } } } } catch (Exception ex) { Log.Error("Musicdatabase: Exception adding multiple field value: {0} stack: {1}", ex.Message, ex.StackTrace); Open(); } }
public static string GetCoverArt(bool isfolder, string filename, MusicTag tag) { string strAlbumName = string.Empty; string strArtistName = string.Empty; if (tag != null) { if (!string.IsNullOrEmpty(tag.Album)) { strAlbumName = tag.Album; } if (!string.IsNullOrEmpty(tag.Artist)) { strArtistName = tag.Artist; } } // attempt to pick up album thumb if already scanned string strThumb = Util.Utils.GetAlbumThumbName(strArtistName, strAlbumName); if (Util.Utils.FileExistsInCache(strThumb)) { if (_createMissingFolderThumbs && _createMissingFolderThumbCache) { string folderThumb = Util.Utils.GetFolderThumb(filename); if (!Util.Utils.FileExistsInCache(folderThumb)) { FolderThumbCreator thumbCreator = new FolderThumbCreator(filename, tag); } } return strThumb; } // attempt to load folder.jpg if (!Util.Utils.IsAVStream(filename)) { string strFolderThumb = string.Empty; if (isfolder) { strFolderThumb = Util.Utils.GetLocalFolderThumbForDir(filename); } else { strFolderThumb = Util.Utils.GetLocalFolderThumb(filename); } if (Util.Utils.FileExistsInCache(strFolderThumb)) { return strFolderThumb; } else { if (_createMissingFolderThumbCache) { FolderThumbCacher thumbworker = new FolderThumbCacher(filename, false); } } } //TODO: consider lookup of embedded artwork return string.Empty; }
protected void LoadPlayList(string strPlayList, bool startPlayback, bool isAsynch, bool defaultLoad) { IPlayListIO loader = PlayListFactory.CreateIO(strPlayList); if (loader == null) { return; } PlayList playlist = new PlayList(); if (!Util.Utils.FileExistsInCache(strPlayList)) { Log.Info("Playlist: Skipping non-existing Playlist file: {0}", strPlayList); return; } if (!loader.Load(playlist, strPlayList)) { if (isAsynch && defaultLoad) // we might not be in GUI yet! we have asynch and default load because we might want to use asynch loading from gui button too, later! throw new Exception(string.Format("Unable to load Playlist file: {0}", strPlayList)); // exception is handled in backgroundworker else TellUserSomethingWentWrong(); return; } if (_autoShuffleOnLoad) { playlist.Shuffle(); } playlistPlayer.CurrentPlaylistName = Path.GetFileNameWithoutExtension(strPlayList); if (playlist.Count == 1 && startPlayback) { Log.Info("GUIMusic:Play: play single playlist item - {0}", playlist[0].FileName); // Default to type Music, when a playlist has been selected from My Music g_Player.Play(playlist[0].FileName, g_Player.MediaType.Music); return; } if (null != bw && isAsynch && bw.CancellationPending) return; // clear current playlist //playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_MUSIC).Clear(); Song song = new Song(); PlayList newPlaylist = new PlayList(); // add each item of the playlist to the playlistplayer for (int i = 0; i < playlist.Count; ++i) { if (null != bw && isAsynch && bw.CancellationPending) return; PlayListItem playListItem = playlist[i]; m_database.GetSongByFileName(playListItem.FileName, ref song); MusicTag tag = new MusicTag(); tag = song.ToMusicTag(); playListItem.MusicTag = tag; if (Util.Utils.FileExistsInCache(playListItem.FileName) || playListItem.Type == PlayListItem.PlayListItemType.AudioStream) { newPlaylist.Add(playListItem); } else { Log.Info("Playlist: File {0} no longer exists. Skipping item.", playListItem.FileName); } } if (null != bw && isAsynch && bw.CancellationPending) return; ReplacePlaylist(newPlaylist); if (startPlayback) StartPlayingPlaylist(); }
public void ShowAlbumInfo(int parentWindowID, string artistName, string albumName, string strPath, MusicTag tag) { Log.Debug("Searching for album: {0} - {1}", albumName, artistName); var dlgProgress = (GUIDialogProgress)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_PROGRESS); var pDlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); var errorEncountered = true; var album = new AlbumInfo(); var albumInfo = new MusicAlbumInfo(); if (m_database.GetAlbumInfo(albumName, artistName, ref album)) { // we already have album info in database so just use that albumInfo.Set(album); errorEncountered = false; } else {// lookup details. start with artist if (null != pDlgOK && !Win32API.IsConnectedToInternet()) { pDlgOK.SetHeading(703); pDlgOK.SetLine(1, 703); pDlgOK.SetLine(2, string.Empty); pDlgOK.DoModal(GetID); return; } // show dialog box indicating we're searching the album if (dlgProgress != null) { dlgProgress.Reset(); dlgProgress.SetHeading(326); dlgProgress.SetLine(1, albumName); dlgProgress.SetLine(2, artistName); dlgProgress.SetPercentage(0); dlgProgress.StartModal(GetID); dlgProgress.Progress(); dlgProgress.ShowProgressBar(true); } var scraper = new AllmusicSiteScraper(); List<AllMusicArtistMatch> artists; var selectedMatch = new AllMusicArtistMatch(); if (scraper.GetArtists(artistName, out artists)) { if (null != dlgProgress) { dlgProgress.SetPercentage(20); dlgProgress.Progress(); } if (artists.Count == 1) { // only have single match so no need to ask user Log.Debug("Single Artist Match Found"); selectedMatch = artists[0]; } else { // need to get user to choose which one to use Log.Debug("Muliple Artist Match Found ({0}) prompting user", artists.Count); var pDlg = (GUIDialogSelect2) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_SELECT2); if (null != pDlg) { pDlg.Reset(); pDlg.SetHeading(GUILocalizeStrings.Get(1303)); foreach (var i in artists.Select(artistMatch => new GUIListItem { Label = artistMatch.Artist + " - " + artistMatch.Genre, Label2 = artistMatch.YearsActive, Path = artistMatch.ArtistUrl, IconImage = artistMatch.ImageUrl })) { pDlg.Add(i); } pDlg.DoModal(GetID); // and wait till user selects one var iSelectedMatch = pDlg.SelectedLabel; if (iSelectedMatch < 0) { return; } selectedMatch = artists[iSelectedMatch]; } if (null != dlgProgress) { dlgProgress.Reset(); dlgProgress.SetHeading(326); dlgProgress.SetLine(1, albumName); dlgProgress.SetLine(2, artistName); dlgProgress.SetPercentage(40); dlgProgress.StartModal(GetID); dlgProgress.ShowProgressBar(true); dlgProgress.Progress(); } } string strAlbumHtml; if (scraper.GetAlbumHtml(albumName, selectedMatch.ArtistUrl, out strAlbumHtml)) { if (null != dlgProgress) { dlgProgress.SetPercentage(60); dlgProgress.Progress(); } if (albumInfo.Parse(strAlbumHtml)) { if (null != dlgProgress) { dlgProgress.SetPercentage(80); dlgProgress.Progress(); } m_database.AddAlbumInfo(albumInfo.Get()); errorEncountered = false; } } } } if (null != dlgProgress) { dlgProgress.SetPercentage(100); dlgProgress.Progress(); dlgProgress.Close(); dlgProgress = null; } if (!errorEncountered) { var pDlgAlbumInfo = (GUIMusicInfo)GUIWindowManager.GetWindow((int)Window.WINDOW_MUSIC_INFO); if (null != pDlgAlbumInfo) { pDlgAlbumInfo.Album = albumInfo; pDlgAlbumInfo.Tag = tag; pDlgAlbumInfo.DoModal(parentWindowID); if (pDlgAlbumInfo.NeedsRefresh) { m_database.DeleteAlbumInfo(albumName, artistName); ShowAlbumInfo(parentWindowID, artistName, albumName, strPath, tag); return; } } } else { Log.Debug("No Album Found"); if (null != pDlgOK) { pDlgOK.SetHeading(187); pDlgOK.SetLine(1, 187); pDlgOK.SetLine(2, string.Empty); pDlgOK.DoModal(GetID); } } }
protected void ShowAlbumInfo(string artistName, string albumName, string strPath, MusicTag tag) { ShowAlbumInfo(GetID, artistName, albumName, strPath, tag); }
public void FindCoverArt(bool isFolder, string artistName, string albumName, string strPath, MusicTag tag, int albumId) { GUIDialogOK pDlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); if (null != pDlgOK && !Win32API.IsConnectedToInternet()) { pDlgOK.SetHeading(703); pDlgOK.SetLine(1, 703); pDlgOK.SetLine(2, string.Empty); pDlgOK.DoModal(GetID); //throw new Exception("no internet"); return; } else if (!Win32API.IsConnectedToInternet()) { //throw new Exception("no internet"); return; } bool bDisplayErr = false; GUIDialogOK dlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); AlbumInfo albuminfo = new AlbumInfo(); MusicAlbumInfo album = new MusicAlbumInfo(); GUICoverArtGrabberResults guiCoverGrabberResults = (GUICoverArtGrabberResults)GUIWindowManager.GetWindow((int)Window.WINDOW_MUSIC_COVERART_GRABBER_RESULTS); if (null != guiCoverGrabberResults) { guiCoverGrabberResults.SearchMode = GUICoverArtGrabberResults.SearchDepthMode.Album; GUIDialogProgress dlgProgress = (GUIDialogProgress)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_PROGRESS); if (dlgProgress != null) { dlgProgress.Reset(); dlgProgress.SetHeading(185); dlgProgress.SetLine(1, albumName); dlgProgress.SetLine(2, artistName); dlgProgress.SetLine(3, string.Empty); dlgProgress.StartModal(GetID); } guiCoverGrabberResults.GetAlbumCovers(artistName, albumName, strPath, GetID, true); guiCoverGrabberResults.DoModal(GetID); albuminfo = guiCoverGrabberResults.SelectedAlbum; if (GUICoverArtGrabberResults.CancelledByUser) { string line1Text = GUILocalizeStrings.Get(4507); if (line1Text.Length == 0) { line1Text = "Cover art grabber aborted by user"; } string caption = GUILocalizeStrings.Get(4511); if (caption.Length == 0) { caption = "Cover Art Grabber Done"; } if (null != dlgOk) { dlgOk.SetHeading(caption); dlgOk.SetLine(1, line1Text); dlgOk.SetLine(2, string.Empty); dlgOk.DoModal(GetID); } } else if (albuminfo != null) { // the GUICoverArtGrabberResults::SelectedAlbum AlbumInfo object contains // the Artist and Album name returned by the Amazon Webservice which may not // match our original artist and album. We want to use the original artist // and album name... albuminfo.Artist = artistName; albuminfo.Album = albumName; SaveCoverArtImage(albuminfo, strPath, true, true); facadeLayout.RefreshCoverArt(); } else { bDisplayErr = true; } } if (bDisplayErr) { if (null != dlgOk) { dlgOk.SetHeading(187); dlgOk.SetLine(1, 187); dlgOk.SetLine(2, string.Empty); dlgOk.DoModal(GetID); } } }
private static string BuildAutoDJFilter(string filterMask, MusicTag tag) { var filter = filterMask; try { if (!string.IsNullOrEmpty(tag.Genre)) { filter = filter.Replace("{genre}", "'" + tag.Genre + "'"); } if (!string.IsNullOrEmpty(tag.Album)) { filter = filter.Replace("{album}", "'" + tag.Album + "'"); } if (!string.IsNullOrEmpty(tag.AlbumArtist)) { filter = filter.Replace("{albumartist}", "'" + tag.AlbumArtist + "'"); } if (!string.IsNullOrEmpty(tag.Artist)) { filter = filter.Replace("{albumartist}", "'" + tag.Artist + "'"); } if (tag.Year > 0) { filter = filter.Replace("{year}", tag.Year.ToString(CultureInfo.InvariantCulture)); } if (tag.Rating > 0) { filter = filter.Replace("{rating}", tag.Rating.ToString(CultureInfo.InvariantCulture)); } if (tag.BPM > 0) { filter = filter.Replace("{BPM}", tag.BPM.ToString(CultureInfo.InvariantCulture)); } } catch (Exception ex) { Log.Debug("Applying filter failed: {0}, exception {1}", filter, ex); } return filter; }
public MusicTag ToMusicTag() { MusicTag tmpTag = new MusicTag(); tmpTag.Title = this.Title; tmpTag.Album = this.Album; tmpTag.DiscID = this.DiscId; tmpTag.DiscTotal = this.DiscTotal; tmpTag.AlbumArtist = this.AlbumArtist; tmpTag.Artist = this.Artist; tmpTag.Duration = this.Duration; tmpTag.Genre = this.Genre; tmpTag.Composer = this.Composer; tmpTag.Conductor = this.Conductor; tmpTag.Track = this.Track; tmpTag.TrackTotal = this.TrackTotal; tmpTag.Year = this.Year; tmpTag.Rating = this.Rating; tmpTag.TimesPlayed = this.TimesPlayed; tmpTag.Lyrics = this.Lyrics; tmpTag.DateTimeModified = this.DateTimeModified; tmpTag.DateTimePlayed = this.DateTimePlayed; tmpTag.Comment = this.Comment; tmpTag.FileType = this.FileType; tmpTag.Codec = this.Codec; tmpTag.BitRateMode = this.BitRateMode; tmpTag.BPM = this.BPM; tmpTag.BitRate = this.BitRate; tmpTag.Channels = this.Channels; tmpTag.SampleRate = this.SampleRate; tmpTag.HasAlbumArtist = string.IsNullOrEmpty(this.AlbumArtist); return tmpTag; }
private bool AddRandomSongToPlaylist(ref Song song) { //check duplication PlayList playlist = playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_MUSIC); for (int i = 0; i < playlist.Count; i++) { PlayListItem item = playlist[i]; if (item.FileName == song.FileName) { return false; } } //add to playlist PlayListItem playlistItem = new PlayListItem(); playlistItem.Type = PlayListItem.PlayListItemType.Audio; StringBuilder sb = new StringBuilder(); playlistItem.FileName = song.FileName; sb.Append(song.Track); sb.Append(". "); sb.Append(song.Artist); sb.Append(" - "); sb.Append(song.Title); playlistItem.Description = sb.ToString(); playlistItem.Duration = song.Duration; MusicTag tag = new MusicTag(); tag = song.ToMusicTag(); playlistItem.MusicTag = tag; playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_MUSIC).Add(playlistItem); return true; }
private void ExtractCoverArt(MusicTag tag) { string formattedAlbum = tag.Album.Trim(trimChars); // Mantis 3078: Filename for Multiple Artists should not contain a semicolon, cause it wouldn't be found later on int i = 0; string formattedArtist = ""; string[] strArtistSplit = tag.Artist.Split(new char[] {';', '|'}); foreach (string strArtist in strArtistSplit) { string s = strArtist.Trim(); if (_stripArtistPrefixes) { Util.Utils.StripArtistNamePrefix(ref s, true); } // Concatenate multiple Artists with " _ " // When we search for multiple artists Covers: "artist a | artist b", the string " | " gets replaced by " _ ", // so we need to build the file accordingly if (i > 0) { formattedArtist += " _ "; } formattedArtist += s.Trim(); i++; } string tagAlbumName = string.Format("{0}-{1}", formattedArtist, formattedAlbum); string smallThumbPath = Util.Utils.GetCoverArtName(Thumbs.MusicAlbum, Util.Utils.MakeFileName(tagAlbumName)); string largeThumbPath = Util.Utils.GetLargeCoverArtName(Thumbs.MusicAlbum, Util.Utils.MakeFileName(tagAlbumName)); // Get the cover image directly out of the mp3 file's ID3 tag if (_extractEmbededCoverArt) { try { if (tag.CoverArtImageBytes != null) { bool extractFile = false; if (!Util.Utils.FileExistsInCache(smallThumbPath)) { extractFile = true; } else { // Prevent creation of the thumbnail multiple times, when all songs of an album contain coverart <-- that's ugly (rtv) try { DateTime fileDate = File.GetLastWriteTime(smallThumbPath); TimeSpan span = _currentDate - fileDate; if (span.Days > 0) { extractFile = true; } } catch (Exception) { extractFile = true; } } if (extractFile) { try { string mp3TagImage = tag.CoverArtFile; if (!String.IsNullOrEmpty(mp3TagImage)) { if ( !Util.Picture.CreateThumbnail(mp3TagImage, smallThumbPath, (int)Thumbs.ThumbResolution, (int)Thumbs.ThumbResolution, 0, Thumbs.SpeedThumbsSmall)) { Log.Info("MusicDatabase: Could not extract thumbnail from {0}", tag.FileName); } if ( !Util.Picture.CreateThumbnail(mp3TagImage, largeThumbPath, (int)Thumbs.ThumbLargeResolution, (int)Thumbs.ThumbLargeResolution, 0, Thumbs.SpeedThumbsLarge)) { Log.Info("MusicDatabase: Could not extract thumbnail from {0}", tag.FileName); } Util.Utils.FileDelete(mp3TagImage); // clean up the temp file directly } } catch (Exception) { Log.Warn("MusicDatabase: Invalid cover art image found in {0}-{1}! {2}", tag.Artist, tag.Title, tag.FileName); } } } } catch (Exception) {} } // Scan folders only one time per song if (string.IsNullOrEmpty(_previousNegHitDir) || (Path.GetDirectoryName(tag.FileName) != _previousNegHitDir)) { string sharefolderThumb; // no mp3 coverart - use folder art if present to get an album thumb if (_useFolderThumbs) { // Do not overwrite covers extracted from mp3 files. if (!Util.Utils.FileExistsInCache(smallThumbPath)) { // No Album thumb found - create one. bool foundThumb = false; if (_useAllImages) { sharefolderThumb = Util.Utils.TryEverythingToGetFolderThumbByFilename(tag.FileName, true); if (string.IsNullOrEmpty(sharefolderThumb)) { _previousNegHitDir = Path.GetDirectoryName(tag.FileName); //Log.Debug("MusicDatabase: No useable album art images found in {0}", _previousNegHitDir); } else { _previousNegHitDir = string.Empty; foundThumb = true; } } else { sharefolderThumb = Util.Utils.GetFolderThumb(tag.FileName); if (Util.Utils.FileExistsInCache(sharefolderThumb)) { foundThumb = true; } } if (foundThumb) { if ( !Util.Picture.CreateThumbnail(sharefolderThumb, smallThumbPath, (int)Thumbs.ThumbResolution, (int)Thumbs.ThumbResolution, 0, Thumbs.SpeedThumbsSmall)) { Log.Info("MusicDatabase: Could not create album thumb from folder {0}", tag.FileName); } if ( !Util.Picture.CreateThumbnail(sharefolderThumb, largeThumbPath, (int)Thumbs.ThumbLargeResolution, (int)Thumbs.ThumbLargeResolution, 0, Thumbs.SpeedThumbsLarge)) { Log.Info("MusicDatabase: Could not create large album thumb from folder {0}", tag.FileName); } } } } // MP has an album cover in the thumb cache (maybe downloaded from last.fm) but no folder.jpg in the shares - create it if (_createMissingFolderThumbs) { if (string.IsNullOrEmpty(_previousPosHitDir) || (Path.GetDirectoryName(tag.FileName) != _previousPosHitDir)) { sharefolderThumb = Util.Utils.GetFolderThumb(tag.FileName); if (!Util.Utils.FileExistsInCache(sharefolderThumb)) { string sourceCover = Util.Utils.TryEverythingToGetFolderThumbByFilename(tag.FileName, true); if (string.IsNullOrEmpty(sourceCover)) { sourceCover = smallThumbPath; } if (Util.Utils.FileExistsInCache(Util.Utils.ConvertToLargeCoverArt(sourceCover))) { sourceCover = Util.Utils.ConvertToLargeCoverArt(sourceCover); } if (Util.Utils.FileExistsInCache(sourceCover)) { _previousPosHitDir = Path.GetDirectoryName(tag.FileName); //FolderThumbCreator newThumb = new FolderThumbCreator(tag.FileName, tag); if ( !Util.Picture.CreateThumbnail(sourceCover, sharefolderThumb, (int)Thumbs.ThumbLargeResolution, (int)Thumbs.ThumbLargeResolution, 0, Thumbs.SpeedThumbsLarge)) { Log.Info("MusicDatabase: Could not create missing folder thumb in share path {0}", sharefolderThumb); } Thread.Sleep(1); } } } } } }
private void ShowSong(string filename) { GUIDialogNotify dlg = (GUIDialogNotify) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_NOTIFY); if (dlg == null) { return; } //get albumart string albumart = g_Player.CurrentFile; int e = albumart.LastIndexOf(@"\") + 1; albumart = albumart.Remove(e); if (_slideList[_currentSlideIndex].Contains(albumart)) { albumart = string.Empty; } else { albumart = Util.Utils.GetFolderThumbForDir(albumart); if (!Util.Utils.FileExistsInCache(albumart)) { albumart = string.Empty; } } // get Song-info // hwahrmann 2006-11-22 Using the Tagreader caused a COM exception in Win Media SDK, when reading WMA files // Accessing the Music Database instead of using the Tagreader. //MediaPortal.TagReader.MusicTag tag = MediaPortal.TagReader.TagReader.ReadTag(g_Player.CurrentFile); Song song = new Song(); MusicTag currentSong = new MusicTag(); // If we don't have a tag in the db, we use the filename without the extension as song.title if (!mDB.GetSongByFileName(g_Player.CurrentFile, ref song)) { try { // try Tagreader method to parse information var pl = PlayListPlayer.SingletonPlayer.GetPlaylist(PlayListPlayer.SingletonPlayer.CurrentPlaylistType); var plI = pl.First(plItem => plItem.FileName == filename); if (plI != null || plI.MusicTag != null) { currentSong = (MusicTag)plI.MusicTag; } } catch (Exception) { // Catch the COM execption but continue code with Music Database instead. } } // Show Dialog dlg.Reset(); dlg.Dispose(); dlg.SetImage(albumart); dlg.SetHeading(4540); if (currentSong == null || string.IsNullOrEmpty(currentSong.Title) || (string.IsNullOrEmpty(currentSong.Artist) && string.IsNullOrEmpty(currentSong.AlbumArtist))) { song.Title = Path.GetFileNameWithoutExtension(g_Player.CurrentFile); dlg.SetText(song.Title + "\n" + song.Artist + "\n" + song.Album); } else { dlg.SetText(currentSong.Title + "\n" + currentSong.Artist + "\n" + currentSong.Album); } dlg.TimeOut = 5; dlg.DoModal(GUIWindowManager.ActiveWindow); }
/// <summary> /// Returns the field value out of the MusicTag /// </summary> /// <param name="tag"></param> /// <param name="field"></param> /// <returns></returns> private string GetMultipleValueFieldValue(MusicTag tag, string field) { if (field == "artist") { return tag.Artist; } else if (field == "albumartist") { return tag.AlbumArtist; } else if (field == "genre") { return tag.Genre; } else if (field == "composer") { return tag.Composer; } return ""; }
public MusicTag ToMusicTag() { var tmpTag = new MusicTag { Title = this.Title, Album = this.Album, DiscID = this.DiscId, DiscTotal = this.DiscTotal, AlbumArtist = this.AlbumArtist, Artist = this.Artist, Duration = this.Duration, Genre = this.Genre, Composer = this.Composer, Conductor = this.Conductor, Track = this.Track, TrackTotal = this.TrackTotal, Year = this.Year, Rating = this.Rating, TimesPlayed = this.TimesPlayed, Lyrics = this.Lyrics, DateTimeModified = this.DateTimeModified, DateTimePlayed = this.DateTimePlayed, Comment = this.Comment, FileType = this.FileType, Codec = this.Codec, BitRateMode = this.BitRateMode, BPM = this.BPM, BitRate = this.BitRate, Channels = this.Channels, SampleRate = this.SampleRate, HasAlbumArtist = string.IsNullOrEmpty(this.AlbumArtist) }; return tmpTag; }
public override int RenderVisualization() { try { if (VisualizationWindow == null || !VisualizationWindow.Visible || _visParam.VisHandle == 0) { return 0; } // Any is wrong with PlaybackStateChanged, if the songfile automatically changed // so i have create a new variable which fix this problem if (Bass != null) { if ((Bass.CurrentFile != _OldCurrentFile) && !Bass.IsRadio) { trackTag = TagReader.TagReader.ReadTag(Bass.CurrentFile); if (trackTag != null) { _songTitle = String.Format("{0} - {1}", trackTag.Artist, trackTag.Title); _OldCurrentFile = Bass.CurrentFile; } else { _songTitle = " "; } } // Set Song information, so that the plugin can display it if (trackTag != null && !Bass.IsRadio) { _mediaInfo.SongTitle = _songTitle; _mediaInfo.SongFile = Bass.CurrentFile; _mediaInfo.Position = (int)(1000 * Bass.CurrentPosition); _mediaInfo.Duration = (int)Bass.Duration; } else { if (Bass.IsRadio) { // Change TrackTag to StreamTag for Radio trackTag = Bass.GetStreamTags(); if (trackTag != null) { // Artist and Title show better i think _songTitle = trackTag.Artist + ": " + trackTag.Title; _mediaInfo.SongTitle = _songTitle; } else { _songTitle = " "; } _mediaInfo.Position = (int)(1000 * Bass.CurrentPosition); } else { _mediaInfo.Position = 0; _mediaInfo.Duration = 0; } } } if (IsPreviewVisualization) { _mediaInfo.SongTitle = "Mediaportal Preview"; } BassVis.BASSVIS_SetInfo(_visParam, _mediaInfo); if (RenderStarted) { return 1; } int stream = 0; if (Bass != null) { stream = (int) Bass.GetCurrentVizStream(); } // ckeck is playing int nReturn = BassVis.BASSVIS_SetPlayState(_visParam, BASSVIS_PLAYSTATE.IsPlaying); if (nReturn == Convert.ToInt32(BASSVIS_PLAYSTATE.Play) && (_visParam.VisHandle != 0)) { // Do not Render without playing if (MusicPlayer.BASS.Config.MusicPlayer == AudioPlayer.WasApi) { RenderStarted = BassVis.BASSVIS_RenderChannel(_visParam, stream, true); } else { RenderStarted = BassVis.BASSVIS_RenderChannel(_visParam, stream, false); } } } catch (Exception) {} return 1; }
/// <summary> /// Scrobble track to last.fm /// </summary> /// <param name="tag">tag details of track to scrobble</param> /// <param name="stoptime">how long song had played for</param> /// <exception cref="ArgumentNullException">Tag must be provided</exception> public static void ScrobbleTrack(MusicTag tag, int stoptime) { if (tag == null) { throw new ArgumentNullException("tag"); } if (string.IsNullOrEmpty(tag.Title)) { Log.Info("Unable to scrobble: {0}", tag.FileName); Log.Info("No title for track"); return; } var artist = tag.Artist; if (string.IsNullOrEmpty(artist)) { if (string.IsNullOrEmpty(tag.AlbumArtist)) { Log.Info("Unable to scrobble: {0}", tag.FileName); Log.Info("No artist or album artist found"); return; } artist = tag.AlbumArtist; } if (tag.Duration < 30) { // last.fm say not to scrobble songs that last less than 30 seconds return; } if (stoptime < 120 && stoptime < (tag.Duration / 2)) { // last.fm say only to scrobble is more than 2 minutes has been listned to or // at least hald the duration of the song return; } try { using (var client = new WebClient()) using (var stream = client.OpenRead("http://www.google.com")) { Log.Debug("internet connection detected. to scrobble: {0} - {1}", tag.Title, artist); } } catch { CacheScrobble(tag, DateTime.UtcNow); Log.Info("No internet connection so unable to scrobble: {0} - {1}", tag.Title, artist); Log.Info("Scrobble has been cached"); return; } try { LastFMLibrary.Scrobble(artist, tag.Title, tag.Album); Log.Info("Last.fm scrobble: {0} - {1}", tag.Title, artist); } catch (LastFMException ex) { if (ex.LastFMError == LastFMException.LastFMErrorCode.ServiceOffline || ex.LastFMError == LastFMException.LastFMErrorCode.ServiceUnavailable) { CacheScrobble(tag, DateTime.UtcNow); Log.Info("Unable to scrobble: {0} - {1}", tag.Title, artist); Log.Info("Scrobble has been cached"); } else { Log.Error("Unable to scrobble: {0} - {1}", tag.Title, artist); Log.Error(ex); } } }
/// <summary> /// This method is called by mediaportal when it wants information for a music file /// The method will check which tagreader supports the file and ask it to extract the information from it /// </summary> /// <param name="strFile">filename of the music file</param> /// <returns> /// MusicTag instance when file has been read /// null when file type is not supported or if the file does not contain any information /// </returns> public static MusicTag ReadTag(string strFile) { // Read Cue info if (CueUtil.isCueFakeTrackFile(strFile)) { try { return(CueUtil.CueFakeTrackFile2MusicTag(strFile)); } catch (Exception ex) { Log.Warn("TagReader: Exception reading file {0}. {1}", strFile, ex.Message); } } if (!IsAudio(strFile)) { return(null); } char[] trimChars = { ' ', '\x00' }; try { // Set the flag to use the standard System Encoding set by the user // Otherwise Latin1 is used as default, which causes characters in various languages being displayed wrong TagLib.ByteVector.UseBrokenLatin1Behavior = true; TagLib.File tag = TagLib.File.Create(strFile); if (tag == null) { Log.Warn("Tagreader: No tag in file - {0}", strFile); return(null); } MusicTag musictag = new MusicTag(); string[] artists = tag.Tag.Performers; if (artists.Length > 0) { musictag.Artist = String.Join(";", artists).Trim(trimChars); // The AC/DC exception if (musictag.Artist.Contains("AC;DC")) { musictag.Artist = musictag.Artist.Replace("AC;DC", "AC/DC"); } } musictag.Album = tag.Tag.Album == null ? "" : tag.Tag.Album.Trim(trimChars); musictag.HasAlbumArtist = false; string[] albumartists = tag.Tag.AlbumArtists; if (albumartists.Length > 0) { musictag.AlbumArtist = String.Join(";", albumartists).Trim(trimChars); musictag.HasAlbumArtist = true; // The AC/DC exception if (musictag.AlbumArtist.Contains("AC;DC")) { musictag.AlbumArtist = musictag.AlbumArtist.Replace("AC;DC", "AC/DC"); } } musictag.BitRate = tag.Properties.AudioBitrate; musictag.Comment = tag.Tag.Comment == null ? "" : tag.Tag.Comment.Trim(trimChars); string[] composer = tag.Tag.Composers; if (composer.Length > 0) { musictag.Composer = string.Join(";", composer).Trim(trimChars); } musictag.Conductor = tag.Tag.Conductor == null ? "" : tag.Tag.Conductor.Trim(trimChars); IPicture[] pics = new IPicture[] { }; pics = tag.Tag.Pictures; if (pics.Length > 0) { musictag.CoverArtImageBytes = pics[0].Data.Data; } musictag.Duration = (int)tag.Properties.Duration.TotalSeconds; musictag.FileName = strFile; musictag.FileType = tag.MimeType.Substring(tag.MimeType.IndexOf("/") + 1); string[] genre = tag.Tag.Genres; if (genre.Length > 0) { musictag.Genre = String.Join(";", genre).Trim(trimChars); } string lyrics = tag.Tag.Lyrics == null ? "" : tag.Tag.Lyrics.Trim(trimChars); musictag.Title = tag.Tag.Title == null ? "" : tag.Tag.Title.Trim(trimChars); // Prevent Null Ref execption, when Title is not set musictag.Track = (int)tag.Tag.Track; musictag.TrackTotal = (int)tag.Tag.TrackCount; musictag.DiscID = (int)tag.Tag.Disc; musictag.DiscTotal = (int)tag.Tag.DiscCount; musictag.Codec = tag.Properties.Description; if (tag.MimeType == "taglib/mp3") { musictag.BitRateMode = tag.Properties.Description.IndexOf("VBR") > -1 ? "VBR" : "CBR"; } else { musictag.BitRateMode = ""; } musictag.BPM = (int)tag.Tag.BeatsPerMinute; musictag.Channels = tag.Properties.AudioChannels; musictag.SampleRate = tag.Properties.AudioSampleRate; musictag.Year = (int)tag.Tag.Year; musictag.ReplayGainTrack = tag.Tag.ReplayGainTrack ?? ""; musictag.ReplayGainTrackPeak = tag.Tag.ReplayGainTrackPeak ?? ""; musictag.ReplayGainAlbum = tag.Tag.ReplayGainAlbum ?? ""; musictag.ReplayGainAlbumPeak = tag.Tag.ReplayGainAlbumPeak ?? ""; if (tag.MimeType == "taglib/mp3") { bool foundPopm = false; // Handle the Rating, which comes from the POPM frame TagLib.Id3v2.Tag id32_tag = tag.GetTag(TagLib.TagTypes.Id3v2) as TagLib.Id3v2.Tag; if (id32_tag != null) { // Do we have a POPM frame written by MediaPortal or MPTagThat? TagLib.Id3v2.PopularimeterFrame popmFrame = TagLib.Id3v2.PopularimeterFrame.Get(id32_tag, "MediaPortal", false); if (popmFrame == null) { popmFrame = TagLib.Id3v2.PopularimeterFrame.Get(id32_tag, "MPTagThat", false); } if (popmFrame != null) { musictag.Rating = popmFrame.Rating; foundPopm = true; } // Now look for a POPM frame written by WMP if (!foundPopm) { TagLib.Id3v2.PopularimeterFrame popm = TagLib.Id3v2.PopularimeterFrame.Get(id32_tag, "Windows Media Player 9 Series", false); if (popm != null) { // Get the rating stored in the WMP POPM frame int rating = popm.Rating; int i = 0; if (rating == 255) { i = 5; } else if (rating == 196) { i = 4; } else if (rating == 128) { i = 3; } else if (rating == 64) { i = 2; } else if (rating == 1) { i = 1; } musictag.Rating = i; foundPopm = true; } } if (!foundPopm) { // Now look for any other POPM frame that might exist foreach (TagLib.Id3v2.PopularimeterFrame popm in id32_tag.GetFrames <TagLib.Id3v2.PopularimeterFrame>()) { int rating = popm.Rating; int i = 0; if (rating > 205 || rating == 5) { i = 5; } else if (rating > 154 || rating == 4) { i = 4; } else if (rating > 104 || rating == 3) { i = 3; } else if (rating > 53 || rating == 2) { i = 2; } else if (rating > 0 || rating == 1) { i = 1; } musictag.Rating = i; foundPopm = true; break; // we only take the first popm frame } } if (!foundPopm) { // If we don't have any POPM frame, we might have an APE Tag embedded in the mp3 file TagLib.Ape.Tag apetag = tag.GetTag(TagTypes.Ape, false) as TagLib.Ape.Tag; if (apetag != null) { TagLib.Ape.Item apeItem = apetag.GetItem("RATING"); if (apeItem != null) { string rating = apeItem.ToString(); try { musictag.Rating = Convert.ToInt32(rating); } catch (Exception ex) { musictag.Rating = 0; Log.Warn("Tagreader: Unsupported APE rating format - {0} in {1} {2}", rating, strFile, ex.Message); } } } } } } else { if (tag.MimeType == "taglib/ape") { TagLib.Ape.Tag apetag = tag.GetTag(TagTypes.Ape, false) as TagLib.Ape.Tag; if (apetag != null) { TagLib.Ape.Item apeItem = apetag.GetItem("RATING"); if (apeItem != null) { string rating = apeItem.ToString(); try { musictag.Rating = Convert.ToInt32(rating); } catch (Exception ex) { musictag.Rating = 0; Log.Warn("Tagreader: Unsupported APE rating format - {0} in {1} {2}", rating, strFile, ex.Message); } } } } } // if we didn't get a title, use the Filename without extension to prevent the file to appear as "unknown" if (musictag.Title == "") { Log.Warn("TagReader: Empty Title found in file: {0}. Please retag.", strFile); musictag.Title = System.IO.Path.GetFileNameWithoutExtension(strFile); } return(musictag); } catch (UnsupportedFormatException) { Log.Warn("Tagreader: Unsupported File Format {0}", strFile); } catch (Exception ex) { Log.Warn("TagReader: Exception reading file {0}. {1}", strFile, ex.Message); } return(null); }
/// <summary> /// Cache scrobble to submit to last.fm later /// </summary> /// <param name="tag">tag details of track being scrobbled</param> /// <param name="dtPlayed">When track was played</param> public static void CacheScrobble(MusicTag tag, DateTime dtPlayed) { var artist = tag.Artist ?? tag.AlbumArtist; CacheScrobble(artist, tag.Title, tag.Album, true, DateTime.UtcNow); }
private void Refresh() { if (coverArtTexture != null) { coverArtTexture.Dispose(); coverArtTexture = null; } string thumbNailFileName; string imageFileName = albumInfo.ImageURL; if (m_tag == null) { m_tag = new MusicTag(); m_tag.Artist = albumInfo.Artist; m_tag.Album = albumInfo.Title; } thumbNailFileName = Util.Utils.GetAlbumThumbName(m_tag.Artist, m_tag.Album); if (!Util.Utils.FileExistsInCache(thumbNailFileName)) { // Download image and save as // permanent thumb Util.Utils.DownLoadImage(imageFileName, thumbNailFileName); } if (Util.Utils.FileExistsInCache(thumbNailFileName)) { coverArtTexture = Util.Picture.Load(thumbNailFileName, 0, 128, 128, true, false, out coverArtTextureWidth, out coverArtTextureHeight); //imgCoverArt.Dispose(); //imgCoverArt.AllocResources(); } Update(); }
/// <summary> /// Handles AutoDJ details of identifying similar tracks and choosing which to add to playlist /// </summary> /// <param name="tag">Tag of track to lookup</param> public static void AutoDJ(MusicTag tag) { // try and match similar track to one being played var tracks = GetSimilarTracks(tag); if (LocalTracksAdded(tracks, tag)) { return; } // no match so lets attempt to lookup similar tracks based on artists top tracks Log.Debug("Unable to match similar tracks for {0} - {1} : trying similar tracks for top artist tracks", tag.Artist, tag.Title); tracks = GetArtistTopTracks(tag.Artist); var i = 0; if (tracks != null) { foreach (var lastFmTrack in tracks) { if (i == 5) { // only check at most 5 tracks to prevent flooding last.fm with requests break; } var lastFmTag = new MusicTag {Artist = lastFmTrack.ArtistName, Title = lastFmTrack.TrackTitle}; tracks = GetSimilarTracks(lastFmTag); if (LocalTracksAdded(tracks, tag)) { return; } i++; } } // still no match so lets just try and match top artist tracks Log.Debug("Unable to match similar top artist tracks for {0} : trying top artist tracks", tag.Artist); tracks = GetArtistTopTracks(tag.Artist); if (LocalTracksAdded(tracks, tag)) { return; } Log.Info("Auto DJ: Unable to match any tracks for {0} - {1}", tag.Artist, tag.Title); }
protected override void OnPageLoad() { base.OnPageLoad(); // Get notification, that an Internet Stream has changed // Moved out of the constructor, since it would cause loading of BASS in the Main thread, // because it is called by the Plugin Manager if (BassAudioEngine._initialized) { BassMusicPlayer.Player.InternetStreamSongChanged += OnInternetStreamSongChanged; } ImagePathContainer.Clear(); _trackChanged = true; GUIPropertyManager.SetProperty("#currentmodule", String.Format("{0}/{1}", GUILocalizeStrings.Get(100005), GUILocalizeStrings.Get(4540))); if (LblUpNext != null) { LblUpNext.Label = GUILocalizeStrings.Get(4541); } if (GUIPropertyManager.GetProperty("#Play.Next.Title") == string.Empty && LblUpNext != null) { LblUpNext.Visible = false; } ControlsInitialized = true; if (ImageChangeTimer == null) { ImageChangeTimer = new Timer(); ImageChangeTimer.Interval = 3600 * 1000; ImageChangeTimer.Elapsed += new ElapsedEventHandler(OnImageTimerTickEvent); ImageChangeTimer.Start(); } // Start the VUMeter Update Timer, when it is enabled in skin file GUIPropertyManager.SetProperty("#VUMeterL", @"VU1.png"); GUIPropertyManager.SetProperty("#VUMeterR", @"VU1.png"); if (VUMeterTimer == null && _usingBassEngine && _vuMeter.ToLowerInvariant() != "none") { VUMeterTimer = new Timer(); VUMeterTimer.Interval = 10; VUMeterTimer.Elapsed += new ElapsedEventHandler(OnVUMterTimerTickEvent); VUMeterTimer.Start(); } UpdateImagePathContainer(); if (g_Player.Playing) { OnPlayBackStarted(g_Player.MediaType.Music, g_Player.CurrentFile); _isStopped = false; } else { CurrentTrackTag = null; NextTrackTag = null; UpdateTrackInfo(); } }
/// <summary> /// Checks last.fm for similar tracks and handle any errors that might occur /// </summary> /// <param name="tag">MusicTag of file to check</param> /// <returns>Similar tracks as defined by last.fm or null</returns> private static IEnumerable<LastFMSimilarTrack> GetSimilarTracks(MusicTag tag) { IEnumerable<LastFMSimilarTrack> tracks; try { tracks = LastFMLibrary.GetSimilarTracks(tag.Title, tag.Artist); } catch (LastFMException ex) { if (ex.LastFMError == LastFMException.LastFMErrorCode.InvalidParameters) { Log.Debug("AutoDJ: Unable to get similar track for : {0} - {1}", tag.Artist, tag.Title); Log.Debug("AutoDJ: {0}", ex.Message); } else { Log.Error("Error in Last.fm AutoDJ - getting similar tracks"); Log.Error(ex); } return null; } catch (Exception ex) { Log.Error("Error in Last.fm AutoDJ - getting similar tracks"); Log.Error(ex); return null; } return tracks; }
/// <summary> /// This method is called by mediaportal when it wants information for a music file /// The method will check which tagreader supports the file and ask it to extract the information from it /// </summary> /// <param name="strFile">filename of the music file</param> /// <returns> /// MusicTag instance when file has been read /// null when file type is not supported or if the file does not contain any information /// </returns> public static MusicTag ReadTag(string strFile) { // Read Cue info if (CueUtil.isCueFakeTrackFile(strFile)) { try { return CueUtil.CueFakeTrackFile2MusicTag(strFile); } catch (Exception ex) { Log.Warn("TagReader: Exception reading file {0}. {1}", strFile, ex.Message); } } if (!IsAudio(strFile)) return null; char[] trimChars = { ' ', '\x00' }; try { // Set the flag to use the standard System Encoding set by the user // Otherwise Latin1 is used as default, which causes characters in various languages being displayed wrong TagLib.ByteVector.UseBrokenLatin1Behavior = true; TagLib.File tag = TagLib.File.Create(strFile); if (tag == null) { Log.Warn("Tagreader: No tag in file - {0}", strFile); return null; } MusicTag musictag = new MusicTag(); string[] artists = tag.Tag.Performers; if (artists.Length > 0) { musictag.Artist = String.Join(";", artists).Trim(trimChars); // The AC/DC exception if (musictag.Artist.Contains("AC;DC")) { musictag.Artist = musictag.Artist.Replace("AC;DC", "AC/DC"); } } musictag.Album = tag.Tag.Album == null ? "" : tag.Tag.Album.Trim(trimChars); musictag.HasAlbumArtist = false; string[] albumartists = tag.Tag.AlbumArtists; if (albumartists.Length > 0) { musictag.AlbumArtist = String.Join(";", albumartists).Trim(trimChars); musictag.HasAlbumArtist = true; // The AC/DC exception if (musictag.AlbumArtist.Contains("AC;DC")) { musictag.AlbumArtist = musictag.AlbumArtist.Replace("AC;DC", "AC/DC"); } } musictag.BitRate = tag.Properties.AudioBitrate; musictag.Comment = tag.Tag.Comment == null ? "" : tag.Tag.Comment.Trim(trimChars); string[] composer = tag.Tag.Composers; if (composer.Length > 0) { musictag.Composer = string.Join(";", composer).Trim(trimChars); } musictag.Conductor = tag.Tag.Conductor == null ? "" : tag.Tag.Conductor.Trim(trimChars); IPicture[] pics = new IPicture[] { }; pics = tag.Tag.Pictures; if (pics.Length > 0) { musictag.CoverArtImageBytes = pics[0].Data.Data; } musictag.Duration = (int)tag.Properties.Duration.TotalSeconds; musictag.FileName = strFile; musictag.FileType = tag.MimeType.Substring(tag.MimeType.IndexOf("/") + 1); string[] genre = tag.Tag.Genres; if (genre.Length > 0) { musictag.Genre = String.Join(";", genre).Trim(trimChars); } string lyrics = tag.Tag.Lyrics == null ? "" : tag.Tag.Lyrics.Trim(trimChars); musictag.Title = tag.Tag.Title == null ? "" : tag.Tag.Title.Trim(trimChars); // Prevent Null Ref execption, when Title is not set musictag.Track = (int)tag.Tag.Track; musictag.TrackTotal = (int)tag.Tag.TrackCount; musictag.DiscID = (int)tag.Tag.Disc; musictag.DiscTotal = (int)tag.Tag.DiscCount; musictag.Codec = tag.Properties.Description; if (tag.MimeType == "taglib/mp3") { musictag.BitRateMode = tag.Properties.Description.IndexOf("VBR") > -1 ? "VBR" : "CBR"; } else { musictag.BitRateMode = ""; } musictag.BPM = (int)tag.Tag.BeatsPerMinute; musictag.Channels = tag.Properties.AudioChannels; musictag.SampleRate = tag.Properties.AudioSampleRate; musictag.Year = (int)tag.Tag.Year; musictag.ReplayGainTrack = tag.Tag.ReplayGainTrack ?? ""; musictag.ReplayGainTrackPeak = tag.Tag.ReplayGainTrackPeak ?? ""; musictag.ReplayGainAlbum = tag.Tag.ReplayGainAlbum ?? ""; musictag.ReplayGainAlbumPeak = tag.Tag.ReplayGainAlbumPeak ?? ""; if (tag.MimeType == "taglib/mp3") { bool foundPopm = false; // Handle the Rating, which comes from the POPM frame TagLib.Id3v2.Tag id32_tag = tag.GetTag(TagLib.TagTypes.Id3v2) as TagLib.Id3v2.Tag; if (id32_tag != null) { // Do we have a POPM frame written by MediaPortal or MPTagThat? TagLib.Id3v2.PopularimeterFrame popmFrame = TagLib.Id3v2.PopularimeterFrame.Get(id32_tag, "MediaPortal", false); if (popmFrame == null) { popmFrame = TagLib.Id3v2.PopularimeterFrame.Get(id32_tag, "MPTagThat", false); } if (popmFrame != null) { musictag.Rating = popmFrame.Rating; foundPopm = true; } // Now look for a POPM frame written by WMP if (!foundPopm) { TagLib.Id3v2.PopularimeterFrame popm = TagLib.Id3v2.PopularimeterFrame.Get(id32_tag, "Windows Media Player 9 Series", false); if (popm != null) { // Get the rating stored in the WMP POPM frame int rating = popm.Rating; int i = 0; if (rating == 255) i = 5; else if (rating == 196) i = 4; else if (rating == 128) i = 3; else if (rating == 64) i = 2; else if (rating == 1) i = 1; musictag.Rating = i; foundPopm = true; } } if (!foundPopm) { // Now look for any other POPM frame that might exist foreach (TagLib.Id3v2.PopularimeterFrame popm in id32_tag.GetFrames<TagLib.Id3v2.PopularimeterFrame>()) { int rating = popm.Rating; int i = 0; if (rating > 205 || rating == 5) i = 5; else if (rating > 154 || rating == 4) i = 4; else if (rating > 104 || rating == 3) i = 3; else if (rating > 53 || rating == 2) i = 2; else if (rating > 0 || rating == 1) i = 1; musictag.Rating = i; foundPopm = true; break; // we only take the first popm frame } } if (!foundPopm) { // If we don't have any POPM frame, we might have an APE Tag embedded in the mp3 file TagLib.Ape.Tag apetag = tag.GetTag(TagTypes.Ape, false) as TagLib.Ape.Tag; if (apetag != null) { TagLib.Ape.Item apeItem = apetag.GetItem("RATING"); if (apeItem != null) { string rating = apeItem.ToString(); try { musictag.Rating = Convert.ToInt32(rating); } catch (Exception ex) { musictag.Rating = 0; Log.Warn("Tagreader: Unsupported APE rating format - {0} in {1} {2}", rating, strFile, ex.Message); } } } } } } else { if (tag.MimeType == "taglib/ape") { TagLib.Ape.Tag apetag = tag.GetTag(TagTypes.Ape, false) as TagLib.Ape.Tag; if (apetag != null) { TagLib.Ape.Item apeItem = apetag.GetItem("RATING"); if (apeItem != null) { string rating = apeItem.ToString(); try { musictag.Rating = Convert.ToInt32(rating); } catch (Exception ex) { musictag.Rating = 0; Log.Warn("Tagreader: Unsupported APE rating format - {0} in {1} {2}", rating, strFile, ex.Message); } } } } } // if we didn't get a title, use the Filename without extension to prevent the file to appear as "unknown" if (musictag.Title == "") { Log.Warn("TagReader: Empty Title found in file: {0}. Please retag.", strFile); musictag.Title = System.IO.Path.GetFileNameWithoutExtension(strFile); } return musictag; } catch (UnsupportedFormatException) { Log.Warn("Tagreader: Unsupported File Format {0}", strFile); } catch (Exception ex) { Log.Warn("TagReader: Exception reading file {0}. {1}", strFile, ex.Message); } return null; }
/// <summary> /// Checks a collection of tracks from last.fm against the users local database /// If tracks are matched then these tracks will be considered by auto DJ /// </summary> /// <param name="tracks">Collection of tracks to check for local copies</param> /// <param name="tag">Tags of track we are looking up</param> /// <returns>True if tracks were added to playlist else false</returns> private static bool LocalTracksAdded(IEnumerable<LastFMSimilarTrack> tracks, MusicTag tag) { if (tracks == null) { return false; } var dbTracks = GetSimilarTracksInDatabase(tracks, tag); if (dbTracks.Count == 0) { return false; } AutoDJAddToPlaylist(dbTracks); return true; }