Exemple #1
0
def _play(mid, start, end):
    """ Play the selection """
    if start is None:
        start = 0
    # Trim the midi
    trimmed = EventStreamSlice(mid, start,
                               end).to_event_stream(repeat_playing=False)
    # Show info about the clip
    print "Start tick: %s" % start
    print "End tick: %s" % end
    print "First event tick: %s" % _ticks_to_ticks(mid, start)
    print "Last event tick: %s" % _ticks_to_ticks(mid, end, before=True)
    start_time = float(_get_time(mid, start)) / 1000.0
    print "Start time: %ss" % start_time
    print "Last event time: %ss" % (float(_get_time(mid, end, before=True)) /
                                    1000.0)
    print
    print "Playing MIDI. Hit ctrl+C to stop"
    # Record playing time
    timer = ExecutionTimer()
    try:
        play_stream(trimmed, block=True)
    except KeyboardInterrupt:
        length = timer.get_time()
        print "\nPlayed for %.2f seconds (stopped ~%.2fs)" % (
            length, start_time + length)
Exemple #2
0
def main():
    usage = "%prog [options] <in-file>"
    description = "Play music using the Harmonical. This allows you to "\
        "play music specified precisely in the tonal space. By default, "\
        "plays back the input, but can also output to a file."
    parser = OptionParser(usage=usage, description=description)
    parser.add_option('-o', '--output', dest="outfile", action="store", help="output the result to a wave file instead of playing back.")
    parser.add_option('-m', '--midi', dest="midi", action="store_true", help="generate midi data, not audio. Depends on the input format supporting midi file generation.")
    options, arguments = parse_args_with_config(parser)
    
    filename = arguments[0]
    
    # Load up the input file
    infile = HarmonicalInputFile.from_file(filename)
    if options.midi:
        midi = infile.render_midi()
        
        if options.outfile is not None:
            # Output a midi file
            write_midifile(midi, options.outfile)
            print >>sys.stderr, "Saved midi data to %s" % options.outfile
        else:
            print >>sys.stderr, "Playing..."
            play_stream(midi, block=True)
    else:
        print >>sys.stderr, "Generating audio..."
        audio = infile.render()
        
        if options.outfile is not None:
            # Output to a file instead of playing
            save_wave_data(audio, options.outfile)
            print >>sys.stderr, "Saved data to %s" % options.outfile
        else:
            print >>sys.stderr, "Playing..."
            play_audio(audio, wait_for_end=True)
Exemple #3
0
 def play_segmidi(segmidi, chunk=None):
     from jazzparser.utils.midi import play_stream
     # Select an individual chunk if a number is given
     if chunk is None:
         strms = enumerate(segmidi)
     else:
         strms = [(chunk, segmidi[chunk])]
     
     try:
         for i,strm in strms:
             print "Playing chunk %d (%d events)" % (i, len(strm.trackpool))
             play_stream(strm, block=True)
     except KeyboardInterrupt:
         print "Stopping playback"
