Пример #1
0
def main():
    global filelist
    noIntro = False
    while True:
        if len(filelist) == 0:
            ui.throw('没有提供任何文件!', True)
        if filelist[0] == '-s':
            noIntro = True
            del filelist[0]
        elif filelist[0] == '-c':
            del filelist[0]
            if len(filelist) == 0:
                ui.throw('错误的参数:-c。', True)
            ui.g.cText = filelist[0]
            del filelist[0]
        elif filelist[0] == '--help':
            ui.showCmdHelp()
            exit()
        else:
            break
    if not noIntro:
        ui.showIntro()
    while True:
        for f in filelist:
            player.play(f)
        ui.showRoll()
Пример #2
0
def get_mood(scene, mood):
    player.play(CONFIG[scene]['moods'][mood]['music'])
    toadd = [SCENE_PAGE_HEADER.format(scene)]
    for title in CONFIG[scene]['moods']:
        toadd.append(SCENE_PAGE_ELEMENT.format(title, scene))
    toadd.append(SCENE_PAGE_FOOTER)
    return ''.join(toadd)
Пример #3
0
 def PlaySong(self, event):
   if self.Songs != None:
     Player = self.ASH_Frame.Tools.Player
     if Player != None:
       Player.Stop()
       Player = None
     
     SongIndex = self.SongList.GetSelections()[0]
     SongName = self.Songs.keys()[SongIndex]
     SongPath = self.Songs[SongName]
     ServerUrl = self.ASH_Frame.Search.LastSearchServer + "songs/"
     RequestUrl = ServerUrl+SongPath
     SongFile = open("saves/.temp.wav", "wb")
     
     import urllib
     Song = urllib.urlopen(ServerUrl+SongPath)
     SongFile.writelines(Song.read())
     SongFile.close()
     
     import player
     player.play(self.ASH_Frame)
     self.ASH_Frame.Tune.TkRoot = Tkinter.Tk()
     tkSnack.initializeSnack(self.ASH_Frame.Tune.TkRoot)
     self.ASH_Frame.Tune.SnackSound.write(".tempfile.wav")
     self.ASH_Frame.Tune.SnackSound = tkSnack.Sound(load=".tempfile.wav")
Пример #4
0
def get_mood(scene, mood):
    player.play(CONFIG[scene]['moods'][mood]['music'])
    toadd = [SCENE_PAGE_HEADER.format(scene)]
    for title in CONFIG[scene]['moods']:
        toadd.append(SCENE_PAGE_ELEMENT.format(title, scene))
    toadd.append(SCENE_PAGE_FOOTER)
    return ''.join(toadd)
Пример #5
0
def sync_play_time(self, pitch_timestamp, old_time):
    # sleep
    deta_time = time.time() - old_time
    deta_timestamp = pitch_timestamp - self.last_timestamp
    wait_time = int(deta_timestamp * parse_midi.g_mseconds_per_quarter / parse_midi.g_ticks_per_quarter )
    # print "---- midi need wait:", wait_time

    ## show before play
    deta_time = time.time() - old_time
    if wait_time - deta_time*1000 > 10:
        self.gl_screen_blit()
        pygame.display.flip()
    deta_time = time.time() - old_time
    # print "after pygame:", int(deta_time*1000)

    for cmd, pitch, volecity in self.play_commands:
        if cmd == "NOTE_ON":
            player.play(pitch, volecity, self.sounds)
        elif cmd == "NOTE_OFF":
            player.stop(pitch, volecity, self.sounds)
        elif cmd == "METRO_ON" and player.g_metronome_volume > 0:
            player.play(pitch, volecity, self.sounds)
    deta_time = time.time() - old_time
    # print "after play:", int(deta_time*1000)

    player.real_stop(self.sounds, wait_time/1000.0 - deta_time - 0.03)
    deta_time = time.time() - old_time
    # print "after stop:", int(deta_time*1000)

    if wait_time/1000.0 - deta_time > 0:
        time.sleep((wait_time/1000.0 - deta_time))
Пример #6
0
def main():
    global filelist
    noIntro = False
    while True:
        if len(filelist) == 0:
            ui.throw('没有提供任何文件!', True)
        if filelist[0] == '-s':
            noIntro = True
            del filelist[0]
        elif filelist[0] == '-c':
            del filelist[0]
            if len(filelist) == 0:
                ui.throw('错误的参数:-c。', True)
            ui.g.cText = filelist[0]
            del filelist[0]
        elif filelist[0] == '--osd':
            ui.g.enable_osd = True
            del filelist[0]
        elif filelist[0] == '--help':
            ui.showCmdHelp()
            exit()
        else:
            break
    if not noIntro:
        ui.showIntro()
    while True:
        ui.g.step = 0
        for f in filelist:
            player.play(f)
        ui.g.step = 1
        ui.showRoll()
Пример #7
0
    def on_partial_transcription(self, text):
        self.listening = False
        led.on()
        try:
            if text.find('开灯') >= 0:
                lamp.turn_on()
            elif text.find('关灯') >= 0:
                lamp.turn_off()
            elif text.find('几点了') >= 0 or text.find('现在几点') >= 0:
                now = datetime.datetime.now()
                player.play(
                    self.synthesize('现在是{}点{}分'.format(now.hour, now.minute)))
            elif text.find('今天星期几') >= 0 or text.find('今天几号') >= 0:
                now = datetime.datetime.now()
                player.play(
                    self.synthesize('今天是{}月{}号,星期{}'.format(
                        now.month, now.day, weekday[now.weekday()])))
            elif text.find('小呆') >= 0:
                alexa.listen()
                time.sleep(3)
            #else:
            #    player.play(self.synthesize(text))
            #    time.sleep(1)
        except Exception as e:
            print(e)

        led.off()
        self.listening = True

        print('on_partial_transcription: {}'.format(text))
Пример #8
0
def main():
	args = parse_args()

	print('This is srpi v{0}'.format(config.VERSION))

	live_audio_url = channels.get_live_audio_url(132)

	player.play(live_audio_url)
Пример #9
0
def test2():
    a = seq.build(seq.track1, player.bitRate)

    screen.init()
    screen.draw(a, player.bitRate / seq.track1[0]["frequency"])

    b = gen.sin(440, player.bitRate, 10, 0)
    player.play(a)
    player.play(b)
def second_phase(model, player, games, phases, train_args):
    for i in range(phases):
        print('Starting phase ', i, 'of ', phases)
        for game in games:
            game.open_zero()
            player.play(game)
        model.fit(games, **train_args)
        for game in games:
            game.reset()
Пример #11
0
def api_play(request, n):
    """Handle API request to Play Song n-> [int|"all"|"shuffle"]."""
    if n not in player.get_collection() and n not in ["all", "shuffle"]:
        request.api_error(json.dumps(dict(error=True)))
        return

    request.send_response(202, 'API', "Requesting playing %r" % n)
    request.send_header('Content-Type', 'application/json')
    request.end_headers()

    request.wfile.write(json.dumps(dict(playing=True)))
    player.play(n)
