当前位置: 首页>>代码示例>>Python>>正文


Python pretty_midi.Note方法代码示例

本文整理汇总了Python中pretty_midi.Note方法的典型用法代码示例。如果您正苦于以下问题:Python pretty_midi.Note方法的具体用法?Python pretty_midi.Note怎么用?Python pretty_midi.Note使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pretty_midi的用法示例。


在下文中一共展示了pretty_midi.Note方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: decode_to_midi

# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Note [as 别名]
def decode_to_midi(self, pianoroll):
    """Decodes pianoroll into midi."""
    # NOTE: Assumes four separate instruments ordered from high to low.
    midi_data = pretty_midi.PrettyMIDI()
    duration = self.qpm / 60 * self.shortest_duration
    tt, pp, ii = pianoroll.shape
    for i in range(ii):
      notes = []
      for p in range(pp):
        for t in range(tt):
          if pianoroll[t, p, i]:
            notes.append(
                pretty_midi.Note(
                    velocity=100,
                    pitch=self.min_pitch + p,
                    start=t * duration,
                    end=(t + 1) * duration))
      notes = merge_held(notes)

      instrument = pretty_midi.Instrument(program=self.programs[i] - 1)
      instrument.notes.extend(notes)
      midi_data.instruments.append(instrument)
    return midi_data 
开发者ID:magenta,项目名称:magenta,代码行数:25,代码来源:lib_pianoroll.py

示例2: set_piano_roll_to_instrument

# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Note [as 别名]
def set_piano_roll_to_instrument(piano_roll, instrument, velocity=100, tempo=120.0, beat_resolution=24):
    # Calculate time per pixel
    tpp = 60.0/tempo/float(beat_resolution)
    # Create piano_roll_search that captures note onsets and offsets
    piano_roll = piano_roll.reshape((piano_roll.shape[0] * piano_roll.shape[1], piano_roll.shape[2]))
    piano_roll_diff = np.concatenate((np.zeros((1,128),dtype=int), piano_roll, np.zeros((1,128),dtype=int)))  
    piano_roll_search = np.diff(piano_roll_diff.astype(int), axis=0)
    # Iterate through all possible(128) pitches
    for note_num in range(128):
        # Search for notes
        start_idx = (piano_roll_search[:,note_num] > 0).nonzero()
        start_time = tpp*(start_idx[0].astype(float))
        end_idx = (piano_roll_search[:,note_num] < 0).nonzero()
        end_time = tpp*(end_idx[0].astype(float))
        # Iterate through all the searched notes
        for idx in range(len(start_time)):
            # Create an Note object with corresponding note number, start time and end time
            note = pretty_midi.Note(velocity=velocity, pitch=note_num, start=start_time[idx], end=end_time[idx])
            # Add the note to the Instrument object
            instrument.notes.append(note)
    # Sort the notes by their start time
    instrument.notes.sort(key=lambda note: note.start) 
开发者ID:llSourcell,项目名称:AI_For_Music_Composition,代码行数:24,代码来源:write_midi.py

示例3: piano_roll_to_midi

# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Note [as 别名]
def piano_roll_to_midi(piano_roll, sample_rate):
    """Convert the piano roll to a PrettyMIDI object.
    See: http://github.com/craffel/examples/reverse_pianoroll.py
    """
    midi = pretty_midi.PrettyMIDI()
    instrument = pretty_midi.Instrument(0)
    midi.instruments.append(instrument)
    padded_roll = np.pad(piano_roll, [(1, 1), (0, 0)], mode='constant')
    changes = np.diff(padded_roll, axis=0)
    notes = np.full(piano_roll.shape[1], -1, dtype=np.int)
    for tick, pitch in zip(*np.where(changes)):
        prev = notes[pitch]
        if prev == -1:
            notes[pitch] = tick
            continue
        notes[pitch] = -1
        instrument.notes.append(pretty_midi.Note(
            velocity=100,
            pitch=pitch,
            start=prev / float(sample_rate),
            end=tick / float(sample_rate)))
    return midi 
