public HymnalEntry(ushort number, string title, Lyrics lyrics, Music music) { Number = number; Title = title; Lyrics = lyrics; Music = music; }
private void Player_SongChanged(object sender, EventArgs e) { ShowCoverArt(); Lyrics.HandleLyrics(); }
private static bool TryGetCache(string title, string artist, int duration, bool useTranslated, out Lyrics lyric) { throw new NotImplementedException(); }
private void ParseLyrics(Lyrics lyrics) { Application.Current.Dispatcher.Invoke(() => this.lyricsLines = null); var localLyricsLines = new ObservableCollection <LyricsLineViewModel>(); var reader = new StringReader(lyrics.Text); string line; bool allLinesHaveTimeStamps = true; // Assume true bool hasLinesWithMultipleTimeStamps = false; // Assume false while (true) { line = reader.ReadLine(); if (line != null) { if (line.Length > 0 && line.StartsWith("[")) { int index = line.LastIndexOf(']'); var time = TimeSpan.Zero; // -1 means: not found (We check for > 0, because > -1 makes no sense in this case) if (index > 0) { MatchCollection ms = Regex.Matches(line, @"\[.*?\]"); if (ms.Count > 1) { hasLinesWithMultipleTimeStamps = true; } foreach (Match m in ms) { string subString = m.Value.Trim('[', ']'); if (FormatUtils.ParseLyricsTime(subString, out time)) { localLyricsLines.Add(new LyricsLineViewModel(time, line.Substring(index + 1))); } else { // The string between square brackets could not be parsed to a timestamp. // In such case, just add the complete lyrics line. localLyricsLines.Add(new LyricsLineViewModel(line)); allLinesHaveTimeStamps = false; } } } } else { localLyricsLines.Add(new LyricsLineViewModel(line)); allLinesHaveTimeStamps = false; } } else { break; } } if (allLinesHaveTimeStamps && hasLinesWithMultipleTimeStamps) { // Only sort when all lines have timestamps and there are lines with multiple timestamps. // This works around a sorting issue when timestamping lyrics and not all lines have timestamps localLyricsLines = new ObservableCollection <LyricsLineViewModel>(localLyricsLines.OrderBy(p => p.Time)); } Application.Current.Dispatcher.Invoke(() => { this.lyricsLines = localLyricsLines; RaisePropertyChanged(nameof(this.LyricsLines)); }); }
private async void RefreshLyricsAsync(PlayableTrack track) { if (!this.nowPlayingIsSelected || !this.lyricsScreenIsActive) { return; } if (track == null) { return; } if (this.previousTrack != null && this.previousTrack.Equals(track)) { return; } this.previousTrack = track; this.StopHighlighting(); FileMetadata fmd = await this.metadataService.GetFileMetadataAsync(track.Path); await Task.Run(() => { // If we're in editing mode, delay changing the lyrics. if (this.LyricsViewModel != null && this.LyricsViewModel.IsEditing) { this.updateLyricsAfterEditingTimer.Start(); return; } // No FileMetadata available: clear the lyrics. if (fmd == null) { this.ClearLyrics(); return; } }); try { Lyrics lyrics = null; bool mustDownloadLyrics = false; await Task.Run(() => { lyrics = new Lyrics(fmd != null && fmd.Lyrics.Value != null ? fmd.Lyrics.Value : String.Empty, string.Empty); // If the file has no lyrics, and the user enabled automatic download of lyrics, indicate that we need to try to download. if (!lyrics.HasText) { if (SettingsClient.Get <bool>("Lyrics", "DownloadLyrics")) { string artist = fmd.Artists != null && fmd.Artists.Values != null && fmd.Artists.Values.Length > 0 ? fmd.Artists.Values[0] : string.Empty; string title = fmd.Title != null && fmd.Title.Value != null ? fmd.Title.Value : string.Empty; if (!string.IsNullOrWhiteSpace(artist) & !string.IsNullOrWhiteSpace(title)) { mustDownloadLyrics = true; } } } }); // No lyrics were found in the file: try to download. if (mustDownloadLyrics) { this.IsDownloadingLyrics = true; try { var factory = new LyricsFactory(); lyrics = await factory.GetLyricsAsync(fmd.Artists.Values[0], fmd.Title.Value); } catch (Exception ex) { LogClient.Error("Could not get lyrics online {0}. Exception: {1}", track.Path, ex.Message); } this.IsDownloadingLyrics = false; } await Task.Run(() => { this.LyricsViewModel = new LyricsViewModel(container, track, metadataService); this.LyricsViewModel.SetLyrics(lyrics); }); } catch (Exception ex) { this.IsDownloadingLyrics = false; LogClient.Error("Could not show lyrics for Track {0}. Exception: {1}", track.Path, ex.Message); this.ClearLyrics(); return; } this.StartHighlighting(); }
public Task <int> DeleteLyricsAsync(Lyrics entry) { return(Database.DeleteAsync(entry)); }
protected Lyrics ReadLyrics() { Lyrics lyrics = new Lyrics(); lyrics.TrackNumber = ReadInt(); for (int i = 0; i < 5; i++) { lyrics.MeasureNumber[i] = ReadInt(); lyrics.Lines[i] = ReadStringInteger(); } return lyrics; }
internal static void DownloadSongLyrics (IMLItem Item, ConnectionResult connectionresult) { if (!Settings.LyricsEnabled) return; if (!connectionresult.InternetConnectionAvailable && Settings.ConnectionDiagnosticsEnabled) return; try { Debugger.LogMessageToFile ("Retrieving LyricsSearched value..."); string LyricsSearched = Helpers.GetTagValueFromItem (Item, "---LyricsSearched---"); if (Settings.SkipSearchedLyrics) { if (LyricsSearched == "true") return; } Debugger.LogMessageToFile("Retrieving Lyrics value..."); string Lyrics = Helpers.GetTagValueFromItem(Item, "Lyrics"); Debugger.LogMessageToFile("Retrieving Artist value..."); string Artist = Helpers.GetTagValueFromItem(Item, "Artist"); Debugger.LogMessageToFile("Retrieving Title value..."); string Title = Helpers.GetTagValueFromItem(Item, "Title"); if (!String.IsNullOrEmpty(Lyrics)) return; if (String.IsNullOrEmpty(Artist)) return; if (String.IsNullOrEmpty(Title)) return; Debugger.LogMessageToFile("Creating LyricFinder class..."); Lyrics myLyrics = new Lyrics(); string lyricsStr; Debugger.LogMessageToFile("Searching lyrics for " + Title + "..."); MainImportingEngine.ThisProgress.Progress(MainImportingEngine.CurrentProgress, "Searching lyrics for " + Title + "..."); lyricsStr = myLyrics.ReturnLyrics(Artist, Title); string[] dirtyText = RegExMatchers.MatchExpressionReturnAllMatchesFirstGroup(lyricsStr, "<br />"); if (dirtyText != null) lyricsStr = dirtyText.Aggregate(lyricsStr, (current, dirtyTag) => current.Replace(dirtyTag, Environment.NewLine)); string[] dirtyTextb = RegExMatchers.MatchExpressionReturnAllMatchesFirstGroup(lyricsStr, "<.*?>"); if (dirtyTextb != null) lyricsStr = dirtyTextb.Aggregate(lyricsStr, (current, dirtyTag) => current.Replace(dirtyTag, "")); string dirtyTextc = RegExMatchers.MatchExpressionReturnFirstMatchFirstGroup(lyricsStr, "Send.*?Ringtone to your Cell "); if (!String.IsNullOrEmpty(dirtyTextc)) lyricsStr = lyricsStr.Replace(dirtyTextc, ""); Debugger.LogMessageToFile("Saving to 'Lyrics' tag..."); Item.Tags["Lyrics"] = lyricsStr; Item.Tags["---LyricsSearched---"] = "true"; Item.SaveTags(); } catch (Exception e) { Debugger.LogMessageToFile("An uncexpected error occurred in the Lyrics downloader method. The error was: " + e.ToString() ); StatusForm.statusForm.TrayIcon.ShowBalloonTip(10000, "An error ocurred", "An uncexpected error occurred in the Lyrics downloader method." + Environment.NewLine + "Please see Debug.log for details.",ToolTipIcon.Error); } }
// Generates a question for the API. private async Task <Question> GenerateQuestionAsync() { // Retrieve recommendations from Spotify Recommendations recommendations = GenerateRecommendations(); if (recommendations == null) { return(null); } // Retrieve photo of artist FullArtist artist = SpotifyHelper.Instance.Api.GetArtist(recommendations.Tracks[0].Artists[0].Id); // Retrieve lyrics from ApiSeeds Lyrics lyrics = await LyricsHelper.Instance.GetLyricsAsync(recommendations.Tracks[0].Artists[0].Name, recommendations.Tracks[0].Name); if (lyrics == null) { return(null); } // Creates an instance of the correct quiz answer Answer answer = new Answer(); answer.Artist = lyrics.Result.Artist.Name; answer.Photo = artist.Images[0].Url; answer.Song.SongName = recommendations.Tracks[0].Name; answer.Song.SongId = recommendations.Tracks[0].Id; answer.Song.SongLyrics = lyrics.Result.Track.Text; answer.Song.Language.LanguageCode = lyrics.Result.Track.Lang.Code; answer.Song.Language.LanguageName = lyrics.Result.Track.Lang.Name; Question.Answer = answer; // Retrieve related artists from Spotify SeveralArtists severalArtists = SpotifyHelper.Instance.Api.GetRelatedArtists(recommendations.Tracks[0].Artists[0].Id); int count = 0; foreach (var relatedArtist in severalArtists.Artists) { Question.RelatedArtists[count].Artist = relatedArtist.Name; Question.RelatedArtists[count].Photo = relatedArtist.Images[0].Url; count++; if (count == 3) { break; } } if (Question.RelatedArtists.Length != 3) { return(null); } return(Question); }
public override void ParseElement(MusicXmlParserState state, Staff staff, XElement element) { var builder = new NoteOrRestBuilder(state); element.IfAttribute("default-x").HasValue <double>().Then(m => builder.DefaultX = m); element.IfAttribute("measure").HasValue("yes").Then(m => builder.FullMeasure = true); element.IfAttribute("print-object").HasValue(new Dictionary <string, bool> { { "yes", true }, { "no", false } }).Then(m => builder.IsVisible = m); element.IfAttribute("size").HasValue("cue").Then(() => builder.IsCueNote = true); element.IfElement("staff").HasValue <int>().Then(m => builder.Staff = staff.Score.Staves.ElementAt(m - 1)); //TODO: Sprawdzić czy staff to numer liczony od góry strony czy numer w obrębie parta element.IfElement("type").HasValue(new Dictionary <string, RhythmicDuration> { { "whole", RhythmicDuration.Whole }, { "half", RhythmicDuration.Half }, { "quarter", RhythmicDuration.Quarter }, { "eighth", RhythmicDuration.Eighth }, { "16th", RhythmicDuration.Sixteenth }, { "32nd", RhythmicDuration.D32nd }, { "64th", RhythmicDuration.D64th }, { "128th", RhythmicDuration.D128th } }).Then(m => builder.BaseDuration = m); element.IfElement("voice").HasValue <int>().Then(m => builder.Voice = m); element.IfElement("grace").Exists().Then(() => builder.IsGraceNote = true); element.IfElement("chord").Exists().Then(() => builder.IsChordElement = true); element.IfElement("accidental").HasValue("natural").Then(() => builder.HasNatural = true); element.IfElement("rest").Exists().Then(() => builder.IsRest = true); element.ForEachDescendant("dot", f => f.Exists().Then(() => builder.NumberOfDots++)); var pitchElement = element.IfElement("pitch").Exists().ThenReturnResult(); pitchElement.IfElement("step").HasAnyValue().Then(v => builder.Step = v); pitchElement.IfElement("octave").HasValue <int>().Then(v => builder.Octave = v); pitchElement.IfElement("alter").HasValue <int>().Then(v => builder.Alter = v); var tieElements = element.Elements().Where(e => e.Name == "tie"); foreach (var tieElement in tieElements) { tieElement.IfAttribute("type").HasValue("start").Then(v => { if (builder.TieType == NoteTieType.Stop) { builder.TieType = NoteTieType.StopAndStartAnother; } else { builder.TieType = NoteTieType.Start; } }).Otherwise(() => builder.TieType = NoteTieType.Stop); } element.IfElement("stem").HasValue("down") .Then(() => builder.StemDirection = VerticalDirection.Down) .Otherwise(() => builder.StemDirection = VerticalDirection.Up); element.GetElement("stem").IfAttribute("default-y").HasValue <float>().Then(v => { builder.StemDefaultY = v; builder.CustomStemEndPosition = true; }); element.ForEachDescendant("beam", h => h.HasValue(new Dictionary <string, NoteBeamType> { { "begin", NoteBeamType.Start }, { "end", NoteBeamType.End }, { "continue", NoteBeamType.Continue }, { "forward hook", NoteBeamType.ForwardHook }, { "backward hook", NoteBeamType.BackwardHook } }).Then(v => builder.BeamList.Add(v))); var notationsNode = element.GetElement("notations"); var tupletNode = notationsNode.GetElement("tuplet"); tupletNode.IfAttribute("type").HasValue(new Dictionary <string, TupletType> { { "start", TupletType.Start }, { "stop", TupletType.Stop }, }).Then(v => builder.Tuplet = v); tupletNode.IfAttribute("placement").HasValue(new Dictionary <string, VerticalPlacement> { { "above", VerticalPlacement.Above }, { "below", VerticalPlacement.Below }, }).Then(v => builder.TupletPlacement = v); notationsNode.IfElement("fermata").HasAnyValue().Then(() => builder.HasFermataSign = true); notationsNode.IfElement("sound").Exists().Then(e => e.IfAttribute("dynamics").HasValue <int>().Then(v => state.CurrentDynamics = v)); notationsNode.IfHasElement("dynamics").Then(d => { var dir = new Direction(); d.IfAttribute("default-y").HasValue <int>().Then(v => { dir.DefaultYPosition = v; dir.Placement = DirectionPlacementType.Custom; }); d.IfAttribute("placement").HasValue(new Dictionary <string, DirectionPlacementType> { { "above", DirectionPlacementType.Above }, { "below", DirectionPlacementType.Below } }).Then(v => { if (dir.Placement != DirectionPlacementType.Custom) { dir.Placement = v; } }); foreach (XElement dynamicsType in d.Elements()) { dir.Text = dynamicsType.Name.LocalName; } staff.Elements.Add(dir); }); notationsNode.IfHasElement("articulations").Then(d => { d.IfElement("staccato").HasAnyValue().Then(() => builder.Articulation = ArticulationType.Staccato); d.IfElement("accent").HasAnyValue().Then(() => builder.Articulation = ArticulationType.Accent); d.IfAttribute("placement").HasValue(new Dictionary <string, VerticalPlacement> { { "above", VerticalPlacement.Above }, { "below", VerticalPlacement.Below }, }).Then(v => builder.ArticulationPlacement = v); }); var ornamentsNode = notationsNode.GetElement("ornaments"); ornamentsNode.GetElement("trill-mark").IfAttribute("placement").HasValue(new Dictionary <string, NoteTrillMark> { { "above", NoteTrillMark.Above }, { "below", NoteTrillMark.Below } }).Then(v => builder.TrillMark = v); ornamentsNode.IfElement("tremolo").HasValue <int>().Then(v => builder.TremoloLevel = v); var invMordentNode = ornamentsNode .IfElement("inverted-mordent") .Exists() .Then(e => builder.Mordent = new Mordent() { IsInverted = true }) .AndReturnResult(); invMordentNode.IfAttribute("placement").HasValue(new Dictionary <string, VerticalPlacement> { { "above", VerticalPlacement.Above }, { "below", VerticalPlacement.Below } }).Then(v => builder.Mordent.Placement = v); invMordentNode.IfAttribute("default-x").HasValue <double>().Then(v => builder.Mordent.DefaultXPosition = v); invMordentNode.IfAttribute("default-y").HasValue <double>().Then(v => builder.Mordent.DefaultYPosition = v); var slurNode = notationsNode.IfElement("slur").Exists().Then(s => builder.Slur = new Slur()).AndReturnResult(); var number = slurNode.IfAttribute("number").HasValue <int>().Then(v => { }).AndReturnResult(); if (number < 2) { slurNode.IfAttribute("type").HasValue(new Dictionary <string, NoteSlurType> { { "start", NoteSlurType.Start }, { "stop", NoteSlurType.Stop } }).Then(v => builder.Slur.Type = v); slurNode.IfAttribute("placement").HasValue(new Dictionary <string, VerticalPlacement> { { "above", VerticalPlacement.Above }, { "below", VerticalPlacement.Below } }).Then(v => builder.Slur.Placement = v); } foreach (var lNode in element.Elements().Where(n => n.Name == "lyric")) { Lyrics lyricsInstance = new Lyrics(); Lyrics.Syllable syllable = new Lyrics.Syllable(); bool isSylabicSet = false; bool isTextSet = false; lNode.IfAttribute("default-y").HasValue <double>().Then(v => lyricsInstance.DefaultYPosition = v); lNode.IfElement("syllabic").HasValue(new Dictionary <string, SyllableType> { { "begin", SyllableType.Begin }, { "middle", SyllableType.Middle }, { "end", SyllableType.End }, { "single", SyllableType.Single } }).Then(v => { syllable.Type = v; isSylabicSet = true; }); lNode.IfElement("text").HasAnyValue().Then(v => { syllable.Text = v; isTextSet = true; }); lNode.IfElement("elision").HasAnyValue().Then(v => syllable.ElisionMark = v); if (isSylabicSet && isTextSet) { lyricsInstance.Syllables.Add(syllable); syllable = new Lyrics.Syllable(); isSylabicSet = false; isTextSet = false; } builder.Lyrics.Add(lyricsInstance); } if (builder.BeamList.Count == 0) { builder.BeamList.Add(NoteBeamType.Single); } var noteOrRest = builder.Build(); var correctStaff = noteOrRest.Staff ?? staff; correctStaff.Elements.Add(noteOrRest); }
public override void ParseElement(MusicXmlParserState state, Staff staff, XElement element) { var builder = new NoteOrRestBuilder(state); element.IfAttribute("default-x").HasValue <double>().Then(m => builder.DefaultX = m); element.IfAttribute("measure").HasValue("yes").Then(m => builder.FullMeasure = true); element.IfAttribute("print-object").HasValue(new Dictionary <string, bool> { { "yes", true }, { "no", false } }).Then(m => builder.IsVisible = m); element.IfAttribute("size").HasValue(new Dictionary <string, NoteOrRestSize> { { "cue", NoteOrRestSize.Cue }, { "full", NoteOrRestSize.Full }, { "large", NoteOrRestSize.Large }, }).Then(s => builder.Size = s); element.IfElement("staff").HasValue <int>().Then(m => builder.Staff = staff.Part.Staves.ElementAt(m - 1)); element.IfElement("type").HasValue(new Dictionary <string, RhythmicDuration> { { "breve", RhythmicDuration.DoubleWhole }, { "whole", RhythmicDuration.Whole }, { "half", RhythmicDuration.Half }, { "quarter", RhythmicDuration.Quarter }, { "eighth", RhythmicDuration.Eighth }, { "16th", RhythmicDuration.Sixteenth }, { "32nd", RhythmicDuration.D32nd }, { "64th", RhythmicDuration.D64th }, { "128th", RhythmicDuration.D128th } }).Then(m => builder.BaseDuration = m); var typeElement = element.GetElement("type"); if (typeElement != null) { typeElement.IfAttribute("size").HasValue(new Dictionary <string, NoteOrRestSize> { { "cue", NoteOrRestSize.Cue }, { "full", NoteOrRestSize.Full }, { "large", NoteOrRestSize.Large }, }).Then(s => builder.Size = s); //"size" attribute apparently can be added to element "type" too } element.IfElement("voice").HasValue <int>().Then(m => builder.Voice = m); var graceElement = element.GetElement("grace"); if (graceElement != null) { graceElement.IfAttribute("slash").HasValue("yes") .Then(v => builder.GraceNoteType = GraceNoteType.Slashed) .Otherwise(v => builder.GraceNoteType = GraceNoteType.Simple); } element.IfElement("chord").Exists().Then(() => builder.IsChordElement = true); element.IfElement("accidental").HasValue("natural").Then(() => builder.HasNatural = true); element.IfElement("rest").Exists().Then(() => builder.IsRest = true); element.ForEachDescendant("dot", f => f.Exists().Then(() => builder.NumberOfDots++)); var pitchElement = element.IfElement("pitch").Exists().ThenReturnResult(); pitchElement.IfElement("step").HasAnyValue().Then(v => builder.Step = v); pitchElement.IfElement("octave").HasValue <int>().Then(v => builder.Octave = v); pitchElement.IfElement("alter").HasValue <int>().Then(v => builder.Alter = v); var unpitchedElement = element.IfElement("unpitched").Exists().Then(x => builder.IsUnpitched = true).AndReturnResult(); unpitchedElement.IfElement("display-step").HasAnyValue().Then(v => builder.Step = v); unpitchedElement.IfElement("display-octave").HasValue <int>().Then(v => builder.Octave = v); unpitchedElement.IfElement("display-alter").HasValue <int>().Then(v => builder.Alter = v); var tieElements = element.Elements().Where(e => e.Name == "tie"); foreach (var tieElement in tieElements) { tieElement.IfAttribute("type").HasValue("start").Then(v => { if (builder.TieType == NoteTieType.Stop) { builder.TieType = NoteTieType.StopAndStartAnother; } else { builder.TieType = NoteTieType.Start; } }).Otherwise(r => builder.TieType = NoteTieType.Stop); } element.IfElement("stem").HasValue("down") .Then(() => builder.StemDirection = VerticalDirection.Down) .Otherwise(r => builder.StemDirection = VerticalDirection.Up); element.GetElement("stem").IfAttribute("default-y").HasValue <float>().Then(v => { builder.StemDefaultY = v; builder.CustomStemEndPosition = true; }); element.ForEachDescendant("beam", h => h.HasValue(new Dictionary <string, NoteBeamType> { { "begin", NoteBeamType.Start }, { "end", NoteBeamType.End }, { "continue", NoteBeamType.Continue }, { "forward hook", NoteBeamType.ForwardHook }, { "backward hook", NoteBeamType.BackwardHook } }).Then(v => builder.BeamList.Add(v)) .Otherwise(r => { if (r.ToLowerInvariant() != "single") { throw new ScoreException(builder, $"Unsupported beam type \"{r}\"."); } })); var notationsNode = element.GetElement("notations"); var tupletNode = notationsNode.GetElement("tuplet"); tupletNode.IfAttribute("type").HasValue(new Dictionary <string, TupletType> { { "start", TupletType.Start }, { "stop", TupletType.Stop }, }).Then(v => builder.Tuplet = v); tupletNode.IfAttribute("placement").HasValue(new Dictionary <string, VerticalPlacement> { { "above", VerticalPlacement.Above }, { "below", VerticalPlacement.Below }, }).Then(v => builder.TupletPlacement = v); notationsNode.IfElement("fermata").Exists().Then(() => builder.HasFermataSign = true); notationsNode.IfElement("sound").Exists().Then(e => e.IfAttribute("dynamics").HasValue <int>().Then(v => state.CurrentDynamics = v)); notationsNode.IfHasElement("dynamics").Then(d => { var dir = new Direction(); d.IfAttribute("default-y").HasValue <int>().Then(v => { dir.DefaultYPosition = v; dir.Placement = DirectionPlacementType.Custom; }); d.IfAttribute("placement").HasValue(new Dictionary <string, DirectionPlacementType> { { "above", DirectionPlacementType.Above }, { "below", DirectionPlacementType.Below } }).Then(v => { if (dir.Placement != DirectionPlacementType.Custom) { dir.Placement = v; } }); foreach (XElement dynamicsType in d.Elements()) { dir.Text = dynamicsType.Name.LocalName; } staff.Elements.Add(dir); }); notationsNode.IfHasElement("articulations").Then(d => { d.IfElement("staccato").HasAnyValue().Then(() => builder.Articulation = ArticulationType.Staccato); d.IfElement("accent").HasAnyValue().Then(() => builder.Articulation = ArticulationType.Accent); d.IfAttribute("placement").HasValue(new Dictionary <string, VerticalPlacement> { { "above", VerticalPlacement.Above }, { "below", VerticalPlacement.Below }, }).Then(v => builder.ArticulationPlacement = v); }); var ornamentsNode = notationsNode.GetElement("ornaments"); ornamentsNode.GetElement("trill-mark").IfAttribute("placement").HasValue(new Dictionary <string, NoteTrillMark> { { "above", NoteTrillMark.Above }, { "below", NoteTrillMark.Below } }).Then(v => builder.TrillMark = v); ornamentsNode.IfElement("tremolo").HasValue <int>().Then(v => builder.TremoloLevel = v); var invMordentNode = ornamentsNode .IfElement("inverted-mordent") .Exists() .Then(e => builder.Mordent = new Mordent() { IsInverted = true }) .AndReturnResult(); invMordentNode.IfAttribute("placement").HasValue(new Dictionary <string, VerticalPlacement> { { "above", VerticalPlacement.Above }, { "below", VerticalPlacement.Below } }).Then(v => builder.Mordent.Placement = v); invMordentNode.IfAttribute("default-x").HasValue <double>().Then(v => builder.Mordent.DefaultXPosition = v); invMordentNode.IfAttribute("default-y").HasValue <double>().Then(v => builder.Mordent.DefaultYPosition = v); foreach (var slurNode in notationsNode?.Elements().Where(e => e.Name == "slur") ?? new XElement[] { }) { var slur = new Slur(); builder.Slurs.Add(slur); slurNode.IfAttribute("number").HasValue <int>().Then(v => slur.Number = v); slurNode.IfAttribute("type").HasValue(new Dictionary <string, NoteSlurType> { { "start", NoteSlurType.Start }, { "stop", NoteSlurType.Stop } }).Then(v => slur.Type = v); slurNode.IfAttribute("placement").HasValue(new Dictionary <string, VerticalPlacement> { { "above", VerticalPlacement.Above }, { "below", VerticalPlacement.Below } }).Then(v => slur.Placement = v); slurNode.IfAttribute("default-x").HasValue <double>().Then(v => slur.DefaultXPosition = v); slurNode.IfAttribute("default-y").HasValue <double>().Then(v => slur.DefaultYPosition = v); slurNode.IfAttribute("bezier-x").HasValue <double>().Then(v => slur.BezierX = v); slurNode.IfAttribute("bezier-y").HasValue <double>().Then(v => slur.BezierY = v); } foreach (var lNode in element.Elements().Where(n => n.Name == "lyric")) { //There can be more than one lyrics in one <lyrics> tag. Add lyrics to list once syllable type and text is set. //Then reset these tags so the next <syllabic> tag starts another lyric. Lyrics lyricsInstance = new Lyrics(); Lyrics.Syllable syllable = new Lyrics.Syllable(); bool isSylabicSet = false; bool isTextSet = false; var defaultYattribute = lNode.Attributes().FirstOrDefault(a => a.Name == "default-y"); if (defaultYattribute != null) { lyricsInstance.DefaultYPosition = UsefulMath.TryParse(defaultYattribute.Value); } foreach (XElement lyricAttribute in lNode.Elements()) { if (lyricAttribute.Name == "syllabic") { if (lyricAttribute.Value == "begin") { syllable.Type = SyllableType.Begin; } else if (lyricAttribute.Value == "middle") { syllable.Type = SyllableType.Middle; } else if (lyricAttribute.Value == "end") { syllable.Type = SyllableType.End; } else if (lyricAttribute.Value == "single") { syllable.Type = SyllableType.Single; } isSylabicSet = true; } else if (lyricAttribute.Name == "text") { syllable.Text = lyricAttribute.Value; isTextSet = true; } else if (lyricAttribute.Name == "elision") { syllable.ElisionMark = lyricAttribute.Value; } if (isSylabicSet && isTextSet) { lyricsInstance.Syllables.Add(syllable); syllable = new Lyrics.Syllable(); isSylabicSet = false; isTextSet = false; } } builder.Lyrics.Add(lyricsInstance); } if (builder.BeamList.Count == 0) { builder.BeamList.Add(NoteBeamType.Single); } var noteOrRest = builder.Build(); var correctStaff = noteOrRest.Staff ?? staff; correctStaff.Elements.Add(noteOrRest); }
//void _selectedCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) //{ // if (this.SyncableObjectSelected != null && this.SelectedCollection.Count > 0) // { // this.SyncableObjectSelected(this, new TimelineEventArgs(this.SelectedCollection.ToList())); // } //} public LyricsTimelineSelectorViewModel(Lyrics lrc) { this.Lyrics = lrc; }
private Lyrics ReadStructLyrics(Lyrics lyrics) { lyrics.Start = Int32; lyrics.Content = LongString; return(lyrics); }
private void EndEditingCell(int rowIndex, int columnIndex) { if (rowIndex >= 0 && columnIndex >= 0) { var curCell = grdSong.Rows[rowIndex].Cells[columnIndex]; var curVerseFile = grdSong.Rows[rowIndex].DataBoundItem as VerseFile; string newValue = curCell.EditedFormattedValue.ToString(); if (curVerseFile.Verse.Update(newValue)) { string binaryFile = SaveLyrics(); SendViaConsole(binaryFile, true); // then the console is going to call Lyrics.SendSelected() txtSong.Text = _lastNotSelectedText.Insert(_lastSelectedTextPosition, Lyrics.ToString()); grdSong.EndEdit(); curCell.ReadOnly = true; if (_selectedBeforeEditingCell != null) { _selectedBeforeEditingCell.Selected = true; } } } _selectedBeforeEditingCell = null; }
public void Initialise() { _mockChatClient = new Mock<IChatClient>(); _mockMusixClient = new Mock<IMusixClient>(); _mockRandomiser = new Mock<IRandomiser>(); _tracks = new List<dynamic> { new { track_id = 1, artist_name = "Roy Doe", track_name = "Shenandoeah", track_share_url = "http://example.org/1" }, new { track_id = 2, artist_name = "Electric Doe", track_name = "Doethrone", track_share_url = "http://example.org/2" } }; _lyrics1 = new Lyrics("Roy Doe", "Shenandoeah", "http://example.org/1", "Doop\nDoop"); _lyrics2 = new Lyrics("Electric Doe", "Doethrone", "http://example.org/2", "No\nNo"); }
private void MetaData() { var anyMeta = false; while (_sy == AlphaTexSymbols.MetaCommand) { var syData = _syData.ToString().ToLower(); if (syData == "title") { NewSy(); if (_sy == AlphaTexSymbols.String) { _score.Title = _syData.ToString(); } else { Error("title", AlphaTexSymbols.String); } NewSy(); anyMeta = true; } else if (syData == "subtitle") { NewSy(); if (_sy == AlphaTexSymbols.String) { _score.SubTitle = _syData.ToString(); } else { Error("subtitle", AlphaTexSymbols.String); } NewSy(); anyMeta = true; } else if (syData == "artist") { NewSy(); if (_sy == AlphaTexSymbols.String) { _score.Artist = _syData.ToString(); } else { Error("artist", AlphaTexSymbols.String); } NewSy(); anyMeta = true; } else if (syData == "album") { NewSy(); if (_sy == AlphaTexSymbols.String) { _score.Album = _syData.ToString(); } else { Error("album", AlphaTexSymbols.String); } NewSy(); anyMeta = true; } else if (syData == "words") { NewSy(); if (_sy == AlphaTexSymbols.String) { _score.Words = _syData.ToString(); } else { Error("words", AlphaTexSymbols.String); } NewSy(); anyMeta = true; } else if (syData == "music") { NewSy(); if (_sy == AlphaTexSymbols.String) { _score.Music = _syData.ToString(); } else { Error("music", AlphaTexSymbols.String); } NewSy(); anyMeta = true; } else if (syData == "copyright") { NewSy(); if (_sy == AlphaTexSymbols.String) { _score.Copyright = _syData.ToString(); } else { Error("copyright", AlphaTexSymbols.String); } NewSy(); anyMeta = true; } else if (syData == "tempo") { NewSy(); if (_sy == AlphaTexSymbols.Number) { _score.Tempo = (int)_syData; } else { Error("tempo", AlphaTexSymbols.Number); } NewSy(); anyMeta = true; } else if (syData == "capo") { NewSy(); if (_sy == AlphaTexSymbols.Number) { _track.Capo = (int)_syData; } else { Error("capo", AlphaTexSymbols.Number); } NewSy(); anyMeta = true; } else if (syData == "tuning") { NewSy(); switch (_sy) { case AlphaTexSymbols.String: var text = _syData.ToString().ToLower(); if (text == "piano" || text == "none" || text == "voice") { // clear tuning _track.Tuning = new int[0]; } else { Error("tuning", AlphaTexSymbols.Tuning); } NewSy(); break; case AlphaTexSymbols.Tuning: var tuning = new FastList <int>(); do { var t = (TuningParseResult)_syData; tuning.Add(t.RealValue); NewSy(); } while (_sy == AlphaTexSymbols.Tuning); _track.Tuning = tuning.ToArray(); break; default: Error("tuning", AlphaTexSymbols.Tuning); break; } anyMeta = true; } else if (syData == "instrument") { NewSy(); if (_sy == AlphaTexSymbols.Number) { var instrument = (int)(_syData); if (instrument >= 0 && instrument <= 128) { _track.PlaybackInfo.Program = (int)_syData; } else { Error("instrument", AlphaTexSymbols.Number, false); } } else if (_sy == AlphaTexSymbols.String) // Name { var instrumentName = _syData.ToString().ToLower(); _track.PlaybackInfo.Program = GeneralMidi.GetValue(instrumentName); } else { Error("instrument", AlphaTexSymbols.Number); } NewSy(); anyMeta = true; } else if (syData == "lyrics") { NewSy(); var lyrics = new Lyrics(); lyrics.StartBar = 0; lyrics.Text = ""; if (_sy == AlphaTexSymbols.Number) // Name { lyrics.StartBar = (int)_syData; NewSy(); } if (_sy == AlphaTexSymbols.String) { lyrics.Text = (string)_syData; NewSy(); } else { Error("lyrics", AlphaTexSymbols.String); } _lyrics.Add(lyrics); anyMeta = true; } else if (anyMeta) { Error("metaDataTags", AlphaTexSymbols.String, false); } else { // fall forward to bar meta if unknown score meta was found break; } } if (anyMeta) { if (_sy != AlphaTexSymbols.Dot) { Error("song", AlphaTexSymbols.Dot); } NewSy(); } else if (_sy == AlphaTexSymbols.Dot) { NewSy(); } }
void man_OnStatusChanged(object sender, Lyrics.LyricsFetchManager.LyricEventArgs e) { tm.SetProgressValue(current, total); if (e.LyricsFound) { subText = String.Format("Lyrics for '{1}' found on source '{0}'!", e.Source.Name, e.Track.Name); foundLyrics++; } else { subText = String.Format("Lyrics for '{1}' not found on source '{0}'.", e.Source.Name, e.Track.Name); } text = string.Format("Getting lyrics for {0} songs, {1} total lyrics found, {2} tracks scanned, {3} running threads", t.Tracks.Count/* - foundLyrics*/, foundLyrics, currentTrack, threads); if (OnStatusChanged != null) OnStatusChanged(null, null); current++; }
private void OnClean() { current_lyrics = null; OutputLyricSentence(Sentence.Empty); }
internal void GetOnlineLyric() { try { HasOriLyrics = false; HasTransLyrics = false; Lyrics tempOriLyric = new Lyrics(); Lyrics tempTransLyric = new Lyrics(); string sLRC = ""; string sContent; HttpRequest hr = new HttpRequest(); sContent = hr.GetContent("http://music.163.com/api/song/media?id=" + ID); if (sContent.Substring(0, 4).Equals("ERR!")) { ErrorLog = ErrorLog + "<RETURN ERR!>"; return; } //反序列化JSON数据 JObject o = (JObject)JsonConvert.DeserializeObject(sContent); if (Regex.IsMatch(o.Root.ToString(), @"""lyric""") == false) { ErrorLog = ErrorLog + "<CAN NOT FIND LYRIC LABEL>"; return; } sLRC = o["lyric"].ToString(); tempOriLyric.ArrangeLyrics(sLRC); HasOriLyrics = true; MixedLyrics.ArrangeLyrics(sLRC); //===========翻译 sContent = hr.GetContent("http://music.163.com/api/song/lyric?os=pc&id=" + ID + "&tv=-1"); if (sContent.Substring(0, 4).Equals("ERR!")) { ErrorLog = ErrorLog + "<RETURN ERR!>"; return; } //反序列化JSON数据 o = (JObject)JsonConvert.DeserializeObject(sContent); sLRC = o["tlyric"].ToString(); o = (JObject)JsonConvert.DeserializeObject(sLRC); sLRC = o["lyric"].ToString(); tempTransLyric.ArrangeLyrics(sLRC); if (tempOriLyric.Count >= tempTransLyric.Count && tempTransLyric.Count != 0) //翻译可能比外文歌词少,下面会对时间轴来判断配对 { int j = 0; //j为外文歌词的index for (int i = 0; i < tempTransLyric.Count && j < tempOriLyric.Count; j++) { if (tempOriLyric[j].Timeline != tempTransLyric[i].Timeline) { continue; } if (tempTransLyric[i].OriLyrics != null && tempTransLyric[i].OriLyrics != "") { MixedLyrics[j].SetTransLyrics("#", tempTransLyric[i].OriLyrics);//Mix是以外文歌词的j来充填,当没有trans的时候留空 } i++; } HasTransLyrics = true; } MixedLyrics.Sort(); tempOriLyric = null; tempTransLyric = null; } catch (System.ArgumentNullException) { ErrorLog = ErrorLog + "<ArgumentNullException ERROR!>"; } catch (System.NullReferenceException) { ErrorLog = ErrorLog + "<NullReferenceException ERROR!>"; } }
private bool TryGetLyricFromCacheFile(string title, string artist, int time, bool is_trans, out Lyrics lyrics) { //todo lyrics = null; var file_path = @"..\lyric_cache\" + GetPath(title, artist, time, is_trans); if (!File.Exists(file_path)) { return(false); } try { var data = File.ReadAllText(file_path, Encoding.UTF8).Replace(@"\r\n", string.Empty); lyrics = Newtonsoft.Json.JsonConvert.DeserializeObject <Lyrics>(data); Utils.Debug("读取缓存文件成功" + file_path); } catch (Exception e) { Utils.Output("读取歌词缓存文件失败,原因" + e.Message, ConsoleColor.Yellow); if (!Directory.Exists(@"..\lyric_cache\failed\")) { Directory.CreateDirectory(@"..\lyric_cache\failed\"); } string failed_save_path = $@"..\lyric_cache\failed\{GetPath(title, artist, time, is_trans)}"; if (File.Exists(failed_save_path)) { File.Delete(failed_save_path); } File.Move(file_path, failed_save_path); return(false); } return(true); }
public void SetLyrics(Lyrics lyrics) { this.Lyrics = lyrics; this.uneditedLyrics = lyrics; this.ParseLyrics(lyrics); }
private Lyric tagInLyric(ITextTag textTag) { return(Lyrics.FirstOrDefault(x => getRelatedTypeTextTag(x, textTag)?.Contains(textTag) ?? false)); }
public static IList <LyricsLineViewModel> ParseLyrics(Lyrics lyrics) { var linesWithTimestamps = new List <LyricsLineViewModel>(); var linesWithoutTimestamps = new List <LyricsLineViewModel>(); var reader = new PeekStringReader(lyrics.Text); string line; while (true) { // Process 1 line line = reader.ReadLine(); if (line == null) { // No line found, we reached the end. Exit while loop. break; } // Ignore empty lines if (line.Length == 0) { // Process the next line. continue; } // Ignore lines with tags MatchCollection tagMatches = Regex.Matches(line, @"\[[a-z]+?:.*?\]"); if (tagMatches.Count > 0) { // This is a tag: ignore this line and process the next line. continue; } // Check if the line has characters and is enclosed in brackets (starts with [ and ends with ]). if (!(line.StartsWith("[") && line.LastIndexOf(']') > 0)) { // This line is not enclosed in brackets, so it cannot have timestamps. linesWithoutTimestamps.Add(new LyricsLineViewModel(line)); int numberOfEmptyLines = GetNumberOfFollowingEmptyLines(ref reader); // Add empty lines AddEmptyLines(numberOfEmptyLines, linesWithoutTimestamps, TimeSpan.Zero); // Process the next line continue; } // Get all substrings between square brackets for this line MatchCollection ms = Regex.Matches(line, @"\[.*?\]"); var spans = new List <TimeSpan>(); bool couldParseAllTimestamps = true; // Loop through all matches foreach (Match m in ms) { var time = TimeSpan.Zero; string subString = m.Value.Trim('[', ']'); if (FormatUtils.ParseLyricsTime(subString, out time)) { spans.Add(time); } else { couldParseAllTimestamps = false; } } // Check if all timestamps could be parsed if (couldParseAllTimestamps) { int startIndex = line.LastIndexOf(']') + 1; int numberOfEmptyLines = GetNumberOfFollowingEmptyLines(ref reader); foreach (TimeSpan span in spans) { linesWithTimestamps.Add(new LyricsLineViewModel(span, line.Substring(startIndex))); // Add empty lines AddEmptyLines(numberOfEmptyLines, linesWithTimestamps, span); } } else { // The line has mistakes. Consider it as a line without timestamps. linesWithoutTimestamps.Add(new LyricsLineViewModel(line)); int numberOfEmptyLines = GetNumberOfFollowingEmptyLines(ref reader); // Add empty lines AddEmptyLines(numberOfEmptyLines, linesWithoutTimestamps, TimeSpan.Zero); } } // Order the time stamped lines linesWithTimestamps = new List <LyricsLineViewModel>(linesWithTimestamps.OrderBy(p => p.Time).ThenByDescending(p => p.Text)); // Merge both collections, lines with timestamps first. linesWithTimestamps.AddRange(linesWithoutTimestamps); return(linesWithTimestamps); }
private Lyric getNextLyricWithTextTag(Lyric current, ITextTag textTag) => Lyrics.GetNextMatch(current, x => getRelatedTypeTextTag(x, textTag)?.Any() ?? false);
private async void RefreshLyricsAsync(PlayableTrack track) { if (!this.nowPlayingIsSelected || !this.lyricsScreenIsActive) { return; } if (track == null) { return; } if (this.previousTrack != null && this.previousTrack.Equals(track)) { return; } this.previousTrack = track; this.StopHighlighting(); FileMetadata fmd = await this.metadataService.GetFileMetadataAsync(track.Path); await Task.Run(() => { // If we're in editing mode, delay changing the lyrics. if (this.LyricsViewModel != null && this.LyricsViewModel.IsEditing) { this.updateLyricsAfterEditingTimer.Start(); return; } // No FileMetadata available: clear the lyrics. if (fmd == null) { this.ClearLyrics(); return; } }); try { Lyrics lyrics = null; bool mustDownloadLyrics = false; await Task.Run(async() => { // Try to get lyrics from the audio file lyrics = new Lyrics(fmd != null && fmd.Lyrics.Value != null ? fmd.Lyrics.Value : String.Empty, string.Empty); lyrics.SourceType = SourceTypeEnum.Audio; // If the audio file has no lyrics, try to find lyrics in a local lyrics file. if (!lyrics.HasText) { var lrcFile = Path.Combine(Path.GetDirectoryName(fmd.Path), Path.GetFileNameWithoutExtension(fmd.Path) + FileFormats.LRC); if (File.Exists(lrcFile)) { using (var fs = new FileStream(lrcFile, FileMode.Open, FileAccess.Read)) { using (var sr = new StreamReader(fs, Encoding.Default)) { lyrics = new Lyrics(await sr.ReadToEndAsync(), String.Empty); if (lyrics.HasText) { lyrics.SourceType = SourceTypeEnum.Lrc; return; } } } } // If we still don't have lyrics and the user enabled automatic download of lyrics: try to download them online. if (SettingsClient.Get <bool>("Lyrics", "DownloadLyrics")) { string artist = fmd.Artists != null && fmd.Artists.Values != null && fmd.Artists.Values.Length > 0 ? fmd.Artists.Values[0] : string.Empty; string title = fmd.Title != null && fmd.Title.Value != null ? fmd.Title.Value : string.Empty; if (!string.IsNullOrWhiteSpace(artist) & !string.IsNullOrWhiteSpace(title)) { mustDownloadLyrics = true; } } } }); // No lyrics were found in the file: try to download. if (mustDownloadLyrics) { this.IsDownloadingLyrics = true; try { var factory = new LyricsFactory(); lyrics = await factory.GetLyricsAsync(fmd.Artists.Values[0], fmd.Title.Value); lyrics.SourceType = SourceTypeEnum.Online; } catch (Exception ex) { CoreLogger.Current.Error("Could not get lyrics online {0}. Exception: {1}", track.Path, ex.Message); } this.IsDownloadingLyrics = false; } await Task.Run(() => { this.LyricsViewModel = new LyricsViewModel(container, track); this.LyricsViewModel.SetLyrics(lyrics); }); } catch (Exception ex) { this.IsDownloadingLyrics = false; CoreLogger.Current.Error("Could not show lyrics for Track {0}. Exception: {1}", track.Path, ex.Message); this.ClearLyrics(); return; } this.StartHighlighting(); }
public void TestSelectDoubleKeyVerse() { string song = @" // comment refrain index 0-A* // comment refrain index 1-A* // comment refrain index 2-A* // comment verse index 3 // comment verse index 4 // comment verse index 5 // comment refrain index 6-B* // comment refrain index 7-B* // comment refrain index 8-B* // comment "; Lyrics lyrics = new Lyrics(song, switcher); lyrics.Selection.ToFirstVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 0); lyrics.Selection.ToNextKeyVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 1); lyrics.Selection.ToNextVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 2); lyrics.Selection.ToNextVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 3); lyrics.Selection.ToPrevKeyVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 0); lyrics.Selection.ToNextKeyVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 1); lyrics.Selection.ToNextVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 2); lyrics.Selection.ToNextKeyVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 4); lyrics.Selection.ToPrevKeyVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 0); lyrics.Selection.ToNextKeyVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 1); lyrics.Selection.ToNextVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 2); lyrics.Selection.ToNextKeyVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 5); lyrics.Selection.ToNextKeyVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 6); lyrics.Selection.ToNextKeyVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 7); lyrics.Selection.ToNextVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 8); }
private static void WriteCache(string title, string artist, int duration, Lyrics lyric) { throw new NotImplementedException(); }
public void TestSelectKeyVerse() { string song = @" // comment // comment string index 0 // comment *refrain index 1 // comment string index 2 // comment string index 3 // comment string index 4 // comment refrain* index 5 // comment //next song next song string // comment next song refrain* // comment "; Lyrics lyrics = new Lyrics(song, switcher); lyrics.Selection.ToFirstVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 0); lyrics.Selection.ToNextKeyVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 1); lyrics.Selection.ToNextVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 2); lyrics.Selection.ToPrevKeyVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 1); lyrics.Selection.ToNextKeyVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 3); lyrics.Selection.ToPrevKeyVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 1); lyrics.Selection.ToNextKeyVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 4); lyrics.Selection.ToNextKeyVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 5); lyrics.Selection.ToNextKeyVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 5); lyrics.Selection.ToNextKeyVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 5); lyrics.Selection.ToPrevKeyVerse(); Assert.AreEqual(lyrics.Selection.CurrentVerse.IndexBasedOnZeroToSelect, 1); }
public void ReloadLyrics() { this._lrc = null; var lrc = this.Lrc; }
public List <Lyrics> ReadByBeatId(int BeatId) { var Users = new List <Lyrics>(); using (SqlConnection conn = new SqlConnection(connString)) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "Lyrics_Select_BeatId"; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@BeatId", BeatId); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { var lyrics = new Lyrics() { Id = Convert.ToInt32(reader["LyricsId"]), UserId = Convert.ToInt32(reader["UserId"]), BeatId = Convert.ToInt32(reader["BeatId"]), Lyric = (string)reader["Lyrics"], Votes = Convert.ToInt32(reader["Votes"]), VoteCount = Convert.ToInt32(reader["VoteCount"]), VoterId = reader["VoterId"] == DBNull.Value? 0:(int)reader["VoterId"], BeatUrl = (string)reader["BeatUrl"], S3SignedUrl = (string)reader["S3SignedUrl"], DateCreated = (DateTime)reader["DateCreated"], DateModified = (DateTime)reader["DateModified"], Name = (string)reader["Name"], Email = (string)reader["Email"], Password = (string)reader["Password"], }; Users.Add(lyrics); } conn.Close(); } } var groupResult = Users.GroupBy(x => new { x.Id, x.UserId, x.BeatId, x.Lyric, x.VoteCount, x.BeatUrl, x.S3SignedUrl, x.DateCreated, x.DateModified, x.Name, x.Email, x.Password }) .Select(y => new Lyrics { Id = y.Key.Id, UserId = y.Key.UserId, BeatId = y.Key.BeatId, User = new User { Id = y.Key.UserId, Name = y.Key.Name, Password = y.Key.Password, Email = y.Key.Email }, Lyric = y.Key.Lyric, VoteCount = y.Key.VoteCount, BeatUrl = y.Key.BeatUrl, S3SignedUrl = y.Key.S3SignedUrl, DateCreated = y.Key.DateCreated, DateModified = y.Key.DateModified, VoterList = y.Select(z => z.VoterId).ToList() //list of voters }).ToList(); groupResult = groupResult.OrderByDescending(u => u.VoteCount).ToList(); return(groupResult); }