async def main(): majorC=RTTTL('10:d=4,o=5,b=180:c,d,e,f,g,a,b,c6') #C major scale anthem=RTTTL('10:d=16,o=5,b=90:2g,e,4c,4e,4g,2c6,8e6,d6,4c6,4e,4f#,2g') #nat'l anthem buzzer.play(majorC) #buzzer.play(anthem)
def play_song(s, duration): """""" note = 0 tune = RTTTL(songs.find(s)) for freq, msec in tune.notes(): if note < duration: play_tone(freq, msec) note += 1
def getData(name): tune = RTTTL(songs.find(name)) n = [] d = [] for freq, msec in tune.notes(): n.append(freq) d.append(msec) data = {} data['freqs'] = n data['durs'] = d with open("/Users/rbn/src/upy-rtttl/sptune.json", "w+") as outfile: json.dump(data, outfile)
def getData(name): tune = RTTTL(songs.find(name)) n=[] d=[] for freq, msec in tune.notes(): n.append(freq) d.append(msec) data = {} data['freqs']=n data['durs']=d with open("/Users/rbn/src/upy-rtttl/sptune.json","w+") as outfile: json.dump(data, outfile)
def getData(unused_addr, args, name): #broadcasts data for ringtone name global playing playing = True tune = RTTTL(songs.find(name)) print("Playing ringtone {}".format(name)) for freq, msec in tune.notes(): #send the data pairs for the notes msg = [] #prepare data message msg.append(freq) msg.append(msec) client.send_message("/ringdata", msg) #broadcast next data pair sleep(msec / 1000.0) #sleep for duration of note #stop current song if playing set to False by received "/abort" message if playing == False: break client.send_message("/finished", True) #broadcasts osc msg when finished
def getData(unused_addr,args,name): #broadcasts data for ringtone name global playing playing=True tune = RTTTL(songs.find(name)) print("Playing ringtone {}".format(name)) for freq, msec in tune.notes(): #send the data pairs for the notes msg=[] #prepare data message msg.append(freq) msg.append(msec) client.send_message("/ringdata",msg) #broadcast next data pair sleep(msec/1000.0) #sleep for duration of note #stop current song if playing set to False by received "/abort" message if playing==False: break client.send_message("/finished",True) #broadcasts osc msg when finished
def getSongNumber(topic, msg): print("Update") print(topic, msg) channelIndex = topic.index( b'cmd') + 4 # search for 'cmd' the channel no follows print("channelIndex: %d" % channelIndex) channel = int(topic[channelIndex:]) # from the channel index to the end print("channel: %d" % channel) valueIndex = msg.index(b'=') + 1 print("valueIndex: %d" % valueIndex) # extract the song number songNo = int(msg[valueIndex:]) print("song number: %d" % songNo) songName = songList.get(songNo) print('Playing the song: %s' % songName) # play the tune tune = RTTTL(songs.find(songName)) for freq, msec in tune.notes(): play_tone(freq, msec)
def parse(melodyOrRTTTL): # If | in melody it is original notes|bpm|transpose format if ('|' in melodyOrRTTTL): defineValue = melodyOrRTTTL.split("|") transposeBySemitones = int( defineValue[2]) if len(defineValue) > 2 else 0 return parseMelody(defineValue[0].strip(), int(defineValue[1]), transposeBySemitones) # Else assume RTTL else: from rtttl import RTTTL retVal = "" tune = RTTTL(melodyOrRTTTL) for freq, msec in tune.notes(): retVal += f"{{{freq:.0f},{msec:.0f}}}," if retVal != "": retVal = "{" + retVal[:-1] + "}" else: raise ValueError("Blank RTTTL melody detected") return retVal
def play_song(self, search): """ play a song stored in songs.py :param search: string; song name listed in songs.py :return: None """ while self.is_playing: self.mute = True else: self.mute = False # play song in a new thread (non-blocking) # _thread.stack_size(16 * 1024) # set stack size to avoid runtime error # play_tone = _thread.start_new_thread(self.play, (RTTTL(songs.find(search)),)) self.play(RTTTL(songs.find(search))) self.song = None
def play_song(search): play(RTTTL(songs.find(search)))
def playsound(frequency,duration): pass #apt-get install beep # os.system('beep -f %s -l %s' % (frequency,duration)) else: def playsound(frequency,duration): winsound.Beep(frequency,duration) while (1): song = raw_input("Paste RTL Tune: ") if (song == ""): exit() tune = RTTTL(song) print "; start song: "+song.split(':')[0] for tcnt, divider_low, divider_high in tune.notes(): while (tcnt > 255): print "db "+str(255)+","+str(divider_low)+","+str(divider_high)+" ; extended" tcnt = tcnt-255 print "db "+str(tcnt)+","+str(divider_low)+","+str(divider_high)+" ; ", if (divider_high==0 and divider_low==0): print " pause" else: print divider = (divider_high*256+ divider_low) if divider==0:
def on_message(client, userdata, msg): """Handle incoming messages.""" # print("Topic:", msg.topic + ' : Message: ' + msg.payload) print(str(msg.topic), str(msg.payload)) if str(msg.topic) == "orchestra/cue": """Handle RTTTL song cue command.""" lcd.set_cursor_position(0, 0) lcd.write("Now playing:".ljust(16)) """Handle incoming playback cue.""" notedict = { "C": 36, "C#": 37, "D": 38, "D#": 39, "E": 40, "F": 41, "F#": 42, "G": 43, "G#": 44, "A": 45, "A#": 46, "B": 47 } channeldict = { "C": 0, "C#": 0, "D": 1, "D#": 1, "E": 2, "F": 3, "F#": 3, "G": 4, "G#": 4, "A": 5, "A#": 5, "B": 6 } tune = RTTTL(msg.payload) # tune is now an object storing a sequence of note frequencies and durations. # Iterate through that and handle each note to play back the song: for freq, msec in tune.notes(): # print(freq, msec) if freq != 0.0: note, oct = freq_to_note( freq ) # Get note name and octave number from the frequency. print(note, oct) play_beats = list( "00000000") # fresh playlist. List so mutable. # Set the glockenspiel channel from the note name. Wrap around octaves since we only have 1 physically. play_beats[channeldict[note]] = "1" playset( ''.join(play_beats)) # Command the glockenspiel over MQTT handle_note( notedict[note], oct) # Synthesise note via pygame for direct playback sleep(msec / 1000.0) # Pause for the note duration. else: print('Rest!') sleep( msec / 1000.0 ) # Pause for the rest duration (note frequency is zero). # Make sure the last note plays sleep(0.3) print(">>> Playback complete!") lcd.clear() lcd.set_cursor_position(0, 0) lcd.write("POISED READY") elif str(msg.topic) == "orchestra/song": print("Song title received") # Display song title on the HAT lcd.set_cursor_position(0, 1) lcd.write(str(msg.payload[:16]).ljust(16)) elif str(msg.topic) == "orchestra/handle": lcd.set_cursor_position(0, 2) # Display song requester lcd.write("For: " + str(msg.payload[:11]).ljust(11)) else: print("Well, that didn't work")
def play_cue(cue): """Playback time!""" lcd.set_cursor_position(0, 0) lcd.write("Now playing:".ljust(16)) """Handle incoming playback cue.""" notedict = { "C": 36, "C#": 37, "D": 38, "D#": 39, "E": 40, "F": 41, "F#": 42, "G": 43, "G#": 44, "A": 45, "A#": 46, "B": 47 } channeldict = { "C": 0, "C#": 0, "D": 1, "D#": 1, "E": 2, "F": 3, "F#": 3, "G": 4, "G#": 4, "A": 5, "A#": 5, "B": 6 } tune = RTTTL(cue) # tune is now an object storing a sequence of note frequencies and durations. # Iterate through that and handle each note to play back the song: # First extract the bpm and send that data over the network. message("bpm", tune.bpm) sleep( 0.2 ) # Give the orchestra controller chance to think about that and stop what it's doing # Send the lead-in command message("status", "lead-in") # Play the lead-in. Assume we're in 4/4, because all music is, right? # First calculate the bpm we're actually going to use. divider = ceil(tune.bpm / maxbpm) playbpm = float(tune.bpm) / divider playdelay = 60.0 / playbpm for _ in range(4): myservo[7].mid() sleep(playdelay / 4) myservo[7].min() sleep(playdelay * 3 / 4) # ...and away we go! for freq, msec in tune.notes(): # print(freq, msec) if freq != 0.0: note, oct = freq_to_note( freq) # Get note name and octave number from the frequency. print(note, oct) # Command the appropriate servo to move myservo[channeldict[note]].mid() # Direct audio synthesis, for testing. handle_note(notedict[note], oct) # Synthesise note via pygame for direct playback # Below commented out from MQTT-passing version of this (now integrated) # play_beats = list("00000000") # fresh playlist. List so mutable. # # Set the glockenspiel channel from the note name. Wrap around octaves since we only have 1 physically. # play_beats[channeldict[note]] = "1" # playset(''.join(play_beats)) # Command the glockenspiel over MQTT sleep(0.1) # Pause for 100msec so the servo can move myservo[channeldict[note]].min() # Return servo to rest sleep((msec / 1000.0) - 0.1) # Pause for the note duration, minus the default pause else: print('Rest!') sleep(msec / 1000.0 ) # Pause for the rest duration (note frequency is zero). # Make sure the last note plays sleep(0.3) print(">>> Playback complete!") # Message the system to assert end of playback message("status", "finished") # reset the Display-o-Tron HAT lcd.clear() lcd.set_cursor_position(0, 0) lcd.write("POISED READY")
def play_melody(song='closed'): print("Play melody: ", song) tune = RTTTL(songs.find(song)) for freq, msec in tune.notes(): play_tone(freq, msec) tone.deinit()
def play_rtttl(self, input): tune = RTTTL(input) for freq, msec in tune.notes(): self.tone(freq, msec)
await uasyncio.sleep_ms(int(msec * 0.1)) async def play(tune, buz_ch): try: for freq, msec in tune.notes(): await play_tone(freq, msec, buz_ch) except KeyboardInterrupt: await play_tone(0, 0, buz_ch) async def killer(): print("sleeping {} seconds".format(20)) await uasyncio.sleep(20) loop = uasyncio.get_event_loop() loop.create_task(file_to_led()) loop.create_task(temp()) from rtttl import RTTTL import songs loop.create_task(play(RTTTL(songs.find('MissionImp')), buz_ch1)) try: loop.run_until_complete(killer()) finally: buz_ch1.deinit() display.fill(0) display.show()
def play(song): tune = RTTTL(song) for freq, duration in tune.notes(): tone(freq, duration)
# Raspberry Pi Pico RTTTL example # scruss - 2021-02: sorry, not sorry ... from rtttl import RTTTL from time import sleep_ms from machine import Pin, PWM # nicked from https://gist.github.com/mhungerford/0af269ee46c0d44a813c NvrGonna = 'NvrGonna:d=4,o=5,b=200:8g,8a,8c6,8a,e6,8p,e6,8p,d6.,p,8p,8g,8a,8c6,8a,d6,8p,d6,8p,c6,8b,a.,8g,8a,8c6,8a,2c6,d6,b,a,g.,8p,g,2d6,2c6.,p,8g,8a,8c6,8a,e6,8p,e6,8p,d6.,p,8p,8g,8a,8c6,8a,2g6,b,c6.,8b,a,8g,8a,8c6,8a,2c6,d6,b,a,g.,8p,g,2d6,2c6.' # pin 26 - GP20; just the right distance from GND at pin 23 # to use one of those PC beepers with the 4-pin headers pwm = PWM(Pin(20)) def play_tone(freq, msec): # print('freq = {:6.1f} msec = {:6.1f}'.format(freq, msec)) if freq > 0: pwm.freq(int(freq)) # Set frequency pwm.duty_u16(32767) # 50% duty cycle sleep_ms(int(0.9 * msec)) # Play for a number of msec pwm.duty_u16(0) # Stop playing for gap between notes sleep_ms(int(0.1 * msec)) # Pause for a number of msec tune = RTTTL(NvrGonna) for freq, msec in tune.notes(): play_tone(freq, msec)
buzzer = PWM(Pin(15)) buzzer.duty(0) def play_tone(freq, msec): if freq > 0: buzzer.freq(freq) # Set frequency buzzer.duty(10) # 50% duty cycle time.sleep(msec * 0.001) # Play for a number of msec buzzer.duty(0) # Stop playing time.sleep(0.05) tune = RTTTL( "Moonheart:d=4,o=5,b=140:c.,8e,g.,8c,b.4,8e,g.,8g,a.,8b,c.6,8a,2g,8e,8d,c.,8c,8c,8p,8e,8d,c.,8c,8c,8p,8d,8e,d.,8a4,b.4,16c,16d,2c" ) tune = RTTTL( "mario:d=4,o=5,b=100:16e6,16e6,32p,8e6,16c6,8e6,8g6,8p,8g,8p,8c6,16p,8g,16p,8e,16p,8a,8b,16a#,8a,16g.,16e6,16g6,8a6,16f6,8g6,8e6,16c6,16d6,8b,16p,8c6,16p,8g,16p,8e,16p,8a,8b,16a#,8a,16g.,16e6,16g6,8a6,16f6,8g6,8e6,16c6,16d6,8b,8p,16g6,16f#6,16f6,16d#6,16p,16e6,16p,16g#,16a,16c6,16p,16a,16c6,16d6,8p,16g6,16f#6,16f6,16d#6,16p,16e6,16p,16c7,16p,16c7,16c7,p,16g6,16f#6,16f6,16d#6,16p,16e6,16p,16g#,16a,16c6,16p,16a,16c6,16d6,8p,16d#6,8p,16d6,8p,16c6" ) # for freq, msec in tune.notes(): # play_tone(freq, msec) # Connect to Wi-Fi if not connected sta_if = network.WLAN(network.STA_IF) sta_if.active(True) sta_if.connect("Wifi 基地台", "Wifi 密碼") # Wait for connecting to Wi-Fi while not sta_if.isconnected(): pass
def fast_vline(x, y, height, color): lcd.fill(x, y, 1, height, color) graphics = gfx.GFX(lcdWidth, lcdHeight, lcd.pixel, hline=fast_hline, vline=fast_vline) lcd.fill(0, 0, lcdWidth, lcdHeight, bgColor) graphics.rect(8, 8, lcdWidth - 16, lcdHeight - 16, textColor) lcd.text("Hello STEMBot 2!", 100, 100, textColor) time.sleep_ms(250) #intro screen delay tune = RTTTL('14:d=4,o=4,b=240:c,e,g,e,f,e,d,e,c') #buzzer.play(tune) pinUp = Pin('E5', Pin.IN, Pin.PULL_UP) pinDown = Pin('B6', Pin.IN, Pin.PULL_UP) pinSel = Pin('B2', Pin.IN, Pin.PULL_UP) #middle button below LCD l = os.listdir('apps') valid = [] for file in l: if (file.endswith('.py') and (file[0] != '.' and file != '_')): #Remove duplicates newfile = file.replace('_', ' ') valid.append(newfile[:-3]) #add file to valid list, remove extension
from rtttl import RTTTL import songs import board import pulseio import time speaker_pin = board.D0 # Speaker is connected to this DIGITAL pin # Initialize input/output pins pwm = pulseio.PWMOut(speaker_pin, variable_frequency=True, duty_cycle=0) def play_tone(freq, msec): # print('freq = {:6.1f} msec = {:6.1f}'.format(freq, msec)) if freq > 0: pwm.frequency = int(freq) # Set frequency pwm.duty_cycle = 32767 # 50% duty cycle time.sleep(msec*0.001) # Play for a number of msec pwm.duty_cycle = 0 # Stop playing time.sleep(0.05) # Delay 50 ms between notes tune = RTTTL(songs.find('Entertainer')) for freq, msec in tune.notes(): play_tone(freq, msec)
import ESP8266WebServer import network, time from machine import Pin, PWM from umqtt.robust import MQTTClient from rtttl import RTTTL # buzzer D8 buzzer = PWM(Pin(15)) buzzer.duty(0) tune = RTTTL( "mario:d=4,o=4,b=100:16e5,16e5,32p,8e5,16c5,8e5,8g5,8p,8g,8p,8c5,16p,8g,16p,8e,16p,8a,8b,16a#,8a,16g.,16e5,16g5,8a5,16f5,8g5,8e5,16c5,16d5,8b,16p,8c5" ) def play_tone(freq, msec): if freq > 0: buzzer.freq(freq) # Set frequency buzzer.duty(10) # 50% duty cycle time.sleep(msec * 0.001) # Play for a number of msec buzzer.duty(0) # Stop playing time.sleep(0.05) # Connect to Wi-Fi if not connected sta_if = network.WLAN(network.STA_IF) sta_if.active(True) sta_if.connect("Wifi 基地台", "Wifi 密碼") # Wait for connecting to Wi-Fi while not sta_if.isconnected(): pass
def play_tone(freq, msec): print('freq = {:6.1f} msec = {:6.1f}'.format(freq, msec)) if freq > 0: buz_tim.freq(freq) buz_ch.pulse_width_percent(pwm) pyb.delay(int(msec * 0.9)) buz_ch.pulse_width_percent(0) pyb.delay(int(msec * 0.1)) def play(tune): try: for freq, msec in tune.notes(): play_tone(freq, msec) except KeyboardInterrupt: play_tone(0, 0) def play_song(search): play(RTTTL(songs.find(search))) # play songs from songs.py play_song('Entertainer') # play songs directly play( RTTTL( 'Monty Python:d=8,o=5,b=180:d#6,d6,4c6,b,4a#,a,4g#,g,f,g,g#,4g,f,2a#,p,a#,g,p,g,g,f#,g,d#6,p,a#,a#,p,g,g#,p,g#,g#,p,a#,2c6,p,g#,f,p,f,f,e,f,d6,p,c6,c6,p,g#,g,p,g,g,p,g#,2a#,p,a#,g,p,g,g,f#,g,g6,p,d#6,d#6,p,a#,a,p,f6,f6,p,f6,2f6,p,d#6,4d6,f6,f6,e6,f6,4c6,f6,f6,e6,f6,a#,p,a,a#,p,a,2a#' ))
import numpy as numpy import matplotlib.pyplot as plt from bigrtttl import * from rtttl import RTTTL data = [] for key, value in songdictEgg.items(): song = RTTTL(value) # print(key, song.bpm) # Used for debugging malformed RTTTL lines if song.bpm > 500: print(key, song.bpm) else: data.append(song.bpm) plt.hist(data, bins=50) plt.show()
from rtttl import RTTTL import songs import board import pulseio import time speaker_pin = board.D0 # Speaker is connected to this DIGITAL pin # Initialize input/output pins pwm = pulseio.PWMOut(speaker_pin, variable_frequency=True, duty_cycle=0) def play_tone(freq, msec): # print('freq = {:6.1f} msec = {:6.1f}'.format(freq, msec)) if freq > 0: pwm.frequency = int(freq) # Set frequency pwm.duty_cycle = 32767 # 50% duty cycle time.sleep(msec * 0.001) # Play for a number of msec pwm.duty_cycle = 0 # Stop playing time.sleep(0.05) # Delay 50 ms between notes tune = RTTTL(songs.find('Super Mario - Main Theme')) for freq, msec in tune.notes(): play_tone(freq, msec)