开发者ID:google,项目名称:vae-seq,代码行数:24,代码来源:dataset.py

示例4: to_midi

# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Note [as 别名]
def to_midi(notes, t_unit=0.02):
    midi = pretty_midi.PrettyMIDI()
    piano = pretty_midi.Instrument(program=0)
    
    
    l, u = find_min_max_stren(notes)
    s_low = 60
    s_up = 127
    v_map = lambda stren: int(s_low+((s_up-s_low)*((stren-l)/(u-l+0.0001))))
    
    low_b = note_to_midi("A0")
    coll = set()
    for nn in notes:
        pitch = nn["pitch"] + low_b
        start = nn["start"] * t_unit
        end = nn["end"] * t_unit
        volume = v_map(nn["stren"])
        coll.add(pitch)
        m_note = pretty_midi.Note(velocity=volume, pitch=pitch, start=start, end=end)
        piano.notes.append(m_note)
    midi.instruments.append(piano)
    return midi 
开发者ID:BreezeWhite,项目名称:Music-Transcription-with-Semantic-Segmentation,代码行数:24,代码来源:postprocess.py

示例5: __init__

# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Note [as 别名]
def __init__(self, notes=[]):
        self.notes = []
        if notes:
            for note in notes:
                assert isinstance(note, Note)
            notes = filter(lambda note: note.end >= note.start, notes)
            self.add_notes(list(notes)) 
开发者ID:djosix,项目名称:Performance-RNN-PyTorch,代码行数:9,代码来源:sequence.py

示例6: to_note_seq

# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Note [as 别名]
def to_note_seq(self):
        time = 0
        notes = []

        velocity = DEFAULT_VELOCITY
        velocity_bins = EventSeq.get_velocity_bins()

        last_notes = {}

        for event in self.events:
            if event.type == 'note_on':
                pitch = event.value + EventSeq.pitch_range.start
                note = Note(velocity, pitch, time, None)
                notes.append(note)
                last_notes[pitch] = note

            elif event.type == 'note_off':
                pitch = event.value + EventSeq.pitch_range.start

                if pitch in last_notes:
                    note = last_notes[pitch]
                    note.end = max(time, note.start + MIN_NOTE_LENGTH)
                    del last_notes[pitch]

            elif event.type == 'velocity':
                index = min(event.value, velocity_bins.size - 1)
                velocity = velocity_bins[index]

            elif event.type == 'time_shift':
                time += EventSeq.time_shift_bins[event.value]

        for note in notes:
            if note.end is None:
                note.end = note.start + DEFAULT_NOTE_LENGTH

            note.velocity = int(note.velocity)

        return NoteSeq(notes) 
开发者ID:djosix,项目名称:Performance-RNN-PyTorch,代码行数:40,代码来源:sequence.py

示例7: get_merged_pianoroll

# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Note [as 别名]
def get_merged_pianoroll(self, mode='sum'):
        """
        Return a merged piano-roll.

        Parameters
        ----------
        mode : {'sum', 'max', 'any'}
            Indicate the merging function to apply along the track axis. Default
            to 'sum'.

            - In 'sum' mode, the piano-roll of the merged track is the summation
              of the collected piano-rolls. Note that for binarized piano-roll,
              integer summation is performed.
            - In 'max' mode, for each pixel, the maximal value among the
              collected piano-rolls is assigned to the merged piano-roll.
            - In 'any' mode, the value of a pixel in the merged piano-roll is
              True if any of the collected piano-rolls has nonzero value at that
              pixel; False if all piano-rolls are inactive (zero-valued) at that
              pixel.

        Returns
        -------
        merged : np.ndarray, shape=(num_time_step, 128)
            The merged piano-rolls.

        """
        if mode not in ('max', 'sum', 'any'):
            raise ValueError("`mode` must be one of {'max', 'sum', 'any'}")

        stacked = self.get_stacked_pianorolls()

        if mode == 'any':
            merged = np.any(stacked, axis=2)
        elif mode == 'sum':
            merged = np.sum(stacked, axis=2)
        elif mode == 'max':
            merged = np.max(stacked, axis=2)

        return merged 
