示例#1
0
文件: play.py 项目: maxsun/MusicFinal
def play_word(word, synth, word_duration=0.01):
    # word_duration = 10
    for note in word:
        n = Note(int(note['midi']))
        n.velocity = int(note['vel'])
        fluidsynth.play_Note(n, channel=1)
    time.sleep(word_duration)
示例#2
0
def createChord(freqList = [], volList = []):
	chord = NoteContainer()
	for i in range(0,len(freqList)):
		sel_freq = freqList[i]
		#scale the volumes of present frequencies
		if(sel_freq > 27 and sel_freq < 4186):
			new_Note = Note().from_hertz(sel_freq,440)
			if(sel_freq < 220 or sel_freq > 2500):
			 	if(sel_freq < 100 or sel_freq > 3000):
			 		volList[i] /= 1.4
			 	else:
			 		volList[i] /= 1.2
			new_Note.velocity = volList[i]
			if(len(BAR) > 0):
				#don't play repeat notes as quickly
				if not new_Note in (BAR[-1]):
					chord.add_note(new_Note)
	BAR.append(chord)
示例#3
0
def synthComm():
    # print "I AM IN synthComm"
    timeStart = time.time()
    fluidsynth.init(config.sf2Path)

    note = Note()
    ser = serial.Serial(config.megaPath, config.megaBaud,timeout = 1)
    fluidsynth.stop_Note(note)
    while config.playing:
        info = ser.readline()
        print info
        if info is not '' and len(info) == 9:
            # print info
            # print timeStart
            fluidsynth.stop_Note(note)
            # print "---"
            # print len(info)
            # print "---"

            timeElp, x, y, vel = parseInput(timeStart, info)
            n = pos2Num(x,y)
            # print n
            # print names[n]
            note = Note(names[n],octave)
            note.velocity = vel
            fluidsynth.play_Note(note)

            print "-----"
            print "Time: {0} \nPosition: {1},{2}\n Velocity: {3}".format(timeElp, x, y, vel)
            print "-----"
        else:
            fluidsynth.stop_Note(note)

                # config.userHits = np.hstack((config.userHits, np.array([[time],[vel],[x],[y])))
    # when done, close out connection
    ser.close()
    # print " I HAVE CLOSED THE connection"
    return
    def MIDI_to_Composition(self, file):
        (header, track_data) = self.parse_midi_file(file)
        c = Composition()
        if header[2]['fps']:
            print "Don't know how to parse this yet"
            return c
        ticks_per_beat = header[2]['ticks_per_beat']

        for track in track_data:
            # this loop will gather data for all notes,
            # set up keys and time signatures for all bars
            # and set the tempo and instrument for the track.

            metronome = 1  # Tick once every quarter note
            thirtyseconds = 8  # 8 thirtyseconds in a quarter note
            step = 256.0 # WARNING: Assumes our smallest desired quantization step is a 256th note.

            meter = (4, 4)
            key = 'C'
            bar = 0
            beat = 0
            now = (bar, beat)
            b = None

            started_notes = {}
            finished_notes = {}
            b = Bar(key=key, meter=meter)
            bars = [b]

            bpm = None
            instrument = None
            track_name = None

            for deltatime, event in track:
                if deltatime != 0:
                    duration = (ticks_per_beat * 4.0) / float(deltatime)

                    dur_q = int(round(step/duration))
                    length_q = int(b.length * step)

                    o_bar = bar
                    c_beat = beat + dur_q
                    bar += int(c_beat / length_q)
                    beat = c_beat % length_q

                    while o_bar < bar:
                        o_bar += 1
                        o_key = b.key
                        b = Bar(key=key, meter=meter)
                        b.key = o_key
                        bars.append(b)

                    now = (bar, beat)

                if event['event'] == 8:
                # note off
                    channel = event['channel']
                    note_int = event['param1']
                    velocity = event['param2']
                    note_name = notes.int_to_note(note_int % 12)
                    octave = note_int / 12 - 1

                    note = Note(note_name, octave)
                    note.channel = channel
                    note.velocity = velocity

                    x = (channel, note_int)
                    start_time = started_notes[x]
                    del started_notes[x]
                    end_time = now

                    y = (start_time, end_time)
                    if y not in finished_notes:
                        finished_notes[y] = []

                    finished_notes[y].append(note)

                elif event['event'] == 9:
                # note on
                    channel = event['channel']
                    note_int = event['param1']
                    velocity = event['param2']
                    x = (channel, note_int)

                    # add the note to the current NoteContainer
                    started_notes[x] = now

                elif event['event'] == 10:
                # note aftertouch
                    pass

                elif event['event'] == 11:
                # controller select
                    pass

                elif event['event'] == 12:
                # program change
                # WARNING: only the last change in instrument will get saved.
                    i = MidiInstrument()
                    i.instrument_nr = event['param1']
                    instrument = i

                elif event['event'] == 0x0f:
                # meta event Text
                    if event['meta_event'] == 1:
                        pass

                    elif event['meta_event'] == 3:
                    # Track name
                        track_name = event['data']

                    elif event['meta_event'] == 6:
                    # Marker
                        pass

                    elif event['meta_event'] == 7:
                    # Cue Point
                        pass

                    elif event['meta_event'] == 47:
                    # End of Track
                        pass

                    elif event['meta_event'] == 81:
                    # Set tempo
                    # WARNING: Only the last change in bpm will get saved
                        mpqn = self.bytes_to_int(event['data'])
                        bpm_o = bpm
                        bpm = 60000000 / mpqn

                    elif event['meta_event'] == 88:
                    # Time Signature
                        d = event['data']
                        thirtyseconds = self.bytes_to_int(d[3])
                        metronome = self.bytes_to_int(d[2]) / 24.0
                        denom = 2 ** self.bytes_to_int(d[1])
                        numer = self.bytes_to_int(d[0])
                        meter = (numer, denom)
                        b.set_meter(meter)

                    elif event['meta_event'] == 89:
                    # Key Signature
                        d = event['data']
                        sharps = self.bytes_to_int(d[0])
                        minor = self.bytes_to_int(d[0])
                        if minor:
                            key = 'A'
                        else:
                            key = 'C'
                        for i in xrange(abs(sharps)):
                            if sharps < 0:
                                key = intervals.major_fourth(key)
                            else:
                                key = intervals.major_fifth(key)
                        b.key = Note(key)

                    else:
                        print 'Unsupported META event', event['meta_event']

                else:
                    print 'Unsupported MIDI event', event

            t = Track(instrument)
            t.name = track_name

            sorted_notes = {}

            # sort the notes (so they are added to the bars in order)
            # this loop will also split up notes that span more than one bar.
            for x in finished_notes:
                (start_bar, start_beat), (end_bar, end_beat) = x
                if end_beat == 0:
                    end_bar -= 1
                    end_beat = int(bars[end_bar].length * step)

                while start_bar <= end_bar:
                    nc = NoteContainer(finished_notes[x])
                    b = bars[start_bar]

                    if start_bar < end_bar:
                        # only executes when note spans more than one bar.
                        length_q = int(b.length * step)
                        dur = int(step/(length_q - start_beat))
                    else:
                        # always executes - add the final section of this note.
                        dur = int(step/(end_beat-start_beat))

                    if start_beat != 0:
                        at = float(start_beat)/step
                    else:
                        at = 0.0

                    if start_bar not in sorted_notes:
                        sorted_notes[start_bar] = {}
                    if at not in sorted_notes[start_bar]:
                        sorted_notes[start_bar][at] = (dur, nc)

                    # set our offsets for the next loop
                    start_beat = 0
                    start_bar += 1

            # add all notes to all bars in order.
            for start_bar in sorted(sorted_notes.keys()):
                for at in sorted(sorted_notes[start_bar].keys()):
                    dur, nc = sorted_notes[start_bar][at]
                    bars[start_bar].place_notes_at(nc, dur, at)

            # add the bars to the track, in order
            for b in bars:
                b.fill_with_rests()
                t + b

            # add the track to the composition
            c.tracks.append(t)

        return (c, bpm)