Exemple #4
0
def main():
    usage = "%prog [options] <midi-file>"
    description = "Divides a midi file into chunks, with a given size and "\
        "offset, and plays "\
        "the chunks consecutively, with a gap between each."
    parser = OptionParser(usage=usage, description=description)
    parser.add_option('-t', '--time-unit', dest="time_unit", action="store", type="float", help="size of chunks in crotchet beats (according to the midi file's resolution)", default=4)
    parser.add_option('-o', '--tick-offset', dest="tick_offset", action="store", type="int", help="offset of the first chunk in midi ticks", default=0)
    parser.add_option('-g', '--gap', dest="gap", action="store", type="float", help="time to wait between playing each chunk in seconds (potentially float). It will take some time to load the chunk and the sequencer usually pauses before reporting it's done: this is not included in this value", default=0.0)
    parser.add_option('-p', '--print', dest="print_events", action="store_true", help="print out all events for each chunk")
    parser.add_option('--pno', '--print-note-ons', dest="print_note_ons", action="store_true", help="print only note-on events")
    parser.add_option('--force-res', dest="force_res", action="store", type="int", help="force the midi file's resolution to be the given value, rather than using that read from the file")
    parser.add_option('-s', '--start', dest="start", action="store", type="int", help="chunk number to start at", default=0)
    options, arguments = parse_args_with_config(parser)
    
    filename = arguments[0]
    
    # Load up the input midi file
    infile = read_midifile(filename, force_resolution=options.force_res)
    handler = MidiHandler(infile,
                          time_unit=options.time_unit,
                          tick_offset=options.tick_offset)
    slices = handler.get_slices()
    
    # Start at the requested chunk
    slices = slices[options.start:]
    
    print "Playing %d-beat chunks with a %d-tick offset" % (options.time_unit, options.tick_offset)
    if options.start > 0:
        print "Start from chunk %d" % options.start
    print "Total chunks: %d" % len(slices)
    print "Ctrl+C to exit"
    print
    
    try:
        for i,slc in enumerate(slices):
            strm = slc.to_event_stream(cancel_playing=True)
            print "Playing chunk %d: %d-%d (%d events)" % (i, slc.start, slc.end,len(strm.trackpool))
            if options.print_events:
                print "\n".join("  %s" % ev for ev in sorted(strm.trackpool))
            elif options.print_note_ons:
                print "\n".join("  %s" % ev for ev in sorted(strm.trackpool) \
                                                    if type(ev) is NoteOnEvent)
            
            play_stream(strm, block=True)
            if options.gap > 0.0:
                print "  Waiting %s seconds..." % options.gap
                time.sleep(options.gap)
    except KeyboardInterrupt:
        print "Exiting"
Exemple #5
0
    def play(self):
        from midi.slice import EventStreamSlice
        from jazzparser.utils.midi import play_stream

        slc = EventStreamSlice(self.midi.midi_stream, self.start, self.end)
        strm = slc.to_event_stream()
        return play_stream(strm)
Exemple #6
0
 def play_from_here(self, *args, **kwargs):
     if self.selected_pos is not None:
         from jazzparser.utils.midi import play_stream
         global currently_playing
         # Work out what time to start at from the click position
         start_time = self.score.x_to_midi_tick(self.selected_pos)
         slc = self.score.stream.slice(start_time)
         currently_playing = play_stream(slc.to_event_stream())
Exemple #7
0
 def play_from_here(self, *args, **kwargs):
     if self.selected_pos is not None:
         from jazzparser.utils.midi import play_stream
         global currently_playing
         # Work out what time to start at from the click position
         start_time = self.score.x_to_midi_tick(self.selected_pos)
         slc = self.score.stream.slice(start_time)
         currently_playing = play_stream(slc.to_event_stream())
def _play(mid, start, end):
    """ Play the selection """
    if start is None:
        start = 0
    # Trim the midi
    trimmed = EventStreamSlice(mid, start, end).to_event_stream(repeat_playing=False)
    # Show info about the clip
    print "Start tick: %s" % start
    print "End tick: %s" % end
    print "First event tick: %s" % _ticks_to_ticks(mid, start)
    print "Last event tick: %s" % _ticks_to_ticks(mid, end, before=True)
    start_time = float(_get_time(mid, start)) / 1000.0
    print "Start time: %ss" % start_time
    print "Last event time: %ss" % (float(_get_time(mid, end, before=True)) / 1000.0)
    print
    print "Playing MIDI. Hit ctrl+C to stop"
    # Record playing time
    timer = ExecutionTimer()
    try:
        play_stream(trimmed, block=True)
    except KeyboardInterrupt:
        length = timer.get_time()
        print "\nPlayed for %.2f seconds (stopped ~%.2fs)" % (length, start_time + length)