Пример #12
0
 def onDetection(self, data, start, end):
     name = "{0}-{1}".format(start, end) + '.wav'
     print(name)
     filename = self.savefile(data, start, end)
     print('current mode', self.MODE)
     if self.MODE == 'RANDOM':
         randomfile = player.getRandomFile(play_folder)
         player.play(randomfile)
     if self.MODE == 'ECHO':
         player.play(filename)
     self.display.display_image()
     print("finished playing")
Пример #13
0
def start_play():
    """
    function to read the listbox selection
    and put the result in a label widget
    """
    # get selected line index
    index = listbox.curselection()[0]
    print(index)
    player.play(jinglelink[index])
    #t = Thread(target=player.play(jinglelink[index]), args=(True,))
    #t.start()
    # get the line's text
    seltext = listbox.get(index)
    # put the selected text in the label
    label['text'] = seltext
Пример #14
0
Файл: web.py Проект: lorc/belyn
def player_view(request):
    if request.method == "POST":
        if request.POST.get("file"):
            fname = request.POST["file"]
            if not os.path.exists(fname):
                pass
                #request.session.flash(u"Файл '%s' не найден :("%fname)
            else:
                player.play(fname)
                return {"file":os.path.basename(fname),
                        "pos":player.get_pos(),
                        "media":media.get()}
        else:
            request.session.flash(u"А что играть то?")
    return {"media": media.get()}
Пример #15
0
def pressed(channel):
    global start
    global time0
    if start:
        time0 = time.time()
        GPIO.output(lightList, 1)
    else:
        GPIO.output(lightList, 0)
        response_time = 1000 * (time.time() - time0)
        print("Your time is {} ms".format(int(response_time)))
        turn_on_n_leds(map_ms_to_n(response_time))
        if response_time < 150:
            player.play(buzzer, [("C", 0.5), ("C", 0.5), ("G", 2)])
        else:
            player.play(buzzer, [("G", 0.5), ("F", 0.5), ("E", 0.5), ("C", 2)])

    start = not start
Пример #16
0
    def play(self, index: QtCore.QModelIndex = None):
        if not index:
            return print('No item selected')

        track = player.play(index.row(), self.tableModel.tracks[index.row()])
        if track:
            self.selectCurrentTrack()
            self.updatePlayStatus()
            self.lyricsTxt.setText(self.lyrics.find())
Пример #17
0
def main():
    import argparse

    CLI_DESC = "It is a simple python package to play videos in the terminal using colored characters as pixels or other usefull outputs"
    EPILOG = ("\033[1;37mThanks for trying video-to-ascii!\033[0m")

    PARSER = argparse.ArgumentParser(prog='video-to-ascii',
                                     description=CLI_DESC,
                                     epilog=EPILOG)
    PARSER.add_argument('-f',
                        '--file',
                        type=str,
                        dest='file',
                        help='input video file',
                        action='store',
                        required=True)
    PARSER.add_argument(
        '--strategy',
        default='ascii-color',
        type=str,
        dest='strategy',
        choices=["ascii-color", "just-ascii", "filled-ascii", "reverse-ascii"],
        help='choose an strategy to render the output',
        action='store')
    PARSER.add_argument('-o',
                        '--output',
                        type=str,
                        dest='output',
                        help='output file to export',
                        action='store')
    PARSER.add_argument('-a',
                        '--with-audio',
                        dest='with_audio',
                        help='play audio track',
                        action='store_true')

    ARGS = PARSER.parse_args()

    player.play(ARGS.file,
                strategy=ARGS.strategy,
                output=ARGS.output,
                play_audio=ARGS.with_audio)
Пример #18
0
def button1Pressed(channel1):
    song_A= [('C', 0.5), ('C', 0.5), ('G', 0.5), ('G', 0.5),
            ('A', 0.5), ('A', 0.5), ('G', 1),
            ('F', 0.5), ('F', 0.5), ('E', 0.5), ('E', 0.5),
            ('D', 0.5), ('D', 0.5), ('C', 1),
            ('G', 0.5), ('G', 0.5), ('F', 0.5), ('F', 0.5),
            ('E', 0.5), ('E', 0.5), ('D', 1),
            ('G', 0.5), ('G', 0.5), ('F', 0.5), ('F', 0.5),
            ('E', 0.5), ('E', 0.5), ('D', 1),
            ('C', 0.5), ('C', 0.5), ('G', 0.5), ('G', 0.5),
            ('A', 0.5), ('A', 0.5), ('G', 1),
            ('F', 0.5), ('F', 0.5), ('E', 0.5), ('E', 0.5),
            ('D', 0.5), ('D', 0.5), ('C', 1)]
    
    song_B=[('C', 0.5), ('C', 0.5), ('D', 0.5), ('E', 0.5), ('C', 0.5), ('E', 0.5), ('D', 0.5),
            ('C', 0.5), ('C', 0.5), ('D', 0.5), ('E', 0.5), ('C',1), ('B2',1)]

    allSongs=[song_A,song_B]
    
    print("button pressed", selectedSong)
    GPIO.output(lightList[0], 1)
    player.play(buzzer, allSongs[selectedSong], tempo=120)
Пример #19
0
def natural_selection(population, path, env, generations, games, ram_obs, mutate_man, mutate_prob, crossover_prob):
    # GENERATE INITIAL POPULATION (ADD SOME VARIATIONS)
    models = []
    for _ in range(population):
        model = nn.NeuralNetwork()
        model.load(path)
        model.genetic_weights_admixture(GeneticAdmixture.MUTATION, mutate_prob, magnitude = mutate_man)
        models.append(model)
    # FOR EACH GENERATION
    for generation in range(generations):
        # PLAY
        best_score = 0
        models_scores_mean = []
        for model in range(population):
            models_scores_mean.append(player.play(models[model], env, games, ram_obs, False, False, True))
            print(f"* Generation: {generation}, Model: {model}, Score: {models_scores_mean[-1]}")
        best_score = max(models_scores_mean)
        # NEW POPULATION
        new_models = []
        # SELECT THE 2 BEST
        for _ in range(2):
            best = np.argmax(models_scores_mean)
            models_scores_mean[best] = 0
            new_models.append(models[best])
        # CROSSOVER BETWEEN THE 2 BEST FOR THE FOLLOWING 2
        for two_next in range(2):
            other = np.argmax(models_scores_mean)
            models_scores_mean[other] = 0
            model = models[other]
            model.copy_dna_weights(new_models[two_next].model)
            model.genetic_weights_admixture(GeneticAdmixture.CROSSOVER, crossover_prob, model = new_models[1 if two_next == 0 else 0].model)
            new_models.append(model)
        # REPRODUCE BEST
        for _ in range(2):
            new_models.append(new_models[0])
        # SAVE BEST MODEL
        new_path = path+"_"+"darwin"+"_"+str(generation)+"_"+str(best_score)
        print(f"--> Save model: {new_path}")
        new_models[0].save(new_path)
        # MUTATE POPULATION
        for candidate in range(2,len(new_models)):
            new_models[candidate].genetic_weights_admixture(GeneticAdmixture.MUTATION, mutate_prob, magnitude=mutate_man)
        # SAVE NEW POPULATION
        models = new_models
