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 getSongNumber(message): print(message) msg = cayenne.client.CayenneMessage(message[0], message[1]) if msg.channel == musicChannel: # extract the song number songNo = int(msg.value) 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 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 find_song(name): """ find_song(name) searches in SONGS list for song name and plays its tones with the play_tone function name: name of the song to search for """ global abort_playback abort_playback = False piezo.init() for song in SONGS: song_name = song.split(":")[0] if song_name == name: tune = RTTTL(song) for freq, msec in tune.notes(): play_tone(freq, msec) if abort_playback: return piezo.deinit()
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_rtttl(self, input): tune = RTTTL(input) for freq, msec in tune.notes(): self.tone(freq, msec)
async def play_completely(song): tune = RTTTL(songs.find(song)) for freq, msec in tune.notes(): await play_tone(freq, msec)
async def play_song(song): tune = RTTTL(songs.find(song)) for freq, msec in tune.notes(): await play_tone(freq, msec) if not door_state.is_open: return
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)
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 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: freq = 32767 else: freq=111861/ (divider_high*256+ divider_low)
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(song): tune = RTTTL(song) for freq, duration in tune.notes(): tone(freq, duration)
speaker.duty(512) # 50% duty cycle sleep_ms(int(msec)) # Play for a number of msec speaker.duty(0) # Stop playing sleep_ms(50) # Delay 50 ms between notes song_numbers = os.urandom(100) cnt = 0 print("Push the button to sound the door bell") while True: if btn.value() == PUSHED: song_nr = int(int(song_numbers[cnt])/10.21) +1 songName = songList.get(song_nr) print("Play song ",songName) sleep_ms(20) # debounce switch # play the song tune = RTTTL(songs.find(songName)) for freq, msec in tune.notes(): play_tone(freq, msec) cnt += 1 if cnt > 99: songs = os.urandom(100) cnt = 0 while True: if btn.value() != RELEASED: sleep_ms(20) # debounce switch else: sleep_ms(20) break;
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")