Exemplo n.º 1
0
def create_midi(prediction_output):
    offset = 0
    output_notes = []

    for pattern in prediction_output:
        if ('.' in pattern) or pattern.isdigit():
            notes_in_chord = pattern.split('.')
            notes = []
            for current_note in notes_in_chord:
                new_note = note.Note(int(current_note))
                new_note.storedInstrument = instrument.Flute()
                notes.append(new_note)
            new_chord = chord.Chord(notes)
            new_chord.offset = offset
            output_notes.append(new_chord)

        else:
            new_note = note.Note(pattern)
            new_note.offset = offset
            new_note.storedInstrument = instrument.Flute()
            output_notes.append(new_note)

        offset += 0.5

    midi_stream = stream.Stream(output_notes)

    midi_stream.write('midi', fp='test_output.mid')
Exemplo n.º 2
0
def generate_music(result_data, instr, filename):
    """生成mid音乐,然后进行保存

    :param result_data: [音符列表]
    :type result_data: [list]
    :param filename: [文件名]
    :type filename: [str]
    """
    result_data = [str(data) for data in result_data]
    offset = 0
    output_notes = []
    # 生成 Note(音符)或 Chord(和弦)对象
    for data in result_data:
        if ('.' in data) or data.isdigit():
            notes_in_chord = data.split('.')
            notes = []
            if instr == 'Flute':
                output_notes.append(instrument.Flute())
            elif instr == 'Piano':
                output_notes.append(instrument.Piano())
            elif instr == 'Bass':
                output_notes.append(instrument.Bass())
            elif instr == 'Guitar':
                output_notes.append(instrument.Guitar())
            elif instr == 'Saxophone':
                output_notes.append(instrument.Saxophone())
            elif instr == 'Violin':
                output_notes.append(instrument.Violin())

            for current_note in notes_in_chord:
                new_note = note.Note(int(current_note))
                #new_note.storedInstrument = instrument.Flute()
                notes.append(new_note)
            new_chord = chord.Chord(notes)
            new_chord.offset = offset
            output_notes.append(new_chord)

        else:
            if instr == 'Flute':
                output_notes.append(instrument.Flute())
            elif instr == 'Piano':
                output_notes.append(instrument.Piano())
            elif instr == 'Bass':
                output_notes.append(instrument.Bass())
            elif instr == 'Guitar':
                output_notes.append(instrument.Guitar())
            elif instr == 'Saxophone':
                output_notes.append(instrument.Saxophone())
            elif instr == 'Violin':
                output_notes.append(instrument.Violin())
            new_note = note.Note(data)
            new_note.offset = offset
            #new_note.storedInstrument = instrument.Flute()
            output_notes.append(new_note)
        offset += 1
    # 创建音乐流(Stream)
    midi_stream = stream.Stream(output_notes)
    # 写入 MIDI 文件
    midi_stream.write('midi', fp=filename + '.mid')
Exemplo n.º 3
0
    def play(self, num=None, save=False, autosave=False):
        """
        This function takes in a song in ABC format string and plays it using music21 and pygame modules
        Note: Timidity must also be installed, as it's config file is required for the stream object.
        :param num: index of the ABC song
        :param save: If true, prompts the user if they want to save the tune after playing.
        superseded by autosave
        :param autosave: If true, automatically save the song after playing it.
        :return: None
        """

        if num is None: num = random.randint(0, len(self.tunes)-1)
        abc = self.header + self.tunes[num]

        try:
            # convert abc format to stream object and add the harp instrument
            tune = converter.parse(abc, format='abc')
            for p in tune.parts: p.insert(0, instrument.Flute())

            # Emit a tone to break up consecutive plays
            player = StreamPlayer(converter.parse(self.header + 'z12C12z12', format='abc'))
            player.play()

            # play music using pygame stream player
            player = StreamPlayer(tune)
            print("Playing tune #{}\nABC:   {}\n".format(num, self.tunes[num]))
            player.play()

            if autosave:
                self.save_tune(num)
            elif save and input('Would you like to save the song as a MIDI file? Y/N:   ').upper() == 'Y':
                self.save_tune(num)
        except AccidentalException:
            print('Accidental Exception thrown in ABC:')
            print(abc)