Пример #20
0
def make_a_move(player, game_history):
    have_played = False
    # last_play = -1 if (len(game_history) == 0) else game_history[-1]

    while (have_played == False):
        if (IN_REPLAY_MODE):
            col = replay_list.pop(0)
        else:
            col = player.play()

        have_played = b.move_piece(player.piece, col)

    player.last_move = col
    # print(player.name, player.last_move)
    game_history.append(col)

    eog = b.check_eog(col)
    if (TOUR_BY_TOUR):
        clear()
        b.print_board()
        input()
    return eog
Пример #21
0
def _alarm(stop_event):
    import manager
    from mydatetime import getNow
    import player
    import time
    prev = getNow()
    minGap = datetime.timedelta(0, 300)  # 超过300秒,认为是睡眠/待机唤醒
    count = 0
    alarm = False  # “闹铃”提醒状态
    while 1:
        if stop_event.is_set():
            break
        cur = getNow()
        if (cur - prev >= minGap):
            manager.refreshWeekly()
            manager.resortAndSave()
            refresh()
        prev = cur
        reminds = manager.getReminds()  # 获取需要闹铃提醒的闹钟
        length = len(reminds)
        player.play(reminds[0]['sound'] if length else None)
        if not alarm and length:
            alarm = True
            _taskbarThread.start()
            _screenThread.start()
            on()
            count = 0
        if alarm and not len(reminds):
            alarm = False
            player.play(None)
            _taskbarThread.stop()
            _screenThread.stop()
            off()
        if alarm and count > 10 * alarmLast:
            alarm = False
            player.play(None)
            _taskbarThread.stop()
            _screenThread.stop()
            manager.later(getNow() + alarmInterval)  # 推迟提醒
            off()
        count += 1
        time.sleep(0.1)
    return
Пример #22
0
def ws_play(connection, n):
    """Handle WS request to Play Song n-> [int|"all"|"shuffle"]."""
    # connection.sendMessage(json.dumps(dict(playing=True)))
    player.play(n)
Пример #23
0
import time
import sys
import config
import player
import wx
app = wx.App(redirect=False)
from gui import interface
config.setup()
interface.window.Show()

if config.appconfig['general']['resumelastsong'] == True and config.appconfig[
        'general']['lastsong'] != "":
    try:
        player.open_file(config.appconfig['general']['lastsong'])
        player.p.stream.set_position(
            int(config.appconfig['general']['lastsongposition']))
        player.play()
    except:
        config.appconfig['general']['lastsong'] = ""
        config.appconfig['general']['lastsongposition'] = 0

app.MainLoop()
Пример #24
0
    try:
        # Read rfid code or manual input
        if (keyboard_input_handler.can_read()):
            code = keyboard_input_handler.read()
            print("Scanned code: " + code)
            logger.info("Scanned code: " + code)
        
        print("last code:" + shared.last_code)

        if (code == shared.last_code):
            continue

        interpreted = interpreter.interpret(code)
        
        if (interpreted.action == interpreter.Action.play):
            player.play(interpreted.arg)
        if (interpreted.action == interpreter.Action.play_mpd):
            card = interpreted.arg
            print(card)
            player.play_mpd(card["uri"], card["index"], card["kind"] == "playlist")
        elif (interpreted.action == interpreter.Action.text2speech):
            card = interpreted.arg
            print("Speek to file:")
            print(card)
            speek.to_file(card["desc"])
            player.play_mpd(card["uri"])
        elif (interpreted.action == interpreter.Action.terminate):
            break
    except Exception as error:
            logger.exception("Unexpected error occured")
            code = ""
Пример #25
0
            doRefresh = selectChannel(weight)
    except:
        doRefresh = False

if mode == _PLAY:
    doRefresh = False
    try:
        stream = urllib.unquote_plus(params['stream'])

        #ottAddon = xbmcaddon.Addon(id = 'script.tvguidedixie')
        #path     = ottAddon.getAddonInfo('path')

        #sys.path.insert(0, path)

        import player
        player.play(stream, False)
    except Exception, e:
        pass

if mode == _CANCELSELECT:
    doRefresh = cancelSelection()

if mode == _INSERTABOVE:
    try:
        weight = int(params['weight'])
        doRefresh = insertSelection(above=True, theWeight=weight)
    except:
        pass

if mode == _INSERTBELOW:
    try:
Пример #26
0
 def playfile1(self):
     player.play(self.filepath1)
Пример #27
0
            doRefresh = selectChannel(weight)                    
    except:
        doRefresh = False

if mode == _PLAY:
    doRefresh = False
    try:
        stream   = urllib.unquote_plus(params['stream'])

        #tvpAddon = xbmcaddon.Addon(id = 'script.tvportal')
        #path     = tvpAddon.getAddonInfo('path')

        #sys.path.insert(0, path)

        import player
        player.play(stream, False)
    except Exception, e:
        pass

if mode == _CANCELSELECT:
    doRefresh = cancelSelection()


if mode == _INSERTABOVE:
    try:
        weight = int(params['weight'])
        doRefresh = insertSelection(above=True, theWeight=weight)
    except:
        pass

Пример #28
0
 def play(self):
     """
     Play the item.
     """
     videoplayer.play(self)
Пример #29
0
for j in tqdm(range(ROUND_NO)):
    players=[]
    winner=set()
    loser=set()
    
    for i in range(PLAYER_NO):
        players.append(player.player(i))
        
    #while not len(winner)+len(loser)>=PLAYER_NO-1:
    while not len(players)<=1:
        a,b=random.sample(players,2)
        players.remove(a)
        players.remove(b)
        if a.isAvailable() and b.isAvailable():
            player.play(a,b)
        if a.isWin():
            winner.add(a.getNo())
            all_player.add(a)
        elif a.isDead():
            loser.add(a.getNo())
            all_player.add(a)
        else:
            pass
            players.append(a)
        if b.isWin():
            winner.add(b.getNo())
            all_player.add(b)
        elif b.isDead():
            loser.add(b.getNo())
            all_player.add(b)
Пример #30
0
import check
import cli
import player
import computer
import numpy as np

game = False
p_coor = np.zeros((3,3))
c_coor = np.zeros((3,3))

cli.intro()
while not game:
	c_coor = computer.play(p_coor, c_coor)
	cli.render(p_coor, c_coor)
	if check.check(c_coor):
		game = True
		print "Computer wins"
		break
	p_coor = player.play(p_coor, c_coor)
	if check.check(p_coor):
		game = True
		print "Player wins"
	