def main():
    usage = "%prog [options] <input>"
    description = "Divides midi files into chunks, with size and offset, "\
        "given in the input file, and plays "\
        "the chunks consecutively. Input is a segmented bulk midi input file."
    parser = OptionParser(usage=usage, description=description)
    parser.add_option(
        '-g',
        '--gap',
        dest="gap",
        action="store",
        type="float",
        help=
        "time to wait between playing each chunk in seconds (potentially float). It will take some time to load the chunk and the sequencer usually pauses before reporting it's done: this is not included in this value",
        default=0.0)
    parser.add_option('-p',
                      '--print',
                      dest="print_events",
                      action="store_true",
                      help="print out all events for each chunk")
    parser.add_option('--pno',
                      '--print-note-ons',
                      dest="print_note_ons",
                      action="store_true",
                      help="print only note-on events")
    parser.add_option(
        '--fopt',
        dest="file_options",
        action="store",
        help=
        "options for file loading. Use '--fopt help' to see available options")
    options, arguments = parse_args_with_config(parser)

    filename = arguments[0]
    # Try getting a file from the command-line options
    input_data = command_line_input(filename=filename,
                                    filetype='bulk-segmidi',
                                    options=options.file_options)

    # Play each input in turn
    input_getter = iter(input_data)
    segmidi = input_getter.next()

    while True:
        print "###############################"
        print "Playing '%s'" % segmidi.name
        print "%s-beat chunks with a %d-tick offset\n" % \
                                    (segmidi.time_unit, segmidi.tick_offset)
        slices = list(segmidi)

        try:
            for i, strm in enumerate(slices):
                print "Playing chunk %d: %d events" % (i, len(strm.trackpool))
                if options.print_events:
                    print "\n".join("  %s" % ev
                                    for ev in sorted(strm.trackpool))
                elif options.print_note_ons:
                    print "\n".join("  %s" % ev for ev in sorted(strm.trackpool) \
                                                    if type(ev) is NoteOnEvent)
                # Play this midi chunk
                play_stream(strm, block=True)
                # Leave a gap before continuing
                if options.gap > 0.0:
                    time.sleep(options.gap)
        except KeyboardInterrupt:
            pass

        print "Continue to next song (<enter>); exit (x); play again (p)"
        command = raw_input(">> ").lower()
        if command == "x":
            sys.exit(0)
        elif command == "p":
            # Play again
            continue
        elif command == "":
            # Move to next
            segmidi = input_getter.next()
            continue
        else:
            print "Unknown command: %s" % command
            print "Playing again..."
            continue
    sys.exit(0)
def main():
    usage = "%prog [options] <input>"
    description = "Divides midi files into chunks, with size and offset, "\
        "given in the input file, and plays "\
        "the chunks consecutively. Input is a segmented bulk midi input file."
    parser = OptionParser(usage=usage, description=description)
    parser.add_option('-g', '--gap', dest="gap", action="store", type="float", help="time to wait between playing each chunk in seconds (potentially float). It will take some time to load the chunk and the sequencer usually pauses before reporting it's done: this is not included in this value", default=0.0)
    parser.add_option('-p', '--print', dest="print_events", action="store_true", help="print out all events for each chunk")
    parser.add_option('--pno', '--print-note-ons', dest="print_note_ons", action="store_true", help="print only note-on events")
    parser.add_option('--fopt', dest="file_options", action="store", help="options for file loading. Use '--fopt help' to see available options")
    options, arguments = parse_args_with_config(parser)
    
    filename = arguments[0]
    # Try getting a file from the command-line options
    input_data = command_line_input(filename=filename, 
                                    filetype='bulk-segmidi',
                                    options=options.file_options)
    
    # Play each input in turn
    input_getter = iter(input_data)
    segmidi = input_getter.next()
    
    while True:
        print "###############################"
        print "Playing '%s'" % segmidi.name
        print "%s-beat chunks with a %d-tick offset\n" % \
                                    (segmidi.time_unit, segmidi.tick_offset)
        slices = list(segmidi)
        
        try:
            for i,strm in enumerate(slices):
                print "Playing chunk %d: %d events" % (i, len(strm.trackpool))
                if options.print_events:
                    print "\n".join("  %s" % ev for ev in sorted(strm.trackpool))
                elif options.print_note_ons:
                    print "\n".join("  %s" % ev for ev in sorted(strm.trackpool) \
                                                    if type(ev) is NoteOnEvent)
                # Play this midi chunk
                play_stream(strm, block=True)
                # Leave a gap before continuing
                if options.gap > 0.0:
                    time.sleep(options.gap)
        except KeyboardInterrupt:
            pass
            
        print "Continue to next song (<enter>); exit (x); play again (p)"
        command = raw_input(">> ").lower()
        if command == "x":
            sys.exit(0)
        elif command == "p":
            # Play again
            continue
        elif command == "":
            # Move to next
            segmidi = input_getter.next()
            continue
        else:
            print "Unknown command: %s" % command
            print "Playing again..."
            continue
    sys.exit(0)
