def start(): global index global player global playing global first_time global flag try: song_name=onlyfiles[index].replace(".mp3","") label.configure(text=song_name) player=MediaPlayer(join(file_dir,onlyfiles[index])) player.play() time.sleep(1) playing = True first_time = False button2.configure(image=pausePh) millis=get_len(player) seconds = (millis / 1000) % 60 seconds = int(seconds) minutes = (millis / (1000 * 60)) % 60 minutes = int(minutes) timeformat = '{:02d}:{:02d}'.format(minutes, seconds) labelpos.configure(text='Total-' + timeformat) flag=True t1=threading.Thread(target=position,args=(millis,)) t1.start() except(IndexError): index=0 start()
def __init__(self): """Initializes empty class variables. The class initializes the following class variables: vlc_player The variable, which is used to play music via an instance of a vlc.MediaPlayer. It is initialized with 'None'. wish_list A list of file paths, that determine the files that are left to play. It is initialized as an empty list. playing_thread A thread that calls 'self.play()' and which is joined in the destructor. It is initialized and started. keep_playing A boolean that signals the method 'self.play()' and thus the thread 'self.playing_thread' when to stop the playback and prepare to be destructed. It is initialized with 'True'. is_paused The boolean signals the method 'play()' when the current playback is paused and is toggled by the method 'self.pause()'. It is initialized with 'False'.. Semaphores ---------- change_player_list A 'threading.Semaphore' that should be acquired and released when ever 'self.wish_list' or 'self.wish_list'. """ self.vlc_player = MediaPlayer() self.change_player_list = Semaphore() self.wish_list = list() self.keep_playing = True self.is_paused = False self.playing_thread = Thread(target=self.play) self.playing_thread.start()
def __init__(self, url): self.player = MediaPlayer(url) self.stream_url = url self._volume = 0 self.player.audio_set_volume(self._volume) self.player.play() self.timer = None
def init_track(self, filepath): try: self.stop() except AttributeError: pass from vlc import MediaPlayer p = MediaPlayer(filepath) self.music_dict['track'] = p
def toggle_playing(): global p if p.is_playing(): p.pause() else: p.play() # We need the next part to start the song again, as soon as the song finishes if p.get_time() == 0: p.stop() p = MediaPlayer(song_path) p.play()
def __init__(self, vlc_instance): Talker.__init__(self) self.vlc_instance = vlc_instance self.media_player: MediaPlayer = MediaPlayer(self.vlc_instance) self.media_list_player: MediaListPlayer = MediaListPlayer(self.vlc_instance) self.media_list_player.set_media_player(self.media_player) self.media_list: MediaList = MediaList(self.vlc_instance) self.media_list_player.set_media_list(self.media_list) self.vlc_events = self.media_player.event_manager() self.vlc_events.event_attach(EventType.MediaPlayerEndReached, self.__on_end_event) self.vlc_events.event_attach(EventType.MediaPlayerStopped, self.__on_stop_event) self.vlc_events.event_attach(EventType.MediaPlayerPlaying, self.__on_play_event)
def playMessage(msg): """ Cria um arquivo na pasta audios, dizendo uma mensagem passada por parametro espera 15s e deleta o arquivo """ tts = gTTS(msg, lang="pt-br") file = "./audios/temp.mp3" tts.save(file) player = MediaPlayer(file) player.play() sleep(10) os.remove(file)
def start(self, name, play=True): if self.player != None: self.player.stop() self.player = None self.mediaplayer = MediaPlayer() assert (isinstance(name, list)) playlist = MediaList() for entry in name: if entry is not None: playlist.add_media(entry) self.player = MediaListPlayer() self.player.set_media_list(playlist) self.player.set_media_player(self.mediaplayer) if play: self.play()
def insert_alert(self, id, msg): # el try catch es porque self.alerts no existe en el # estado inicial s_timespamp = datetime.now().strftime('%d-%m-%Y %I:%M %p') try: self.alerts.append((id, s_timespamp, msg)) except: self.alerts = [(id, s_timespamp, msg)] s = "" for a in self.alerts: # dejo el s[0] para debugging s += str(a[1]) + " - " + str(a[2]) + "\n" self.txtArea.setPlainText( s ) tts = gTTS(text=msg, lang='es') tts.save("msg.mp3") p = MediaPlayer("msg.mp3") p.play() return id
def play_webradio(self, url): self.player = MediaPlayer(url) self.player.play() self.playing_radio = True
def play(self, audio_path): self.audio_path = audio_path self.current_audio = MediaPlayer('file://' + audio_path) self.current_audio.play()
player = random.choice(players) player.play() # Wait till the current sound is done while player.is_playing() or player.will_play(): pass player.stop() # Configure button pin GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Create players by find all mp3 files in the working dir files = os.listdir('.') players = [ MediaPlayer(file_name) for file_name in files if file_name.endswith('.mp3') ] print("Loaded {} sounds".format(len(players))) play(random.choice(players)) while True: input_state = GPIO.input(18) if input_state == False: time.sleep(0.1) input_state = GPIO.input(18) if input_state == False: play(random.choice(players)) print("Done") else: print("Debounce caught invalid press")
def play(url): MediaPlayer('https:' + url).play()
#!/usr/bin/env python3 from gpiozero import MotionSensor from vlc import MediaPlayer from signal import pause from sys import exit pir = MotionSensor(24) song_path = "../media/song.ogg" p = MediaPlayer(song_path) def toggle_playing(): global p if p.is_playing(): p.pause() else: p.play() # We need the next part to start the song again, as soon as the song finishes if p.get_time() == 0: p.stop() p = MediaPlayer(song_path) p.play() pir.when_motion = toggle_playing try: pause() except KeyboardInterrupt:
def make_vlc_player(songname): ''' Returns a VLC Media Player object ''' player = MediaPlayer(resources_folder + songname) return player
def __init__(self): self.current_audio = MediaPlayer()
global index try: index=0 onlyfiles=[""] file_dir=filedialog.askdirectory() player.stop() onlyfiles = [f for f in listdir(file_dir) if f.endswith('.mp3')] if(onlyfiles==[]): # if no mp3 files in directory raise FileNotFoundError start() except(FileNotFoundError): if(file_dir==""): pass else: messagebox.showinfo('Error','No MP3 in selected folder select a folder with mp3 file') player=MediaPlayer() libvlc_audio_set_volume(player,70) def start(): global index global player global playing global first_time global flag try: song_name=onlyfiles[index].replace(".mp3","") label.configure(text=song_name) player=MediaPlayer(join(file_dir,onlyfiles[index])) player.play() time.sleep(1) playing = True first_time = False
from flask import Flask, render_template, redirect, url_for, request, jsonify, abort import requests, winsound as ws, threading, service as srv, match, time, hue from vlc import MediaPlayer app = Flask(__name__) m = match.Match() previous_chal = {'id': -1} music_player = MediaPlayer("static/music trivia/payday.mp3") music_on = False ready = 0 fb = {"times": 0, "rate": 0} danceRank = list() DANCE_POINTS = [50, 100, 250, 400, 600, 800, 1000, 1500] RIGHT_ANSWER = 100 VOICE_HZ = {5: 1000, 50: 500, 100: 400, 150: 300, 250: 100, 350: 20} FITNESS_CHAL_MULTIPLIER = 5 FITNESS_PLAYER = MediaPlayer("static/music trivia/eye of the tiger.mp3") DANCE_PLAYER = MediaPlayer("static/music trivia/pump it.mp3") MUSIC_DANCE = False GAME_OVER_PLAYER = MediaPlayer("static/sound effects/Vittoria!.mp3") @app.route('/') def lobby(): return redirect(url_for('showPlayers')) @app.route('/categories') def categories(): r = requests.get(m.ONLINE_SERVER + "/categories")
if not os.path.exists(mp3_dir): os.makedirs(mp3_dir, exist_ok=True) if not os.path.exists(wav_dir): os.makedirs(wav_dir, exist_ok=True) if to_say in overrides.keys(): to_say = overrides[to_say] tts = gTTS(to_say.replace("-", " "), lang=language) tts.save(mp3) sound = AudioSegment.from_mp3(mp3) sound.export(wav, format="wav") if playback: player = MediaPlayer(wav) player.play() time.sleep(0.1) duration = player.get_length() / 1000 print(file_basename + " (" + str(duration) + "s)") time.sleep(duration) else: print(mp3) except KeyboardInterrupt: print("\n-- Ctrl^C ---") break except Exception: traceback.print_exc() break
def player(filename): MediaPlayer(filename).play()
def music_fa(): """this def for get music fa""" name_artist = args.n famle_artist = args.f track_name_artist = args.track url = "https://www.radiojavan.com/search?query="+name_artist+"+"+famle_artist+"+"+track_name_artist url_req = requests.get(url).text soup = BeautifulSoup(url_req, "lxml") soup_name_artist = soup.find("span", class_="artist_name") soup_name_track = soup.find("span", class_="song_name") get_txt_name = get_text(str(soup_name_artist)) get_txt_track = get_text(str(soup_name_track)) get_txt_name = get_txt_name.replace(" ", "-") get_txt_track = get_txt_track.replace(" ", "-") url_ext = url_download+get_txt_name+"-"+get_txt_track+".mp3" url_ext_2 = url_download_2+get_txt_name+"-"+get_txt_track+".mp3" url_ext_3 = url_download_3+get_txt_name+"-"+get_txt_track+".mp3" url_ext_3 = url_ext_3.replace("-&", "") url_ext_2 = url_ext_2.replace("-&", "") url_ext = url_ext.replace("-&", "") #show play list track artist try: #checkd url steram found or not found! u = urlopen(url_ext_2).readline() if u == b'Not found': if args.download: print("download done!") download(url_ext) exit() msg_player = "Mix Player\n" msg = " start play music " rows, columns = popen('stty size', 'r').read().split() # get size terminal msg_x = msg.center(int(columns)) msg_y = msg_player.center(int(columns)) system("clear") echo(style(msg_y, blink=True, bold=True, fg="red")) echo(style(msg_x, blink=True, bold=True, fg="red")) name = "\n\n\nartist: "+get_txt_name track = "\ntrack: "+get_txt_track echo(style(name, bold=True,fg="reset",)) echo(style(track, bold=True,fg="reset")) soup_name_track_all = soup.find_all("span", class_="song_name") j = 0 Music5 = " - - - - - 5 New music - - - - - " Music5 = Music5.center(int(columns)) echo(style(Music5, bold=True,fg="reset")) track_5 = soup_name_track_all[0:5] for i in track_5: global playlist_arti global playlist_artist_2 get_txt_track_all = get_text(str(i)) get_txt_track_all = get_txt_track_all.replace(" ", "-") all_tk = get_txt_track_all.center(int(columns)) j = j+1 print("\n\n",j,"-") echo(style(all_tk, bold=True,fg="reset")) MediaPlay2 = MediaPlayer(url_ext) MediaPlay2.play() sleep(240) # sleep for play muisc else: if args.download: download(url_ext_2) print("download done!") exit() msg_player = "------------Mix Player-----------\n" msg = " start play music \n\n" rows, columns = popen('stty size', 'r').read().split() msg_x = msg.center(int(columns)) msg_y = msg_player.center(int(columns)) system("clear") echo(style(msg_y, blink=True, bold=True,fg="red")) echo(style(msg_x, blink=True, bold=True,fg="red")) name = "\n\n\nartist: "+get_txt_name track = "\ntrack: "+get_txt_track echo(style(name, bold=True,fg="reset")) echo(style(track, bold=True,fg="reset")) soup_name_track_all = soup.find_all("span", class_="song_name") j = 0 Music5 = " - - - - - 5 New music - - - - - " Music5 = Music5.center(int(columns)) echo(style(Music5, bold=True,fg="reset")) track_5 = soup_name_track_all[0:5] for i in track_5: global playlist_arti global playlist_artist_2 get_txt_track_all = get_text(str(i)) get_txt_track_all = get_txt_track_all.replace(" ", "-") all_tk = get_txt_track_all.center(int(columns)) j = j+1 print("\n\n",j,"-") echo(style(all_tk, bold=True,fg="reset")) MediaPlay = MediaPlayer(url_ext_2) # strt stream muisc MediaPlay.play() sleep(240) # def PlaylistArtist(): # for track_in_playlist in soup_name_track_all: # playlists = get_text(str(track_in_playlist)) # print(playlists) except BaseException: system("clear") print("Exit Mix Player")
from vlc import MediaPlayer, State from time import sleep import re init = False p = MediaPlayer(r'$VLC_PLAYABLE_AUDIO_FILE_LOCATION') f = open(r'$LRC_FILE_LOCATION', 'r', encoding = 'utf-16le') timecodes_ms = [] texts = [] for item in f.readlines(): m = re.fullmatch('\[(?P<mm>\d\d):(?P<ss>\d\d).(?P<msms>\d\d)\](?P<txt>[\S ]+)?', item.strip()) if m: if m.group('txt') != None: texts.append(m.group('txt')) else: texts.append('') timecodes_ms.append( (int(m.group('mm'))*60000) + (int(m.group('ss'))*1000) + (int(m.group('msms')))) init = False p.play() while p.get_state() != State.Ended and p.get_state() != State.NothingSpecial: if p.get_state() != State.Opening: if init is False: duration = p.get_length() init = True pos_in_ms = duration*(p.get_position()) if len(timecodes_ms)>0: if pos_in_ms>timecodes_ms[0]: if len(texts) == 1 and texts[0] == '': print('\n[THE END]\n(waiting for song file to end)')
def __init__(self): self._filename = _read_file() self._audio = MediaPlayer(AUDIO_DIR + "/" + self.filename) self.play()
def pomodoro(task, rest, bigrest, maxrounds): try: speech = gTTS(text='tá', lang='pt-br', slow=False) speech.save("fx.mp3") except: print('Will run without sound') system('cls' if name == 'nt' else 'clear') sound = None if path.isfile('fx.mp3'): sound = MediaPlayer("fx.mp3") state = {'cur': 'task', 'rounds': 0} cfg = { 'task': task, 'rest': rest, 'big_rest': bigrest, 'max_rounds': maxrounds } def loopomodore(): nonlocal state nonlocal cfg nonlocal sound task = "🍅 None" if state['cur'] == 'task': state['rounds'] += 1 task = "🍅 Begin:" + datetime.now().strftime( "%d/%m/%Y %H:%M:%S") + ' | ' + input( colored('What is the current task?\n', 'green')) #chamada ao fim do loop def selection_screen(isnt_timeout): nonlocal state nonlocal task nonlocal cfg system('cls' if name == 'nt' else 'clear') log_folder = getenv('HOME') # task block if state['cur'] == 'task': #inserindo tempo decorrido para que a tarefa seja concluída if isnt_timeout: task += ' | TIME: {0} minutes'.format(isnt_timeout) else: task += ' | TIME: {0} minutes'.format(cfg['task']) # criando log no log_folder log = open('{0}/pymodore_log.txt'.format(log_folder), 'a') log.write('\n' + task) log.close() #big rest block if state['rounds'] == cfg['max_rounds']: state['cur'] = 'big_rest' log = open('{0}/pymodore_log.txt'.format(log_folder), 'a') log.write('\n' + '|-🍅-🍅- REST -🍅-🍅-|') log.close() message = "\nTime for a big rest! Press {0} and take {1} mins! {2}".format( colored('ENTER', 'green'), colored(cfg['big_rest'], 'red'), colored("('N' to quit)", 'magenta')) #rest block else: state['cur'] = 'rest' message = "\nStart rest? {0} to continue. {1}".format( colored('ENTER', 'green'), colored("('N' to quit)", 'magenta')) #iniciando nova tarefa else: state['cur'] = 'task' message = "\nStart new task? {0} to continue. {1}".format( colored('ENTER', 'green'), colored("('N' to quit)", 'magenta')) #saindo ou processeguindo no loop willcontinue = input(message) if willcontinue: if willcontinue.strip().lower()[0] == 'n': if path.isfile('fx.mp3'): remove('fx.mp3') return print( colored( 'Remember to check your log in {0}'.format( log_folder), 'red')) loopomodore() input('Press {0} to start the timer. {1}'.format( colored('ENTER', 'green'), colored('🍅', 'red'))) if state['cur'] == 'task': print("Seconds are bad " + colored('ヽ(ಠ_ಠ)ノ', 'red') + colored( '\nTo finish current task press F and ENTER', 'magenta')) #loop de atividade for i in range(cfg[state['cur']]): CICLE_SIZE = 60 cur_time = '' if cfg[state['cur']] - i < 10: cur_time = '0' + str(cfg[state['cur']] - i) else: cur_time = str(cfg[state['cur']] - i) time_left = '\rMinutes Left: ' + colored(cur_time, 'blue') stdout.write(time_left) #escrevendo #finalizador de tarefas if state['cur'] == 'task': s_i, s_o, s_e = select([stdin], [], [], CICLE_SIZE) #se for digitada qualquer coisa no input if s_i: return selection_screen(i + 1) stdout.flush() #atualizando if state['cur'] != 'task': sleep(CICLE_SIZE) # fim do timer if sound: for e in range(5): sound.play() sleep(0.5) sound.stop() selection_screen(0) #inicio do loop loopomodore()