Пример #31
0
 def play(self):
     """
     Start playing the item
     """
     audioplayer.play(self)
Пример #32
0
def makeAbeat(beatsPerMeasure, tempo):
    global previousBeat, beatsPerMIDI, modus

    while main:

        kickKansList = []
        SnareKansList = []
        kick = []
        snare = []
        snareDef = []

        #makes a list with "building blocks" --> 5/4 is list with 3 elements and a list with 2 elements.
        #7/4 is list with 2*list of 2 elements en 1* list of 3 elements. All the elements contain numbers define the chance
        kansPMListKick = ba.kansPerMaatsoort(beatsPerMeasure, kickKansList,
                                             "kick")

        kansPMListSnare = ba.kansPerMaatsoort(beatsPerMeasure, SnareKansList,
                                              "snare")

        #rotates list with building blocks, so 5/4 can be 3+2 or 2+3 etc..
        NewkickKansList = ba.transformKansList(kansPMListKick)

        NewSnareKansList = ba.transformKansList(kansPMListSnare)

        #generate a random list to compare with the chances defined in new<>KansList
        uitkomst = ba.makeRandomList(beatsPerMeasure)

        #generate kickList
        newKick = ba.generateList(NewkickKansList, kick, uitkomst,
                                  beatsPerMeasure)

        #generate snareList
        newSnare = ba.generateList(NewSnareKansList, snare, uitkomst,
                                   beatsPerMeasure)

        #looks for similarity in the kick and snare lists, if there is kick the snare is removed
        newSnares = ba.checkList(newSnare, newKick, snareDef, beatsPerMeasure)

        # sums all snares
        sumSnare = sum(newSnares)

        if sumSnare == 0:  #checks if there are snares in the generated beat
            newSnares = ba.addASnare(newKick, newSnares, beatsPerMeasure)
            newSnares = ba.checkList(newSnare, newKick, snareDef,
                                     beatsPerMeasure)
        else:
            beat = newSnares + newKick
            if beat == previousBeat:  #check if the new beat is the same as te last beat
                makeAbeat(beatsPerMeasure,
                          tempo)  #generate a new Beat if they are the same
            else:  #play the beat and covert list to a "midiList" with time events
                global midiKick, midiSnare, midiHihat, midiTempo

                #stores previousBeat to compare with the most recent beat, if they are the same a new beat is generated
                previousBeat = newSnare + newKick

                # print("beatsPerMeasure : ", beatsPerMeasure)
                midiTempo = tempo

                if beatsPerMeasure == 7:  #because 7/8 counts in 8th notes the tempo is twice is fast as 5/4
                    tempo = tempo * 2

                h = [1] * beatsPerMeasure
                if modus == 1:
                    #double note function doubles the note depth, in modus 1 the 8th notes are not used
                    newKick = ba.doubleNotes(newKick, beatsPerMeasure, 2)
                    newSnares = ba.doubleNotes(newSnares, beatsPerMeasure, 2)
                    h = ba.doubleNotes(
                        h, beatsPerMeasure, 2
                    )  #because the note depth is twice as high te tempo and beatsPerMeasure is * 2
                    beatsPerMeasure = beatsPerMeasure * 2
                    tempo = tempo * 2
                if modus == 2:  #note depth is set to eighth notes
                    newKick = ba.doubleNotes(newKick, beatsPerMeasure, 2)
                    newSnares = ba.doubleNotes(newSnares, beatsPerMeasure, 2)
                    h = ba.doubleNotes(h, beatsPerMeasure, 2)
                    #generate a hihat pattern with 8th notes
                    h = ba.countTriggers(newKick, newSnares, h,
                                         beatsPerMeasure)
                    beatsPerMeasure = beatsPerMeasure * 2
                    tempo = tempo * 2
                    #checks where there is no snare and if there is a snare it adds none to the list.
                    # for example [0,1,2,3,none,5,6,none] etc..
                    notSnare = ba.searchForNotSnare(newSnares)
                    #splits list for example [0,1,2,3] [5,6] etc..
                    splitNotSnare = ba.split(notSnare, None)
                    #generate a kick pattern with 8th notes, choses from the splitted lists
                    kick = ba.getKickPosition(splitNotSnare)
                    #from timestamp to a list with 1 and 0
                    newKick = ba.eventsToIndex(kick, beatsPerMeasure)
                    #if there is no snare on the first beat, kick is add on index 0
                    if newSnares[0] == 0:
                        newKick[0] = 1
                    if beatsPerMeasure == 14:
                        if sum(newSnares) == 1 and newSnares[
                                10] == 1:  #add some snares if there is only 1 snare on index 10
                            moreSnares = ba.addMoreSnares(
                                newKick, newSnares, beatsPerMeasure)
                            newSnares = ba.eventsToIndex(
                                moreSnares, beatsPerMeasure)

                #print generated beat
                print(" ")
                print("===================================================")
                print(" ")
                print("HIHAT : ", h)
                print("SNARE : ", newSnares)
                print("KICK  : ", newKick)
                print(" ")
                print("===================================================")
                print(" ")
                print(
                    colors.bcolors.WELKOM +
                    "if you like this beat, press 'y' to export or PRESS 'enter' for a new beat or 'q' to quit"
                    + colors.bcolors.ENDC)

                #convert list from 1 and 0 to timestamps
                beatsPerMIDI = beatsPerMeasure
                midiKick = midi.convertListForMidi(newKick, midiKick,
                                                   beatsPerMeasure)
                midiSnare = midi.convertListForMidi(newSnares, midiSnare,
                                                    beatsPerMeasure)
                midiHihat = midi.convertListForMidi(h, midiHihat,
                                                    beatsPerMeasure)

                tempo = 60 / tempo  #form BPM to time millis
                player.play(newKick, newSnares, h, beatsPerMeasure, tempo)
Пример #33
0
 def play(self, event):
     if player.p.loaded == True and player.p.streaming == False:
         if player.p.stream.is_playing == False:
             player.play()
         else:
             player.pause()
Пример #34
0
def play(args):
    log.info('play')
    player.play()
Пример #35
0
 def play(self):
     """
     Start playing the item
     """
     audioplayer.play(self)
Пример #36
0
import time
import sys
import config
import player
import wx
app = wx.App(redirect=False)
from gui import interface
config.setup()
interface.window.Show()

if config.appconfig['general']['resumelastsong']==True and config.appconfig['general']['lastsong']!="":
	try:
		player.open_file(config.appconfig['general']['lastsong'])
		player.p.stream.set_position(int(config.appconfig['general']['lastsongposition']))
		player.play()
	except:
		config.appconfig['general']['lastsong']=""
		config.appconfig['general']['lastsongposition']=0