Exemple #11
0
 def play(self):
     from jazzparser.utils.midi import play_stream
     return play_stream(self.midi_stream)
Exemple #12
0
def main():
    usage = "%prog [options] <midi-input>"
    description = "Trims a MIDI file to the required start and end points. "\
        "By default, plays the trimmed MIDI (for testing) and can also write "\
        "it out to a file."
    parser = OptionParser(usage=usage, description=description)
    parser.add_option(
        "-s",
        "--start",
        dest="start",
        action="store",
        help="start point, in ticks as 'x', or in seconds as 'xs'")
    parser.add_option("-e",
                      "--end",
                      dest="end",
                      action="store",
                      help="end point (formatted as -s)")
    parser.add_option(
        "-o",
        "--output",
        dest="output",
        action="store",
        help=
        "MIDI file to output to. If given, output is stored instead of being played"
    )
    options, arguments = parser.parse_args()

    if len(arguments) == 0:
        print >> sys.stderr, "You must specify a MIDI file"
        sys.exit(1)
    mid = read_midifile(arguments[0])

    def _time_to_ticks(time, before=False):
        # Find the tick time of the first event after the given time
        #  or the last event before it
        mstime = int(time * 1000)
        if time is not None:
            previous = min(mid.trackpool)
            for ev in sorted(mid.trackpool):
                # Look for the first event after the time
                if ev.msdelay >= mstime:
                    if before:
                        # Return the previous event's tick
                        return previous.tick
                    else:
                        # Return this event's tick
                        return ev.tick
                previous = ev
        return max(mid.trackpool).tick

    def _ticks_to_ticks(ticks, before=False):
        # Find the tick time of the first event after the given time
        #  or the last event before it
        if ticks is not None:
            previous = min(mid.trackpool)
            for ev in sorted(mid.trackpool):
                # Look for the first event after the time
                if ev.tick >= ticks:
                    if before:
                        # Return the previous event's tick
                        return previous.tick
                    else:
                        # Return this event's tick
                        return ev.tick
                previous = ev
        return max(mid.trackpool).tick

    def _get_time(ticks, before=False):
        # Find the event time of the first event after the given tick time
        #  or the last event before it
        previous = min(mid.trackpool)
        if ticks is not None:
            for ev in sorted(mid.trackpool):
                # Look for the first event after the time in ticks
                if ev.tick >= ticks:
                    if before:
                        # Return the previous event's time
                        return previous.msdelay
                    else:
                        # Return this event's time
                        return ev.msdelay
                previous = ev
        return max(mid.trackpool).msdelay

    def _parse_time(val, before=False):
        if val.endswith("s"):
            # Value in seconds
            # Convert to ticks
            return _time_to_ticks(float(val[:-1]), before=before)
        else:
            return int(val)

    # Work out start and end points
    if options.start is not None:
        start = _parse_time(options.start, before=False)
    else:
        start = 0

    if options.end is not None:
        end = _parse_time(options.end, before=True)
    else:
        end = None

    if end is not None and start > end:
        print "Start time of %d ticks > end time of %d ticks" % (start, end)
        sys.exit(1)

    # Cut the stream to the desired start and end
    slc = EventStreamSlice(mid, start, end)
    trimmed_mid = slc.to_event_stream(repeat_playing=False)

    # Print out some info
    print "Start tick: %s" % start
    print "End tick: %s" % end
    print
    print "First event tick: %s" % _ticks_to_ticks(start)
    print "Last event tick: %s" % _ticks_to_ticks(end, before=True)
    print
    print "Start time: %ss" % (float(_get_time(start)) / 1000.0)
    print "Last event time: %ss" % (float(_get_time(end, before=True)) /
                                    1000.0)
    print
    print "%d events" % len(trimmed_mid.trackpool)

    # Record playing time
    timer = ExecutionTimer()

    if options.output is None:
        # Play the output by default
        try:
            play_stream(trimmed_mid, block=True)
        except KeyboardInterrupt:
            print "\nPlayed for %.2f seconds" % timer.get_time()
    else:
        # Output to a file
        outfile = os.path.abspath(options.output)
        write_midifile(trimmed_mid, outfile)
        print "Output written to %s" % outfile