示例#5
0
    return vel_midi   
           
    

# collect the data and plot a moving frame
while run:
    ser.reset_input_buffer()
    data = ser.readline().split(' ')

    # sometimes the incoming data is garbage, so just 'try' to do this
    try:
        #print data
        #print data[3]
        #note = data[3] + "-5"
        note =  Note(data[3] + "-5")
        note_time = int(data[5])
        note.velocity = velocity(note_time)
        if (note_time > 0):
            print note_time, velocity(note_time)
            fluidsynth.play_Note(note)
        
    # if the try statement throws an error, just do nothing
    except: pass
    current_time = time()
    # when time's up, kill the collect+plot loop
    if current_time > end_time: run=False
    
    # update the plot

ser.close()
示例#6
0
    def MIDI_to_Composition(self, file):
        (header, track_data) = self.parse_midi_file(file)
        c = Composition()
        if header[2]['fps']:
            print("Don't know how to parse this yet")
            return c
        ticks_per_beat = header[2]['ticks_per_beat']
        for track in track_data:
            t = Track()
            b = Bar()
            metronome = 1  # Tick once every quarter note
            thirtyseconds = 8  # 8 thirtyseconds in a quarter note
            meter = (4, 4)
            key = 'C'
            for e in track:
                (deltatime, event) = e
                duration = float(deltatime) / (ticks_per_beat * 4.0)
                if duration != 0.0:
                    duration = 1.0 / duration
                if deltatime != 0:
                    if not b.place_notes(NoteContainer(), duration):
                        t + b
                        b = Bar(key, meter)
                        b.place_notes(NoteContainer(), duration)

                if event['event'] == 8:
                    if deltatime == 0:
                        pass
                elif event['event'] == 9:

                # note on

                    n = Note(notes.int_to_note(event['param1'] % 12),
                             event['param1'] / 12 - 1)
                    n.channel = event['channel']
                    n.velocity = event['param2']
                    if len(b.bar) > 0:
                        b.bar[-1][2] + n
                    else:
                        b + n
                elif event['event'] == 10:

                # note aftertouch

                    pass
                elif event['event'] == 11:

                # controller select

                    pass
                elif event['event'] == 12:

                # program change

                    i = MidiInstrument()
                    i.instrument_nr = event['param1']
                    t.instrument = i
                elif event['event'] == 0x0f:

                # meta event Text

                    if event['meta_event'] == 1:
                        pass
                    elif event['meta_event'] == 3:

                    # Track name

                        t.name = event['data']
                    elif event['meta_event'] == 6:

                    # Marker

                        pass
                    elif event['meta_event'] == 7:

                    # Cue Point

                        pass
                    elif event['meta_event'] == 47:

                    # End of Track

                        pass
                    elif event['meta_event'] == 81:

                    # Set tempo warning Only the last change in bpm will get
                    # saved currently

                        mpqn = self.bytes_to_int(event['data'])
                        bpm = 60000000 / mpqn
                    elif event['meta_event'] == 88:

                    # Time Signature

                        d = event['data']
                        thirtyseconds = self.bytes_to_int(d[3])
                        metronome = self.bytes_to_int(d[2]) / 24.0
                        denom = 2 ** self.bytes_to_int(d[1])
                        numer = self.bytes_to_int(d[0])
                        meter = (numer, denom)
                        b.set_meter(meter)
                    elif event['meta_event'] == 89:

                    # Key Signature

                        d = event['data']
                        sharps = self.bytes_to_int(d[0])
                        minor = self.bytes_to_int(d[0])
                        if minor:
                            key = 'A'
                        else:
                            key = 'C'
                        for i in range(abs(sharps)):
                            if sharps < 0:
                                key = intervals.major_fourth(key)
                            else:
                                key = intervals.major_fifth(key)
                        b.key = Note(key)
                    else:
                        print('Unsupported META event', event['meta_event'])
                else:
                    print('Unsupported MIDI event', event)
            t + b
            c.tracks.append(t)
        return (c, bpm)
