How to add a new note to every chord of a score

• Sep 15, 2019 - 01:28

I am trying to write a plugin for MuseScore 3.x that harmonizes a melody; it should read a score with a single-voice melody and then add 2 more notes to each note (thus creating a chord), based on some rules. I can not find a way to iterate over the score and add a new note along an existing one. The cursor method addNote seems to overwrite the element and I can not find any API functionality to add a note to an existing element, in order to create a chord (not a chord element - every note seems to be a chord element -, just to stack three notes to create a chord). Furthermore, overwriting an element with addNote seems to break MuseScore. Sample code:

var cursor = curScore.newCursor();
cursor.track    = 0;
cursor.voice    = 0;
cursor.staffIdx = 0;
cursor.rewind(0);

while (cursor.segment) {
      if (cursor.element && cursor.element.type === Element.CHORD) {
            cursor.setDuration(cursor.element.numerator, cursor.element.denominator);
            cursor.addNote(60);
      }
      cursor.next();
}

The above code breaks MuseScore. What am I missing here? Can anyone post a code snippet where they add one more note whenever they find a CHORD element?


Comments

An ability to add a note to existing chords from a plugin was indeed missing in MuseScore 3, and it was implemented again recently, see #291790: Port the add/remove functions that exist on the Chord cpp end into the 3.x Plugin API wrapper.
This feature will be available in MuseScore 3.3 (beta version is available), and with it notes can be added to chords like shown below:

if (cursor.element && cursor.element.type === Element.CHORD) {
    var chord = cursor.element;
    var newNote = newElement(Element.NOTE);
    newNote.pitch = 60;
    chord.add(newNote);
}

Hope this helps!

In reply to by dmitrio95

Thanks for your answer. Unfortunately, it does not seem to work as I expected... It does add C to every existing CHORD element, but the notes added are not visible. They only become visible after I randomly change the current voice from the GUI. What's more, you can not undo it after the plugin runs. Any idea why this happens? My main problem is the visibility that needs a random voice toggling to happen (notes are not in a different voice, they appear in all voices after the random toggling).

Do you still have an unanswered question? Please log in first to post your question.