Exemple #13
0
def main():
    usage = "%prog [options] <midi-file>"
    description = "Divides a midi file into chunks, with a given size and "\
        "offset, and plays "\
        "the chunks consecutively, with a gap between each."
    parser = OptionParser(usage=usage, description=description)
    parser.add_option(
        '-t',
        '--time-unit',
        dest="time_unit",
        action="store",
        type="float",
        help=
        "size of chunks in crotchet beats (according to the midi file's resolution)",
        default=4)
    parser.add_option('-o',
                      '--tick-offset',
                      dest="tick_offset",
                      action="store",
                      type="int",
                      help="offset of the first chunk in midi ticks",
                      default=0)
    parser.add_option(
        '-g',
        '--gap',
        dest="gap",
        action="store",
        type="float",
        help=
        "time to wait between playing each chunk in seconds (potentially float). It will take some time to load the chunk and the sequencer usually pauses before reporting it's done: this is not included in this value",
        default=0.0)
    parser.add_option('-p',
                      '--print',
                      dest="print_events",
                      action="store_true",
                      help="print out all events for each chunk")
    parser.add_option('--pno',
                      '--print-note-ons',
                      dest="print_note_ons",
                      action="store_true",
                      help="print only note-on events")
    parser.add_option(
        '--force-res',
        dest="force_res",
        action="store",
        type="int",
        help=
        "force the midi file's resolution to be the given value, rather than using that read from the file"
    )
    parser.add_option('-s',
                      '--start',
                      dest="start",
                      action="store",
                      type="int",
                      help="chunk number to start at",
                      default=0)
    options, arguments = parse_args_with_config(parser)

    filename = arguments[0]

    # Load up the input midi file
    infile = read_midifile(filename, force_resolution=options.force_res)
    handler = MidiHandler(infile,
                          time_unit=options.time_unit,
                          tick_offset=options.tick_offset)
    slices = handler.get_slices()

    # Start at the requested chunk
    slices = slices[options.start:]

    print "Playing %d-beat chunks with a %d-tick offset" % (
        options.time_unit, options.tick_offset)
    if options.start > 0:
        print "Start from chunk %d" % options.start
    print "Total chunks: %d" % len(slices)
    print "Ctrl+C to exit"
    print

    try:
        for i, slc in enumerate(slices):
            strm = slc.to_event_stream(cancel_playing=True)
            print "Playing chunk %d: %d-%d (%d events)" % (
                i, slc.start, slc.end, len(strm.trackpool))
            if options.print_events:
                print "\n".join("  %s" % ev for ev in sorted(strm.trackpool))
            elif options.print_note_ons:
                print "\n".join("  %s" % ev for ev in sorted(strm.trackpool) \
                                                    if type(ev) is NoteOnEvent)

            play_stream(strm, block=True)
            if options.gap > 0.0:
                print "  Waiting %s seconds..." % options.gap
                time.sleep(options.gap)
    except KeyboardInterrupt:
        print "Exiting"