示例#7
0
''' tester for mingus fluidsynth '''

from mingus.midi import fluidsynth
from mingus.containers import Note
import sys
import time
import random

fluidsynth.init("../HS_Magic_Techno_Drums.SF2")
names = ['A', 'Bb', 'B', 'C', 'Db','D','Eb', 'E', 'F', 'Gb','G','Ab']
# while(True):
# 	n = Note(names[random.randrange(0,11,1)], random.randrange(1,4,1))
# 	n.velocity = random.randrange(40,100,1)
# 	# fluidsynth.set_instrument(1, random.randrange(1,5,1), bank =1)
# 	fluidsynth.play_Note(n)
# 	time.sleep(.1*random.randrange(1,15,1))
# 	# fluidsynth.stop_Note(n)
# 	time.sleep(.5*random.randrange(1,15,1))
# 	# fluidsynth.play_Note(n)

for i in xrange(0,12):
	# for j in xrange(1,4):
	# 	n = Note(names[i],j)
	# 	fluidsynth.play_Note(n)
	# 	time.sleep(2)
	n = Note(names[i], 4)
	n.velocity = 127
	fluidsynth.play_Note(n)
	time.sleep(1)
	def MIDI_to_Composition(self, file):
		header, track_data = self.parse_midi_file(file)

		c = Composition()
		if header[2]["fps"]:
			print "Don't know how to parse this yet"
			return c

		ticks_per_beat = header[2]["ticks_per_beat"]
		for track in track_data:
			t = Track()
			b = Bar()
			metronome = 1 # Tick once every quarter note
			thirtyseconds = 8 # 8 thirtyseconds in a quarter note
			meter = (4,4)
			key = 'C'

			for e in track:

				deltatime, event = e
				duration =  float(deltatime) / (ticks_per_beat * 4.0)
				if duration != 0.0:
					duration = 1.0 / duration

				if deltatime != 0:
					if not b.place_notes(NoteContainer(), duration):
						t + b
						b = Bar(key, meter)
						b.place_notes(NoteContainer(), duration)
						

				# note off
				if event["event"] == 8:
					if deltatime == 0:
						pass

				# note on 
				elif event["event"] == 9:
					n = Note(notes.int_to_note(event["param1"] % 12), 
						event["param1"] / 12 - 1)
					n.channel = event["channel"]
					n.velocity = event["param2"]

					if len(b.bar) > 0:
						b.bar[-1][2] + n
					else:
						b + n

				# note aftertouch
				elif event["event"] == 10:
					pass
				# controller select
				elif event["event"] == 11:
					pass
				# program change
				elif event["event"] == 12:
					i = MidiInstrument()
					i.instrument_nr = event["param1"]
					t.instrument = i

				# meta event
				elif event["event"] == 15:

					# Track name
					if event["meta_event"] == 3:
						t.name = event["data"]
					
					# Marker 
					elif event["meta_event"] == 6:
						pass

					# Cue Point
					elif event["meta_event"] == 7:
						pass

					# End of Track
					elif event["meta_event"] == 47:
						pass

					# Set tempo 
					#warning Only the last change in bpm will get saved currently
					elif event["meta_event"] == 81:
						mpqn = self.bytes_to_int(event["data"])
						bpm = 60000000 / mpqn

					# Time Signature
					elif event["meta_event"] == 88:
						d = event["data"]
						thirtyseconds = self.bytes_to_int(d[3])
						metronome = self.bytes_to_int(d[2]) / 24.0
						denom = 2 ** self.bytes_to_int(d[1])
						numer = self.bytes_to_int(d[0])
						meter = (numer, denom)
						b.set_meter(meter)

					# Key Signature
					elif event["meta_event"] == 89:
						pass

					else:
						print "Unsupported META event", event["meta_event"]

				else:
					print "Unsupported MIDI event", event

			t + b
			c.tracks.append(t)
		
		return c, bpm
示例#9
0
 def to_ming_note(self):
     note = None
     if self.command in (NOTE_OFF, NOTE_ON):
         note = Note(notes.int_to_note(self.data1 % 12), self.data1 / 12 -1)
         note.velocity = self.data2
     return note
示例#10
0
    for case in range(1, 8):
        arr = switch(case)
        note_name = arr[0]
        x_offset = arr[1]
        y_offset = arr[2]
        sum = 0
        for x in range(40):
            for y in range(40):
                sum += M[(x_offset + x) * ratio, (y_offset + y) * ratio]

        if sum < min_volume:
            min_volume = sum
        if sum > max_volume:
            max_volume = sum
        note = Note(note_name)
        note.velocity = sum
        note.channel = 1
        n.add_note(note)
        note.channel = 2
        n_2.add_note(note)

    precision = (max_volume / 1600) / 127
    scale = 1600 * precision

    for x in range(len(n)):
        n[x].velocity = ((n[x].velocity - min_volume) /
                         (max_volume - min_volume)) * 127
        if n[x].velocity < 129 and n[x].velocity > 127:
            n[x].velocity = 127

    ### secondary instrument