app.MainLoop()
Пример #37
0
for i in range(winSize):
    R[i]=N.exp(j*N.pi*i)

   
yChunk=s.tVect()   

y=N.zeros(samples,N.float)   

player= player.Player()

nChunks = int(samples/chunkSize)

w=s.hanning()
W=P.fft(w)

P.plot(abs(W))
P.show()
    
for i in range(nChunks-1):
    i1=i*chunkSize
    i2=i1+winSize
    
    z=N.double(P.ifft(X1))
    y[i1:i2] += z*w
    X1 *= R
    

player.play(y)

Пример #38
0
    def update(self):
        global mousex, mousey
        if self.state == states["START"]:
            initial_hand_size = 5
            self.player1.draw_cards(initial_hand_size)
            self.player2.draw_cards(initial_hand_size)
            self.set_state(states["PICK_MOVE"])

        for event in pygame.event.get():
            if event.type == pygame.locals.QUIT:
                pygame.quit()
            elif event.type == pygame.locals.KEYDOWN:
                if event.key == pygame.locals.K_ESCAPE:
                    pygame.event.post(pygame.event.Event(pygame.locals.QUIT))
                elif event.key == 13 and not self.state == 5:
                    self.end_turn()
                    #self.set_state(states["PICK_MOVE"])
            elif event.type == pygame.locals.MOUSEMOTION:
                mousex, mousey = event.pos
                #check end turn
                #(1041,363), (1131,405)
            elif event.type == pygame.locals.MOUSEBUTTONDOWN and event.button == 1:
                if 1024 <= mousex <= 1131 and 363 <= mousey <= 405 and not self.state == 5:
                    self.end_turn()

            if game.state == states['WIN']:
                if event.type == pygame.locals.MOUSEBUTTONDOWN:
                    self.reinit()
                    self.state = states["PICK_MOVE"]

            if game.state == states['PICK_TARGET_CARD']:
                if event.type == pygame.locals.MOUSEBUTTONDOWN:
                    if event.button == 3:
                        game.state = states["PICK_MOVE"]
                    else:
                        hand = game.get_current_player().hand
                        for i in range(0, len(hand)):
                        # if the click was within the boundary of a card, play that card
                            if hand[i].posx <= mousex <= hand[i].posx + screen.CARD_WIDTH and hand[i].posy <= mousey <= hand[i].posy + screen.CARD_HEIGHT:
                                game.state = states['PICK_MOVE']
                                return i if hand[i].isFunction else None

            # if the player is picking a card to play
            if game.state == states["PICK_MOVE"]:
                # if the player left clicks,
                if event.type == pygame.locals.MOUSEBUTTONDOWN and event.button == 1:
                    player = game.player1
                    if game.current_player == 1:
                        hand = game.player1.hand
                    else:
                        hand = game.player2.hand
                        player = game.player2

                    # check move
                    #(763, 372), (820,399)
                    if 763 <= mousex <= 820 and 372 <= mousey <= 399:
                        p = game.get_current_player()
                        if p.current_cycles >= 1 and not p.moved_this_turn:
                            po = game.get_inactive_player()
                            game.state = states["PICK_TARGET_MEMORY"]
                            i = game.update()
                            while i is None and game.state == states["PICK_TARGET_MEMORY"]:
                                i = game.update()
                            if i is not None:
                                m = p.get_memory(i)
                                if m.value is not None:
                                    moved = False
                                    for j in range(0, len(po.memory)):
                                        n = po.get_memory(j)
                                        if n.value is None and m.get_color() == game.current_player and po.put_memory(j, m.value, m.length):
                                            po.get_memory(j).color(game.current_player)
                                            p.current_cycles -= 1
                                            p.moved_this_turn = True
                                            game.state = states["PICK_MOVE"]
                                            moved = True
                                            break
                                    if not moved and m.get_color() == game.current_player:
                                        game.win('Player ' + str(self.current_player) + ' has won by overflowing his opponent\'s memory.\nClick to restart.')

                    # check push
                    #(928,162), (987, 190)
                    if 928 <= mousex <= 987 and 162 <= mousey <= 190:
                        game.state = states["PICK_TARGET_MEMORY"]
                        i = game.update()
                        while i is None and game.state == states["PICK_TARGET_MEMORY"]:
                            i = game.update()
                        if i is not None:
                            v = player.get_memory(i).value
                            if v is not None:
                                game.stack.append(player.get_memory(i).value)
                    if len(game.stack) > 25:
                        game.win('Player ' + str(game.get_inactive_player().number) + 'has won the game after Player ' + str(game.current_player) + ' overflowed the stack.\nClick to restart.' )
                    elif game.state != 5:
                        game.state = states["PICK_MOVE"]

                    for i in range(0, len(hand)):
                        # if the click was within the boundary of a card, play that card
                        if hand[i].posx <= mousex <= hand[i].posx + screen.CARD_WIDTH and hand[i].posy <= mousey <= hand[i].posy + screen.CARD_HEIGHT:
                            player.play(i, game)
                            break
            elif game.state == states["PICK_TARGET_MEMORY"] or game.state == states["PICK_EITHER_MEMORY"]:
                p = None
                l1 = None
                if game.state == states["PICK_TARGET_MEMORY"]:
                    p = game.get_current_player().memory
                else:
                    l1 = len(game.get_current_player().memory)
                    p = game.get_current_player().memory[:]
                    p.extend(game.get_inactive_player().memory)

                if event.type == pygame.locals.MOUSEBUTTONDOWN and event.button ==1:
                    for i in range(0, len(p)):
                        m = p[i]
                        if m.posx <= mousex <= m.posx + 2*m.width and m.posy <= mousey <= m.posy + 2*m.height:
                            game.state = states["PICK_MOVE"]
                            return i
                if event.type == pygame.locals.MOUSEBUTTONDOWN and event.button == 3:
                    game.state = states["PICK_MOVE"]
        return None
Пример #39
0
 def playfile2(self):
     player.play(self.filepath2)
            songsmith.Note(songsmith.nametofreq("E4"), 0.5, 8000)
        ]),
        songsmith.Chord(notes=[
            songsmith.Note(songsmith.nametofreq("C4"), 0.5, 8000),
            songsmith.Note(songsmith.nametofreq("E4"), 0.5, 8000),
            songsmith.Note(songsmith.nametofreq("G4"), 0.5, 8000)
        ]),
        songsmith.Chord(notes=[
            songsmith.Note(songsmith.nametofreq("C4"), 1.5, 8000),
            songsmith.Note(songsmith.nametofreq("E4"), 1.5, 8000),
            songsmith.Note(songsmith.nametofreq("G4"), 1.5, 8000),
            songsmith.Note(songsmith.nametofreq("C5"), 1.5, 8000)
        ])
    ])
    song.addovertones(5)
    return str(song)