Exemplo n.º 4
0
    def generate(self, seq_len, a_par=0):
        pattern = self.model_inp[self.start]
        prediction_output = []
        for note_index in range(seq_len):
            prediction_input = pattern.reshape(1, seq_len, 2,
                                               len(self.sorted_notes))
            prediction_input = prediction_input / float(len(self.sorted_notes))
            predictions = self.model.predict(prediction_input, verbose=0)[0]
            for prediction in predictions:
                index = np.argmax(prediction[0])
                duration_i = np.argmax(prediction[1])

                for name, value in self.sorted_notes.items():
                    if value == index:
                        result = name
                        break
                    else:
                        result = None

                for name, value in self.sorted_durations.items():
                    if value == duration_i:
                        duration = name
                        break
                    else:
                        duration = None

                prediction_output.append((result, Duration(duration)))
                result = np.zeros_like(prediction)
                result[0][index] = 1
                result[1][duration_i] = 1
                pattern = np.concatenate([pattern, [result]])
            pattern = pattern[len(pattern) - seq_len:len(pattern)]

        offset = 0
        output_notes = []
        for pattern, duration in prediction_output:
            if pattern.isdigit() or ('.' in pattern):
                notes_in_chord = pattern.split('.')
                notes = []
                for current_note in notes_in_chord:
                    new_note = Note(int(current_note))
                    new_note.duration = duration
                    new_note.storedInstrument = instrument.PanFlute()
                    notes.append(new_note)
                new_chord = Chord(notes)
                new_chord.offset = offset
                output_notes.append(new_chord)
            else:
                new_note = Note(pattern)
                new_note.offset = offset
                new_note.storedInstrument = instrument.Flute()
                output_notes.append(new_note)
            offset += 0.6

        midi_stream = stream.Stream(output_notes)
        midi_stream.write('midi',
                          fp=f'my_music/{self.model.name}_{self.start}.mid')
Exemplo n.º 5
0
 def change_instrument(self, choice):
     instruments = [
         instrument.Piano(),
         instrument.AcousticGuitar(),
         instrument.Violin(),
         instrument.Flute(),
         instrument.Mandolin()
     ]
     self.actual_instrument = instruments[choice]
     self.melody_stream[0] = self.actual_instrument
Exemplo n.º 6
0
def create_midi(prediction_output, output_tag, sequence_length, offset_adj):
    print("\n**Creating midi**")
    offset = 0
    output_notes = []

    for pattern in prediction_output:
        # prepares chords (if) and notes (else)
        if ('.' in pattern) or pattern.isdigit():
            notes_in_chord = pattern.split('.')
            notes = []
            for current_note in notes_in_chord:
                new_note = note.Note(int(current_note))
                new_note.storedInstrument = instrument.Flute()
                notes.append(new_note)
            new_chord = chord.Chord(notes)
            new_chord.offset = offset
            output_notes.append(new_chord)
        else:
            new_note = note.Note(pattern)
            new_note.offset = offset
            new_note.storedInstrument = instrument.Flute()

            output_notes.append(new_note)
        offset += offset_adj  #0.5

    print("Generating {} notes stored as {}".format(len(output_notes),
                                                    type(output_notes)))
    midi_stream = stream.Stream(output_notes)
    midi_file = output_tag + 'lstm_midi.mid'
    midi_stream.write('midi', fp=midi_file)
    print("Midi saved at: {}".format(midi_file))

    output_notes_file = output_tag + 'output_notes'
    with open(output_notes_file, 'wb') as f:
        pickle.dump(output_notes, f)
    print("Output notes/chords stored as {} then pickled at {}".format(
        type(output_notes), output_notes_file))
    return output_notes, midi_file
Exemplo n.º 7
0
 def testMultipleInstruments(self):
     '''
     This is a score for two woodwind players both doubling on
     flute and oboe. They both switch to flute and then back to oboe.
     There are six m21 instruments to represent this, but the
     <score-instrument> tags need just four, since no
     musicXML <part> needs two oboes in it, etc., unless
     there is a patch change/MIDI instrument change.
     '''
     p1 = stream.Part([
         stream.Measure([instrument.Oboe(),
                         note.Note(type='whole')]),
         stream.Measure([instrument.Flute(),
                         note.Note(type='whole')]),
         stream.Measure([instrument.Oboe(),
                         note.Note(type='whole')]),
     ])
     p2 = stream.Part([
         stream.Measure([instrument.Oboe(),
                         note.Note(type='whole')]),
         stream.Measure([instrument.Flute(),
                         note.Note(type='whole')]),
         stream.Measure([instrument.Oboe(),
                         note.Note(type='whole')]),
     ])
     s = stream.Score([p1, p2])
     scEx = ScoreExporter(s)
     tree = scEx.parse()
     self.assertEqual(len(tree.findall('.//score-instrument')), 4)
     self.assertEqual(len(tree.findall('.//measure/note/instrument')), 6)
     self.assertEqual(
         tree.find('.//score-instrument').get('id'),
         tree.find('.//measure/note/instrument').get('id'))
     self.assertNotEqual(
         tree.find('.//score-instrument').get('id'),
         tree.findall('.//measure/note/instrument')[-1].get('id'))