def main():
    usage = "%prog [options] <midi-input>"
    description = (
        "Trims a MIDI file to the required start and end points. "
        "By default, plays the trimmed MIDI (for testing) and can also write "
        "it out to a file."
    )
    parser = OptionParser(usage=usage, description=description)
    parser.add_option(
        "-s", "--start", dest="start", action="store", help="start point, in ticks as 'x', or in seconds as 'xs'"
    )
    parser.add_option("-e", "--end", dest="end", action="store", help="end point (formatted as -s)")
    parser.add_option(
        "-o",
        "--output",
        dest="output",
        action="store",
        help="MIDI file to output to. If given, output is stored instead of being played",
    )
    options, arguments = parser.parse_args()

    if len(arguments) == 0:
        print >> sys.stderr, "You must specify a MIDI file"
        sys.exit(1)
    mid = read_midifile(arguments[0])

    def _time_to_ticks(time, before=False):
        # Find the tick time of the first event after the given time
        #  or the last event before it
        mstime = int(time * 1000)
        if time is not None:
            previous = min(mid.trackpool)
            for ev in sorted(mid.trackpool):
                # Look for the first event after the time
                if ev.msdelay >= mstime:
                    if before:
                        # Return the previous event's tick
                        return previous.tick
                    else:
                        # Return this event's tick
                        return ev.tick
                previous = ev
        return max(mid.trackpool).tick

    def _ticks_to_ticks(ticks, before=False):
        # Find the tick time of the first event after the given time
        #  or the last event before it
        if ticks is not None:
            previous = min(mid.trackpool)
            for ev in sorted(mid.trackpool):
                # Look for the first event after the time
                if ev.tick >= ticks:
                    if before:
                        # Return the previous event's tick
                        return previous.tick
                    else:
                        # Return this event's tick
                        return ev.tick
                previous = ev
        return max(mid.trackpool).tick

    def _get_time(ticks, before=False):
        # Find the event time of the first event after the given tick time
        #  or the last event before it
        previous = min(mid.trackpool)
        if ticks is not None:
            for ev in sorted(mid.trackpool):
                # Look for the first event after the time in ticks
                if ev.tick >= ticks:
                    if before:
                        # Return the previous event's time
                        return previous.msdelay
                    else:
                        # Return this event's time
                        return ev.msdelay
                previous = ev
        return max(mid.trackpool).msdelay

    def _parse_time(val, before=False):
        if val.endswith("s"):
            # Value in seconds
            # Convert to ticks
            return _time_to_ticks(float(val[:-1]), before=before)
        else:
            return int(val)

    # Work out start and end points
    if options.start is not None:
        start = _parse_time(options.start, before=False)
    else:
        start = 0

    if options.end is not None:
        end = _parse_time(options.end, before=True)
    else:
        end = None

    if end is not None and start > end:
        print "Start time of %d ticks > end time of %d ticks" % (start, end)
        sys.exit(1)

    # Cut the stream to the desired start and end
    slc = EventStreamSlice(mid, start, end)
    trimmed_mid = slc.to_event_stream(repeat_playing=False)

    # Print out some info
    print "Start tick: %s" % start
    print "End tick: %s" % end
    print
    print "First event tick: %s" % _ticks_to_ticks(start)
    print "Last event tick: %s" % _ticks_to_ticks(end, before=True)
    print
    print "Start time: %ss" % (float(_get_time(start)) / 1000.0)
    print "Last event time: %ss" % (float(_get_time(end, before=True)) / 1000.0)
    print
    print "%d events" % len(trimmed_mid.trackpool)

    # Record playing time
    timer = ExecutionTimer()

    if options.output is None:
        # Play the output by default
        try:
            play_stream(trimmed_mid, block=True)
        except KeyboardInterrupt:
            print "\nPlayed for %.2f seconds" % timer.get_time()
    else:
        # Output to a file
        outfile = os.path.abspath(options.output)
        write_midifile(trimmed_mid, outfile)
        print "Output written to %s" % outfile