def TEST3():
    """ Returns a 16-bit string audio waveform to test musical beats"""
    return str(songsmith.Phrase(chords=[
        songsmith.Chord(notes=[
            songsmith.Note(220, 20.0, 16000),
            songsmith.Note(220.2, 20.0, 16000)
        ])
    ]))

if __name__=="__main__":
    player.play(waveform.from_string(TEST1()))
    player.play(waveform.from_string(TEST2()))
    player.play(waveform.from_string(TEST3()))
Пример #41
0
        if order == 'a':
            manager.cancel(None)
            return 1
        # switch
        if order == 's':
            manager.switch([])
            return 1
        return -1


listenThread.on = lambda :append(AlarmPage())
listenThread.off = pop
listenThread.refresh = lambda :stack[-1].reprint()


try:
    # 模块初始化
    import manager
    if data['config']['warning_pause']:
        initUtil.warning_pause()
    append(MainPage())
    listenThread.start()
    while (1):
        order = raw_input()
        stack[-1].do(order)
        if len(stack) == 0:
            break
finally:
    player.play(None)
    listenThread.stop()
Пример #42
0
def _start_playing():
    player.play(state.playing.path, lambda: next())
    _after_movement()
Пример #43
0
def pomodoro_termino(tarea):
    player.play(sonido)
    mensaje3 = "Ya pasaron 25 minutos"
    mensaje4 = "Ya debió terminar: %s" % tarea
    notify.create_icon(mensaje3,mensaje4)
    gtk.main()
Пример #44
0
import parser
import player

STORY_FILE = 'scripts/sf_adventure.txt'

if __name__ == '__main__':
    with open(STORY_FILE) as f:
        player.play(parser.parse_script(f.read()))
Пример #45
0
def main():
	print((sys.version))
	
	#get presets
	getPresets()
	writePresets()
	
	
	inp = inputs.inputs()	
	stations = radioTime.Stations()
	
	menuList = ("Radio", "USB", "Settings")
	menuListSel = "Radio"
	stationListSel = ""
	activeStation = player.getInformation()["Station"]
	activePage = "Menu"
	activePageLast = "Menu"
	
	
	#init done, fade to main prog
	visu.explosion()
	
	#update screen and handle events
	running = True
	while running:
		action = inp.getInput()
	
		
		#Menu ----------------------------------------------------------------
		if activePage == "Menu":
			activeItem = menuList.index(menuListSel)
			if action == "up":
				activeItem -= 1
				if activeItem < 0: activeItem = 0
			elif action == "down":
				activeItem += 1
				if activeItem >= len(menuList): activeItem = len(menuList) - 1
			elif action == "enter":
				if menuListSel == "Radio":
					activePage = "StationSelect" if activeStation == "" else "Radio"
				else:
					activePage = menuListSel
			elif action == "back":
				activePage = activePageLast
			
			menuListSel = menuList[activeItem]

			visu.menu1(menuList, activeItem)

		
		#Radio ---------------------------------------------------------------
		elif activePage == "Radio":
			if action == "up":
				player.volume(2)
			elif action == "down":
				player.volume(-2)
			elif action == "enter":
				activePage = "StationSelect"
			elif action == "back":
				activePage = "Menu"
			
			info = player.getInformation()
			
			if info["Station"] == "":
					info["Station"] = activeStation
			if info["Station"] != activeStation:
				try:
					url = stations.stations[activeStation]
					del stations.stations[activeStation]
					stations.stations[info["Station"]] = url
					activeStation = info["Station"]
					stationListSel = activeStation
				except:
					pass
			
			visu.radio(activeStation, info["Text"], info["Volume"], info["WLAN"])
		
		#StationSelect -------------------------------------------------------
		elif activePage == "StationSelect":
			nameList = list(stations.stations.keys())
			nameList.sort(key=lambda x: x.lower()) #Case In-sensitive
			
			try:
				activeItem = nameList.index(stationListSel)
			except:
				activeItem = 0

			if action == "up":
				activeItem -= 1
				if activeItem < 0: activeItem = 0
			elif action == "down":
				activeItem += 1
				if activeItem >= len(stations.stations): activeItem = len(stations.stations) - 1
			elif action == "enter":
				if activeStation != stationListSel:			
					activeStation = stationListSel			
					stations.updateUrl(activeStation)
					player.play(stations.stations[activeStation])
				activePage = "Radio"	
			elif action == "back":
				activePage = "Menu" if activeStation == "" else "Radio"
			
			stationListSel = nameList[activeItem]
			
			visu.menu2(nameList, activeItem)

		
		#USB -----------------------------------------------------------------
		elif activePage == "USB":
			if action == "up":
				x = 0
				#volume up
			elif action == "down":
				x = 0
				#volume down
			elif action == "enter":
				activePage = "SongSelect"
			elif action == "back":
				activePage = "Menu"
				
			if action == "none":
				visu.usb()
			
		#Settings ------------------------------------------------------------
		elif activePage == "Settings":
			if action == "up":
				x = 0
				#foo
			elif action == "down":
				x = 0
				#foo
			elif action == "enter":
				x = 0
				#foo
			elif action == "back":
				activePage = "Menu"
			
			if action == "none":
				visu.settings()	
Пример #46
0
  # Removes partition without any note
  _song.partitions = filter(lambda partition: partition.notes, _song.partitions)
  
  # Start the song at time == 0
  start = min(map(lambda partition: min([sys.maxint] + map(lambda note: note.time, partition.notes)), _song.partitions))
  for partition in _song.partitions:
    for note in partition.notes:
      note.time = note.time - start
      
  return _song
  
if __name__ == "__main__":
  import sys, globdef
  
  file = open(sys.argv[1])
  
  s = parse(file)
  
  #print len(s.partitions)
  #sys.exit()
  
  #print s
  
  import player
  player.play(s)
  
  import time
  
  while 1:
    time.sleep(1000)
Пример #47
0
	def playfile1(self):
		player.play(self.filepath1)
Пример #48
0
	def playfile2(self):
		player.play(self.filepath2)
Пример #49
0
 def play(self, menuFactory):
     return player.play(menuFactory)
Пример #50
0
 def playaudio(self, index):
     s = headsets[index]
     player.play(s)
Пример #51
0
    def on_partial_transcription(self, text):
        print('on_partial_transcription: {}'.format(text))

        self.listening = False
        player.play(self.synthesize(text))
        self.listening = True