Exemplo n.º 8
0
def play_midi_at_tempo(midi_file, bpm, instrument_to_exclude):
    score = converter.parse(midi_file)
    new_score = stream.Score()
    #score_list = list(score)
    # score_list[3].show('midi')
    instruments = []
    for part in score:
        # part.show('midi')
        # print(part.getInstrument().)
        # if part.getInstrument().midiProgram != 0:
        if part.getInstrument().instrumentName != None and part.getInstrument(
        ).instrumentName != instrument_to_exclude:
            if part.getInstrument().instrumentName == 'Mandolin':
                part.insert(0, instrument.StringInstrument())
                # part.insert(0, volume.Volume(velocity=40))

            if part.getInstrument().instrumentName == 'Fretless Bass':
                part.insert(0, instrument.FretlessBass())
                # part.insert(0, volume.Volume(velocity=90))

            if part.getInstrument().instrumentName == 'Alto':
                part.insert(0, instrument.Flute())

            #print(part.getInstrument().instrumentName, part.getInstrument().midiProgram)
            for element in part.flat:
                if isinstance(element, tempo.MetronomeMark):
                    print('Original tempo: ', element.number)
                    gain = bpm / element.number
                    element.number *= gain
                    print('New tempo: ', element.number)
            new_score.append(part)

            instruments.append(part.getInstrument().instrumentName)

    new_score.write('midi', fp=bridge_temp_file)

    instruments.append(instrument_to_exclude)
    return instruments
Exemplo n.º 9
0
def get_instruments(genre, ontology):
    programs = []
    if genre.label[0] == "Blues":
        programs.append(instrument.AcousticGuitar().midiProgram)
        programs.append(instrument.Harmonica().midiProgram)
        programs.append(instrument.TomTom().midiProgram)
    elif genre.label[0] == "Folk":
        programs.append(instrument.Banjo().midiProgram)
        programs.append(instrument.AcousticBass().midiProgram)
        programs.append(instrument.Piano().midiProgram)
    elif genre.label[0] == "Rock":
        programs.append(instrument.ElectricGuitar().midiProgram)
        programs.append(instrument.ElectricBass().midiProgram)
        programs.append(instrument.BassDrum().midiProgram)
    elif genre.label[0] == "Classical":
        programs.append(instrument.Violin().midiProgram)
        programs.append(instrument.Oboe().midiProgram)
        programs.append(instrument.Flute().midiProgram)
        programs.append(instrument.Viola().midiProgram)
    elif genre.label[0] == "Country":
        programs.append(instrument.AcousticGuitar().midiProgram)
        programs.append(instrument.Banjo().midiProgram)
        programs.append(instrument.TomTom().midiProgram)
    return programs
Exemplo n.º 10
0
def convertor(out, s):

    if(out == "Flute"):
        print("Flute")
        for p in s.parts:
            p.insert(0, instrument.Flute())
        s.write('midi', 'C:/Users/Ciprian/PycharmProjects/AI-music/static/midi/Flute.mid')
    
    elif (out == "Violin"):
        print("Violin")
        for p in s.parts:
            p.insert(0, instrument.Violin())
        s.write('midi', 'C:/Users/Ciprian/PycharmProjects/AI-music/static/midi/Violin.mid')
    
    elif (out == "Piano"):
        print("Piano")
        for p in s.parts:
            p.insert(0, instrument.Piano())
        s.write('midi', 'C:/Users/Ciprian/PycharmProjects/AI-music/static/midi/Piano.mid')
    elif (out == "Celesta"):
        print("Celesta")
        for p in s.parts:
            p.insert(0, instrument.Celesta())
    s.write('midi', 'C:/Users/Ciprian/PycharmProjects/AI-music/static/midi/Celesta.mid')