开发者ID:salu133445,项目名称:lakh-pianoroll-dataset,代码行数:41,代码来源:multitrack.py

示例8: pianoroll_to_midi

# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Note [as 别名]
def pianoroll_to_midi(pianoroll, midi_folder, filename, instrument_name, bpm):
    if not os.path.exists(midi_folder):
        os.makedirs(midi_folder) 
    midi = pm.PrettyMIDI(initial_tempo=bpm, resolution=200)    
    midi.time_signature_changes.append(pm.TimeSignature(4, 4, 0))
    piano_program = pm.instrument_name_to_program(instrument_name)
    piano = pm.Instrument(program=piano_program)
    ind = np.nonzero(pianoroll)
    for i in range(ind[0].shape[0]):
        note = pm.Note(velocity=80, pitch=ind[1][i], start=(60/(2*bpm))*ind[0][i], end=(60/(2*bpm))*ind[0][i] + 0.25)
        piano.notes.append(note)
    midi.instruments.append(piano)
#    print(midi.get_tempo_changes())
    midi.write(midi_folder + filename+'.mid') 
开发者ID:brunnergino,项目名称:JamBot,代码行数:16,代码来源:midi_functions.py

示例9: pianoroll_to_midi_continous

# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Note [as 别名]
def pianoroll_to_midi_continous(pianoroll, midi_folder, filename, instrument_name, bpm):
    if not os.path.exists(midi_folder):
        os.makedirs(midi_folder)
    midi = pm.PrettyMIDI(initial_tempo=bpm, resolution=200)    
    midi.time_signature_changes.append(pm.TimeSignature(4, 4, 0))
    piano_program = pm.instrument_name_to_program(instrument_name)
    piano = pm.Instrument(program=piano_program)
        
    tracker = []
    start_times  = dict()
    for i, note_vector in enumerate(pianoroll):
        notes = list(note_vector.nonzero()[0])
#        print('notes',notes)
        removal_list = []
        for note in tracker:
            if note in notes and (i)%8 is not 0:
#                print('removing', note, 'from notes')
                notes.remove(note)
            else:
                midi_note = pm.Note(velocity=80, pitch=note, start=(60/(2*bpm))*start_times[note], end=(60/(2*bpm))*i)
                piano.notes.append(midi_note)
#                print('removing', note, 'from tracker')
                removal_list.append(note)
        for note in removal_list:
            tracker.remove(note)
#        print('tracker',tracker)
#        print('notes',notes)

        for note in notes:
            tracker.append(note)
            start_times[note]=i
#        print('tracker',tracker)
#        print('-'*50)
    midi.instruments.append(piano)
#    print(midi.get_tempo_changes())
    midi.write(midi_folder + filename+'.mid') 
开发者ID:brunnergino,项目名称:JamBot,代码行数:38,代码来源:midi_functions.py

示例10: write_test_note

# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Note [as 别名]
def write_test_note(path, duration, note):
    midi = pretty_midi.PrettyMIDI()
    instrument = pretty_midi.Instrument(0)
    instrument.notes.append(pretty_midi.Note(100, note, 0.0, duration))
    midi.instruments.append(instrument)
    midi.write(path) 
开发者ID:google,项目名称:vae-seq,代码行数:8,代码来源:dataset.py

示例11: save

# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Note [as 别名]
def save(self, file_path, note_df):
        '''
        Save MIDI file.
        
        Args:
            file_path:    File path of MIDI.
            note_df:      `pd.DataFrame` of note data.
            
        '''

        chord = pretty_midi.PrettyMIDI()
        for program in note_df.program.drop_duplicates().values.tolist():
            df = note_df[note_df.program == program]
            midi_obj = pretty_midi.Instrument(program=program)
            for i in range(df.shape[0]):
                note = pretty_midi.Note(
                    velocity=int(df.iloc[i, :]["velocity"]),
                    pitch=int(df.iloc[i, :]["pitch"]),
                    start=float(df.iloc[i, :]["start"]), 
                    end=float(df.iloc[i, :]["end"])
                )
                # Add it to our cello instrument
                midi_obj.notes.append(note)
            # Add the cello instrument to the PrettyMIDI object
            chord.instruments.append(midi_obj)
        # Write out the MIDI data
        chord.write(file_path) 
开发者ID:chimera0,项目名称:accel-brain-code,代码行数:29,代码来源:midi_controller.py

示例12: to_midi

# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Note [as 别名]
def to_midi(pred, out_path, velocity=100, threshold=0.4, t_unit=0.02):
    midi = pretty_midi.PrettyMIDI()
    piano = pretty_midi.Instrument(program=0) 
    
    notes = []
    pred = np.where(pred>threshold, 1, 0)   
    pred = merge_channels(pred)
    pitch_offset = librosa.note_to_midi("A0")
    #print("Transformed shape: ", pred.shape)
    
    plt.imshow(pred.transpose(), origin="lower", aspect=20)
    plt.savefig("{}.png".format(out_path), dpi=250)
    
    for i in range(pred.shape[1]):
        pp = pred[:, i]
        candy = np.where(pp > 0.5)[0]
        if len(candy) == 0:
            # No pitch present
            continue
        
        shift = np.insert(candy, 0, 0)[:-1]
        diff = candy - shift
        on_idx = np.where(diff>1)[0]
        onsets = candy[on_idx]
        offsets = shift[on_idx[1:]]
        offsets = np.append(offsets, candy[-1])

        for ii in range(len(onsets)):
            on_t = onsets[ii] * t_unit
            off_t = offsets[ii] * t_unit
            note = pretty_midi.Note(velocity=velocity, pitch=i+pitch_offset, start=on_t, end=off_t)
            notes.append(note)

    piano.notes = notes
    midi.instruments.append(piano)

    if not out_path.endswith(".mid"):
        out_path += ".mid"
    midi.write(out_path)

    return midi 
开发者ID:BreezeWhite,项目名称:Music-Transcription-with-Semantic-Segmentation,代码行数:43,代码来源:utils.py

示例13: get_merged_pianoroll

# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Note [as 别名]
def get_merged_pianoroll(self, mode="sum"):
        """
        Return the merged pianoroll.

        Parameters
        ----------
        mode : {'sum', 'max', 'any'}
            A string that indicates the merging strategy to apply along the
            track axis. Default to 'sum'.

            - In 'sum' mode, the merged pianoroll is the sum of all the
              pianorolls. Note that for binarized pianorolls, integer summation
              is performed.
            - In 'max' mode, for each pixel, the maximum value among all the
              pianorolls is assigned to the merged pianoroll.
            - In 'any' mode, the value of a pixel in the merged pianoroll is
              True if any of the pianorolls has nonzero value at that pixel;
              False if all pianorolls are inactive (zero-valued) at that pixel.

        Returns
        -------
        merged : np.ndarray, shape=(n_time_steps, 128)
            The merged pianoroll.

        """
        stacked = self.get_stacked_pianoroll()

        if mode == "any":
            merged = np.any(stacked, axis=2)
        elif mode == "sum":
            merged = np.sum(stacked, axis=2)
        elif mode == "max":
            merged = np.max(stacked, axis=2)
        else:
            raise ValueError("`mode` must be one of {'max', 'sum', 'any'}.")

        return merged 
开发者ID:salu133445,项目名称:pypianoroll,代码行数:39,代码来源:multitrack.py

示例14: merge_tracks

# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Note [as 别名]
def merge_tracks(self, track_indices=None, mode='sum', program=0,
                     is_drum=False, name='merged', remove_merged=False):
        """
        Merge piano-rolls of tracks specified by `track_indices`. The merged
        track will have program number as given by `program` and drum indicator
        as given by `is_drum`. The merged track will be appended at the end of
        the track list.

        Parameters
        ----------
        track_indices : list
            List of indices that indicates which tracks to merge. If None,
            default to merge all tracks.
        mode : {'sum', 'max', 'any'}
            Indicate the merging function to apply along the track axis. Default
            to 'sum'.

            - In 'sum' mode, the piano-roll of the merged track is the summation
              of the collected piano-rolls. Note that for binarized piano-roll,
              integer summation is performed.
            - In 'max' mode, for each pixel, the maximal value among the
              collected piano-rolls is assigned to the merged piano-roll.
            - In 'any' mode, the value of a pixel in the merged piano-roll is
              True if any of the collected piano-rolls has nonzero value at that
              pixel; False if all piano-rolls are inactive (zero-valued) at that
              pixel.

        program: int
            Program number to be assigned to the merged track. Available values
            are 0 to 127.
        is_drum : bool
            Drum indicator to be assigned to the merged track.
        name : str
            Name to be assigned to the merged track. Default to 'merged'.
        remove_merged : bool
            True to remove the merged tracks from the track list. False to keep
            them. Default to False.

        """
        if mode not in ('max', 'sum', 'any'):
            raise ValueError("`mode` must be one of {'max', 'sum', 'any'}")

        merged = self[track_indices].get_merged_pianoroll(mode)

        merged_track = Track(merged, program, is_drum, name)
        self.append_track(merged_track)

        if remove_merged:
            self.remove_tracks(track_indices) 
开发者ID:salu133445,项目名称:lakh-pianoroll-dataset,代码行数:51,代码来源:multitrack.py

示例15: merge_tracks

# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Note [as 别名]
def merge_tracks(
        self,
        track_indices=None,
        mode="sum",
        program=0,
        is_drum=False,
        name="merged",
        remove_merged=False,
    ):
        """
        Merge pianorolls of the tracks specified by `track_indices`. The merged
        track will have program number as given by `program` and drum indicator
        as given by `is_drum`. The merged track will be appended at the end of
        the track list.

        Parameters
        ----------
        track_indices : list
            The indices of tracks to be merged. Defaults to all the tracks.
        mode : {'sum', 'max', 'any'}
            A string that indicates the merging strategy to apply along the
            track axis. Default to 'sum'.

            - In 'sum' mode, the merged pianoroll is the sum of the collected
              pianorolls. Note that for binarized pianorolls, integer summation
              is performed.
            - In 'max' mode, for each pixel, the maximum value among the
              collected pianorolls is assigned to the merged pianoroll.
            - In 'any' mode, the value of a pixel in the merged pianoroll is
              True if any of the collected pianorolls has nonzero value at that
              pixel; False if all the collected pianorolls are inactive
              (zero-valued) at that pixel.

        program: int
            A program number according to General MIDI specification [1].
            Available values are 0 to 127. Defaults to 0 (Acoustic Grand Piano).
        is_drum : bool
            A boolean number that indicates whether it is a percussion track.
            Defaults to False.
        name : str
            A name to be assigned to the merged track. Defaults to 'merged'.
        remove_merged : bool
            True to remove the source tracks from the track list. False to keep
            them. Defaults to False.

        References
        ----------
        [1] https://www.midi.org/specifications/item/gm-level-1-sound-set

        """
        if mode not in ("max", "sum", "any"):
            raise ValueError("`mode` must be one of {'max', 'sum', 'any'}.")

        merged = self[track_indices].get_merged_pianoroll(mode)

        merged_track = Track(merged, program, is_drum, name)
        self.append_track(merged_track)

        if remove_merged:
            self.remove_tracks(track_indices) 
开发者ID:salu133445,项目名称:pypianoroll,代码行数:62,代码来源:multitrack.py


注:本文中的pretty_midi.Note方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。