Пример #52
0
    def main(self):
        """Play a midi file with sound samples
        """
        player.init()
        clock = pygame.time.Clock()
        old_time = 0
        p_done = False

        pitch_offset = 60
        need_update_display = True
        while not p_done:
            # events
            for ev in pygame.event.get():
                need_update_display = True
                menu_bar_screen = self.menu_bar.update(ev)
                if self.menu_bar:
                    self.menu_bar_info.set(self.get_menus_info_bar())
                    # self.menu_bar_info.update(ev)

                if self.menu_bar.choice:
                    try:
                        self.load_resource(self.menu_bar.choice_label[-1])
                    except Exception, e:
                        print "menu error:", e
                    # if have choice, continue event
                    continue

                if ev.type == MOUSEBUTTONUP:
                    if ev.pos[1] > 60:
                        continue
                    # enable/disable tracks
                    for track_idx in self.enabled_tracks:
                        sw = self.enabled_tracks_switch[track_idx]
                        if sw.collidepoint(ev.pos):
                            self.enabled_tracks[track_idx] = not self.enabled_tracks[track_idx]

                            idx = self.tracks_order_idx[track_idx]
                            note_color = self.piano.TRACK_COLORS[idx % len(self.piano.TRACK_COLORS)]
                            if self.enabled_tracks[track_idx]:
                                self.piano.screen.fill(note_color, sw)
                            else:
                                self.piano.screen.fill(self.piano.color_lines, sw)

                elif ev.type == MOUSEBUTTONDOWN:
                    if ev.button == 5: # scroll down
                        self.staff_offset_x += 40

                    elif ev.button == 4: # scroll up
                        self.staff_offset_x -= 40
                        if self.staff_offset_x < 0:
                            self.staff_offset_x = 0

                    elif ev.button == 3: # right button
                        self.is_pause = not self.is_pause

                    elif ev.button == 1:   # left button
                        if ev.pos[1] < 60: # progress bar can not click
                            continue
                        clicked_staff_number = int((ev.pos[1] - self.staff_top) / (self.piano.staff_total_lines * self.piano.staff_space_height))
                        wraped_staff_offset = 0
                        if clicked_staff_number > 0:
                            wraped_staff_offset += self.piano.lastbar_pos_in_line1
                        if clicked_staff_number > 1:
                            wraped_staff_offset += self.piano.lastbar_pos_in_line2 * (clicked_staff_number-1)

                        timestamp_offset_x = (
                            self.staff_offset_x +
                            ev.pos[0] +
                            wraped_staff_offset
                        ) * self.piano.timestamp_range / self.screen_rect.width

                        self.last_timestamp = -1
                        for idx, midi_line in enumerate(self.all_midi_lines):
                            cmd, pitch, volecity_data, track_idx, pitch_timestamp = midi_line[:5]
                            if timestamp_offset_x > pitch_timestamp:
                                if self.last_timestamp != pitch_timestamp:
                                    self.midi_cmd_idx = idx
                                    self.last_timestamp = pitch_timestamp
                            elif timestamp_offset_x < pitch_timestamp:
                                break

                        self.play_one_timestamp_while_paused = True
                        self.piano.reset_piano()


                elif ev.type == KEYUP:
                    if ev.key == K_ESCAPE:
                        p_done = True
                        break

                    # MENU Reload
                    elif ev.key == K_RETURN:
                        menus_in_bar, self.midi_filename_data = get_menu_data()
                        self.menu_bar.set(menus_in_bar)

                    # Stop
                    elif ev.key == K_s:
                        self.piano.reset_piano()
                        self.staff_offset_x = 0
                        self.midi_cmd_idx = 0
                        self.last_timestamp = -1
                        self.is_pause = True

                    # Pause/Play
                    elif ev.key == K_SPACE:
                        self.is_pause = not self.is_pause

                    # is_longbar_show
                    elif ev.key == K_c:
                        self.piano.is_longbar_show = not self.piano.is_longbar_show

                    elif ev.key == K_COMMA:
                        # Slower
                        parse_midi.g_mseconds_per_quarter = int(60000 / (
                            60000 / parse_midi.g_mseconds_per_quarter - 10))
                        if parse_midi.g_mseconds_per_quarter > 2000:
                            parse_midi.g_mseconds_per_quarter = 2000
                        self.menu_bar_info.set(self.get_menus_info_bar())
                    elif ev.key == K_PERIOD:
                        # Faster
                        parse_midi.g_mseconds_per_quarter = int(60000 / (
                            60000 / parse_midi.g_mseconds_per_quarter + 10))
                        if parse_midi.g_mseconds_per_quarter <= 200:
                            parse_midi.g_mseconds_per_quarter = 200
                        self.menu_bar_info.set(self.get_menus_info_bar())

                    #Page_Up/Page_Down
                    elif ev.key == K_DOWN:
                        self.staff_offset_x += self.piano.lastbar_pos_in_line1
                    elif ev.key == K_UP:
                        self.staff_offset_x -= self.piano.lastbar_pos_in_line1
                        if self.staff_offset_x < 0:
                            self.staff_offset_x = 0

                    # Previous/Next MIDI
                    elif ev.key in [K_LEFT, K_RIGHT]:
                        need_reload = False
                        if ev.key == K_LEFT:
                            if self.midi_filename_idx > 0:
                                self.midi_filename_idx -= 1
                                need_reload = True
                        elif ev.key == K_RIGHT:
                            if self.midi_filename_idx+1 < len(self.midi_filename_data):
                                self.midi_filename_idx += 1
                                need_reload = True
                        if need_reload:
                            midi_filename = self.midi_filename_data[self.midi_filename_idx]
                            self.load_resource(midi_filename)

                    # Metronome
                    elif ev.key == K_m:
                        if (1.0 - player.g_metronome_volume) / 2 < 0.1:
                            player.g_metronome_volume += 0.1
                        else:
                            player.g_metronome_volume += (1.0 - player.g_metronome_volume) / 2

                    # # Set Progress Percent
                    # elif ev.key in [K_0, K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9]:
                    #     self.piano.reset_piano()
                    #     self.midi_cmd_idx = self.all_midi_lines_length * (ev.key - 48) / 10
                    #     self.last_timestamp = -1

                    # Set Pitch Offset
                    elif ev.key in [K_v, K_b, K_n]:
                        pitch_offset = {K_v: 36,  K_b: 60,  K_n: 84}[ev.key]

                    elif ev.key == K_f:
                        player.g_volecity_adjust = (player.g_volecity_adjust+1) % len(player.g_volecity_list)
                        player.load_sounds([(midi_data[1], midi_data[2]) for midi_data in self.all_midi_lines],
                                           self.sounds)

                    elif ev.key == K_z:
                        if self.piano.staff_space_height > 2:
                            self.piano.staff_space_height /= 2
                        self.piano.timestamp_range = TIMESTAMP_RANGE * parse_midi.g_ticks_per_quarter / parse_midi.g_mseconds_per_quarter
                        self.piano.timestamp_range = self.piano.timestamp_range * self.piano.staff_space_height_base / self.piano.staff_space_height
                    elif ev.key == K_x:
                        if self.piano.staff_space_height < 128:
                            self.piano.staff_space_height *= 2
                        self.piano.timestamp_range = TIMESTAMP_RANGE * parse_midi.g_ticks_per_quarter / parse_midi.g_mseconds_per_quarter
                        self.piano.timestamp_range = self.piano.timestamp_range * self.piano.staff_space_height_base / self.piano.staff_space_height

                    # Play Piano with keys
                    elif ev.key in PITCH_OF_KEY_ON_KEYBOARD:
                        pitch = pitch_offset + PITCH_OF_KEY_ON_KEYBOARD.index(ev.key)
                        player.stop(pitch, 100, self.sounds)
                        player.load_sounds([(pitch, 100)], self.sounds)
                        cmd = "NOTE_OFF"
                        self.piano.show_keys_press(cmd, pitch)

                elif ev.type == KEYDOWN:
                    if ev.key in PITCH_OF_KEY_ON_KEYBOARD:
                        pitch = pitch_offset + PITCH_OF_KEY_ON_KEYBOARD.index(ev.key)
                        player.load_sounds([(pitch, 100)], self.sounds)
                        player.play(pitch, 100, self.sounds)
                        cmd = "NOTE_ON"
                        self.piano.show_keys_press(cmd, pitch)

            # must out of events loop
            if self.menu_bar or self.menu_bar.choice:
                self.gl_screen_blit()
                pygame.display.flip()
                clock.tick(10)
                continue

            # get cmd
            try:
                if (self.is_pause and not self.play_one_timestamp_while_paused):
                    raise Exception("paused")
                # repeat
                if self.midi_cmd_idx >= self.all_midi_lines_length:
                    raise Exception("repeat")

                midi_line = self.all_midi_lines[self.midi_cmd_idx]
                self.midi_cmd_idx += 1
                cmd, pitch, volecity_data, track_idx, pitch_timestamp = midi_line[:5]
                volecity = player.get_volecity(volecity_data)
                if pitch not in [0, 1] + player.g_grand_pitch_range:
                    continue
                if track_idx >= 0 and not self.enabled_tracks.get(track_idx, False):
                    continue
                if self.last_timestamp == -1:
                    # init last timestamp
                    self.last_timestamp = pitch_timestamp - 1
            except Exception, e:
                if need_update_display:
                    self.piano.show_notes_staff_in_page(self.enabled_tracks, self.tracks_order_idx,
                                            self.notes_in_all_staff, self.last_timestamp,
                                            self.staff_top,
                                            parse_midi.g_bar_duration,
                                            parse_midi.g_time_signature_n,
                                            self.staff_offset_x, self.is_pause)
                    has_stoped = player.real_stop(self.sounds)
                    self.gl_screen_blit()
                    pygame.display.flip()
                    need_update_display = False

                if self.midi_cmd_idx >= self.all_midi_lines_length:
                    if self.midi_repeat_count < TRAINING_REPEAT_TIMES:
                        self.midi_repeat_count += 1
                        self.staff_offset_x = 0
                        self.midi_cmd_idx = 0
                        self.last_timestamp = -1
                    else:
                        if self.midi_filename_idx+1 < len(self.midi_filename_data):
                            self.midi_filename_idx += 1
                        else:
                            self.midi_filename_idx = 0
                        midi_filename = self.midi_filename_data[self.midi_filename_idx]
                        self.load_resource(midi_filename)
                        self.is_pause = False

                clock.tick(40)
                continue
