Beispiel #1
0
 def playNote(self, note):
     p = Note(note)
     p.quarterLength = 1.5
     stream_obj = stream.Stream()
     stream_obj.append(p)
     sp = midi.realtime.StreamPlayer(stream_obj)
     sp.play()
Beispiel #2
0
    def test_parse_music21_note(self):
        note = Note("A3")
        note.quarterLength = 4.0
        parsed_pitch = self.music_xml_plugin.parse_note_pitch(str(note.pitch))
        parsed_type = self.music_xml_plugin.parse_note_type(note.quarterLength)
        self.assertEqual(parsed_pitch, NotePitch.A3)
        self.assertEqual(parsed_type, NoteType.whole)

        note = Note("G#5")
        note.quarterLength = 1.5
        parsed_pitch = self.music_xml_plugin.parse_note_pitch(str(note.pitch))
        parsed_type = self.music_xml_plugin.parse_note_type(note.quarterLength)
        self.assertEqual(parsed_pitch, NotePitch.GS5)
        self.assertEqual(parsed_type, NoteType.dotted_quarter)

        note = Note("A#99")
        note.quarterLength = 83.1
        parsed_pitch = self.music_xml_plugin.parse_note_pitch(str(note.pitch))
        parsed_type = self.music_xml_plugin.parse_note_type(note.quarterLength)
        self.assertEqual(parsed_pitch, NotePitch.REST)
        self.assertEqual(parsed_type, NoteType.quarter)
Beispiel #3
0
def add_bass_closing(roman, duration, bass):
   '''Generate a closing riff for the bassline, given chord and
      duration in eighths'''
   filled = 0
   length_weight = 2    # Longer notes later in the bar
   root = roman.root()  # Root pitch of the chord (NOT a note object)
   while filled < duration:
      note = Note(deepcopy(root))
      length = min(random.randint(1,length_weight),duration-filled) # cap at time left
      note.quarterLength = length/2.0

      note.octave -= 2
      bass.append(note)
      filled += length
      length_weight += length # Longer notes later in the bar
 def add_to_melody_sequence(new_melody_sequence, elem, bar_length):
     if type(elem) not in [Note, Rest]:
         pass
     elif bar_length + elem.quarterLength >= time_signature:
         extra = bar_length + elem.quarterLength - time_signature
         elem.quarterLength = time_signature - bar_length
         if elem.quarterLength > 0.0:
             new_melody_sequence += [elem]
         bar_length = extra
         # The possible extra note
         elem = Note(elem.nameWithOctave) if type(elem) is Note else Rest()
         elem.quarterLength = extra
         if elem.quarterLength > 0.0:
             new_melody_sequence += [elem]
     else:
         new_melody_sequence += [elem]
         bar_length += elem.quarterLength
     return (new_melody_sequence, elem, bar_length)
def read_vmf_string(vmf_string):
    """
    Reads VMF data from a string to a Score Stream.

    :param vmf_string: The contents of the VMF file as a string.
    :return: A music21 score instance containing the music in the VMF file.
    """

    parts_converted = {}

    vmf = json.loads(vmf_string)

    # create a score
    score = Score()

    # Get the initial data
    number_of_parts = vmf['header']['number_of_parts']
    number_of_voices = vmf['header']['number_of_voices']
    smallest_note = float(Fraction(vmf['header']['tick_value']))

    # create the parts and first measure.
    for voice_number in range(number_of_parts):
        part = Part()
        voice = Voice()

        part.append(voice)

        score.append(part)

    # get the body of the vmf
    body = vmf['body']

    part_number = 0

    # We do this because we want to do each part at a time.
    for voice_number in range(number_of_voices):
        # Get all ticks for a given part.
        part = [tick[voice_number] for tick in body]

        current_element = None
        current_voice = None

        # iterate over each tick
        for tick in part:

            if current_voice is None:
                # Get the parent part if it exists.
                try:
                    current_part = parts_converted[tick[-1]]

                    # add a new voice and write to it.
                    voice = Voice()

                    initial_key_signature = KeySignature(vmf['header']['key_signature']['0.0'])
                    initial_time_signature = TimeSignature(vmf['header']['time_signature']['0.0'])

                    voice.append(initial_key_signature)
                    voice.append(initial_time_signature)

                    current_part.append(voice)

                except KeyError:
                    # Add it to our dictionary otherwise.
                    current_part = score.parts[part_number]
                    part_number += 1

                    parts_converted[tick[-1]] = current_part

                # Get the last voice.
                current_voice = current_part.voices[-1]

            if tick[0] == 1:
                if current_element is not None:
                    # check for precision and adjust
                    rounded = round(current_element.quarterLength)
                    if abs(current_element.quarterLength - rounded) < PRECISION:
                        current_element.quarterLength = rounded

                    # append to the part
                    current_voice.append(current_element)

                # Find how many notes to write. This will always be an int.
                number_of_notes = int(find_number_of_notes_in_tick(tick))

                if number_of_notes == 1:
                    # create a new note
                    current_element = Note(Pitch(pitchClass=tick[3], octave=tick[4]))
                else:
                    pitches = []

                    # create the pitches.
                    # From the beginning to the end of the pitch section of the tick.
                    for i in range(FIRST_PITCH_INDEX, FIRST_PITCH_INDEX + 2 * number_of_notes, 2):
                        pitch = Pitch(pitchClass=tick[i], octave=tick[i + 1])
                        pitches.append(pitch)

                    # create a new chord with these pitches.
                    current_element = Chord(pitches)


                # set the velocity of the note.
                current_element.volume.velocity = DynamicConverter.vmf_to_velocity(tick[DYNAMIC_BIT])
                # set the articulation
                if tick[ARTICULATION_BIT] != 0:
                    current_element.articulations.append(
                        ArticulationConverter.vmf_to_articulation(tick[ARTICULATION_BIT]))

                # set the value for this tick.
                current_element.quarterLength = smallest_note
            elif tick[0] == 2:
                # extend previous note
                current_element.quarterLength += smallest_note

            elif tick[0] == 0 and (isinstance(current_element, note.Note) or current_element is None):
                if current_element is not None:
                    # check for precision and adjust
                    rounded = round(current_element.quarterLength)
                    if abs(current_element.quarterLength - rounded) < PRECISION:
                        current_element.quarterLength = rounded

                    # append to the part
                    current_voice.append(current_element)

                # create new rest
                current_element = Rest()

                # Set the value for this tick.
                current_element.quarterLength = smallest_note

            elif tick[0] == 0 and isinstance(current_element, note.Rest):
                # extend previous rest.
                current_element.quarterLength += smallest_note

        # Append the last element in progress.
        if current_element is not None:
            # check for precision and adjust
            rounded = round(current_element.quarterLength)
            if abs(current_element.quarterLength - rounded) < PRECISION:
                current_element.quarterLength = rounded

            # append to the part
            current_voice.append(current_element)

    # create the stream for time signature changes
    time_signature_stream = Stream()

    for offset, time_signature_str in sorted(vmf['header']['time_signature'].items()):
        time_signature = TimeSignature(time_signature_str)
        time_signature_stream.append(time_signature)
        time_signature_stream[-1].offset = float(offset)

    # finish up the file.
    for part in score.parts:
        for voice in part.voices:
            voice.makeMeasures(inPlace=True, meterStream=time_signature_stream)

        for offset, t in sorted(vmf['header']['tempo'].items()):
            mm = tempo.MetronomeMark(number=t, referent=note.Note(type='quarter'))
            voice.insert(offset, mm)

        for offset, ks in sorted(vmf['header']['key_signature'].items()):
            voice.insert(offset, KeySignature(ks))

    return score