Пример #53
0
from music import Note
from player import play

from music import notes, Semitones, Reference
from exercise import IntervalIdentificationMelodicExercise

intervals = [Semitones(i) for i in range(2, 9)]
exercise = IntervalIdentificationMelodicExercise(intervals=intervals,
                                                 repetition=5)

for (a, b, c) in exercise.generate_exercises():
    print('-' * 50)
    print(a, b, c)
    play(a)
    play(b)
Пример #54
0
	def play(self, event):
		if player.p.loaded==True and player.p.streaming==False:
			if player.p.stream.is_playing==False:
				player.play()
			else:
				player.pause()
Пример #55
0
def play(id):
    resource = Station()
    station = resource.get(id)
    player.play(station)
    publisher.publishStatus(station)
    return jsonify(station)
Пример #56
0
def buttonPressed(channel):
    song1 = [
        ("C", 0.5),
        ("C", 0.5),
        ("G", 0.5),
        ("G", 0.5),
        ("A", 0.5),
        ("A", 0.5),
        ("G", 1),
        ("F", 0.5),
        ("F", 0.5),
        ("E", 0.5),
        ("E", 0.5),
        ("D", 0.5),
        ("D", 0.5),
        ("C", 1),
        ("G", 0.5),
        ("G", 0.5),
        ("F", 0.5),
        ("F", 0.5),
        ("E", 0.5),
        ("E", 0.5),
        ("D", 1),
        ("G", 0.5),
        ("G", 0.5),
        ("F", 0.5),
        ("F", 0.5),
        ("E", 0.5),
        ("E", 0.5),
        ("D", 1),
        ("C", 0.5),
        ("C", 0.5),
        ("G", 0.5),
        ("G", 0.5),
        ("A", 0.5),
        ("A", 0.5),
        ("G", 1),
        ("F", 0.5),
        ("F", 0.5),
        ("E", 0.5),
        ("E", 0.5),
        ("D", 0.5),
        ("D", 0.5),
        ("C", 1),
    ]

    song2 = [
        ("E", 0.5),
        ("lB", 0.5),
        ("C", 1),
        ("E", 0.5),
        ("lB", 0.5),
        ("C", 1),
        ("C", 0.25),
        ("C", 0.25),
        ("C", 0.25),
        ("C", 0.25),
        ("D", 0.25),
        ("D", 0.25),
        ("D", 0.25),
        ("D", 0.25),
        ("E", 0.5),
        ("lB", 0.5),
        ("C", 2),
    ]

    song3 = [
        ("E", 1),
        ("E", 1),
        ("F", 1),
        ("G", 1),
        ("G", 1),
        ("F", 1),
        ("E", 1),
        ("D", 1),
        ("C", 1),
        ("C", 1),
        ("D", 1),
        ("E", 1),
        ("E", 1.25),
        ("D", 0.25),
        ("D", 1),
        ("E", 1),
        ("E", 1),
        ("F", 1),
        ("G", 1),
        ("G", 1),
        ("F", 1),
        ("E", 1),
        ("D", 1),
        ("C", 1),
        ("C", 1),
        ("D", 1),
        ("E", 1),
        ("E", 1.25),
        ("C", 0.25),
        ("C", 1),
    ]
    song4 = [
        ("G", 1),
        ("E", 1),
        ("G", 1.5),
        ("E", 1),
        ("C", 1.5),
        ("D", 1),
        ("E", 1),
        ("F", 1.25),
        ("D", 1.25),
        ("G", 1.25),
        ("C", 1),
        ("B", 2),
    ]
    song5 = []
    song6 = []
    song7 = []
    song8 = []
    songList = [song1, song2, song3, song4, song5, song6, song7, song8]
    print("button pressed")
    GPIO.output(lightList[0], 1)
    player.play(buzzer, songList[currLight], tempo=120)