示例#1
0
def modify_media_list(mrl,
                      media_list,
                      media_player,
                      shuffle=True,
                      append=False,
                      switch_current=False):
    '''For setting a new playlist to a vlc.MediaList, or appending to it.
    Shuffle is enabled by default.'''
    if not append:
        media_list_clear(media_list)

    if os.path.isdir(mrl):
        list_of_media = [
            vlc.Media(audio_file) for audio_file in audio_file_dir_walk(mrl)
        ]
    else:
        list_of_media = [vlc.Media(mrl)]

    for media in list_of_media:
        media_list.add_media(media)
    media_list_flatten(media_list)

    if shuffle:
        media_list_shuffle(media_list)

    if switch_current:
        media_player.play_item(list_of_media[0])
示例#2
0
    def nextSong( self, event=False ):
        self.curSong += 1

        info = self.songinfo[self.curSong]
        if self.player.is_playing():
            self.player.stop()
        self.player = vlc.MediaPlayer()
        self.player.audio_set_volume( self.curVolume )
        self.event_manager = self.player.event_manager()
        self.event_manager.event_attach(vlc.EventType.MediaPlayerEndReached,      self.nextSong)
        info = self.songinfo[self.curSong]
        self.displaysongs.append(info)
        self.song = info['title']
        if info['localpath']:
            print "Playing song from cache"
            self.player.set_media(vlc.Media(info['localpath']))
        else:
            print "Playing song live from URL"
            self.player.set_media(vlc.Media(info['url']))
        self.playing = True
        self.player.play()
        self.songChangeCallBack()
        self.player.audio_set_delay( 2500 )
        print self.player.audio_get_delay()
        
        if self.curSong >= len(self.songinfo)-1:
            self.addSongs()
        self.songCount += 1
        if self.songCount >= 15:
            self.songCount = 0
            self.auth(self.settings['username'], self.settings['password'])
示例#3
0
文件: main.py 项目: mecubey/Pyplayer
def next_audio():
    """
    next_audio description
    checks if shuffle is on -> skips to  random audio file as next audio

    skips to next audio file normally
    """
    global default_shuffle
    media_object.stop()
    if (default_shuffle == False):
        try:
            media = vlc.Media(
                dir_name.get() + "/" +
                files_list[files_list.index(current_song.cget("text")) + 1])
            media_object.set_media(media)
            current_song.configure(
                text=files_list[files_list.index(current_song.cget("text")) +
                                1])
            media_object.play()
        except:
            media = vlc.Media(dir_name.get() + "/" + files_list[0])
            media_object.set_media(media)
            current_song.configure(text=files_list[0])
            media_object.play()
    else:
        random_audio = random.choice(new_file_list)
        media = vlc.Media(dir_name.get() + "/" + random_audio)
        current_song.configure(text=random_audio)
        media_object.set_media(media)
        media_object.play()
示例#4
0
 def channel_back(self):
     if self.index <= 0:
         self.index = len(self.med) - 1
         self.media_player.set_media(
             vlc.Media(self.path + self.med[self.index]))
         self.media_player.play()
     else:
         self.index -= 1
         self.media_player.set_media(
             vlc.Media(self.path + self.med[self.index]))
         self.media_player.play()
示例#5
0
 def channel_forth(self):
     if self.index < len(self.med) - 1:
         self.index += 1
         self.media_player.set_media(
             vlc.Media(self.path + self.med[self.index]))
         self.media_player.play()
     else:
         self.index = 0
         self.media_player.set_media(
             vlc.Media(self.path + self.med[self.index]))
         self.media_player.play()
示例#6
0
 def play(self, index):
     path_t = os.path.join(self.path, self._album, self._tracks[index])
     media = vlc.Media(path_t)
     self.player.set_media(media)
     self.player.play()
     self._index = index
     self._album_playing = self._album
def playSong(URL):
    global timeout

    say(songName + " by " + songAuthor)

    #tell what movie or tv show the music is from
    fromMoviesOrTV = songName.split("(")
    print("fropm,mpooves ior tv:" + str(fromMoviesOrTV))
    for i in fromMoviesOrTV:
        whatFrom = i.split(")")
        print(str(whatFrom) )

        print("length of whatfrom:" + str(len(whatFrom)))
        if(len(whatFrom) > 1):
            say("from " + str(whatFrom[0]))


    URL = "https:"+URL
    #get the audio link
    # errors were returned based on certificate checking
    #video = pafy.new(URL)
    video = pafy.new(URL, ydl_opts={'nocheckcertificate': True, 'buffer-size':3600})
    audio = video.getbestaudio()
    #audio = video.getbest()
    playurl = audio.url

    #play the audio
    Media = vlc.Media(playurl)
    Media.get_mrl()
    player.set_media(Media)
    player.play()
    time.sleep(1.5)
    timeout = float(player.get_length() / 1000)
示例#8
0
    def __init__(self, media_path, initial_volume=0, *args, **kwargs):
        VolumeFaderMixin.__init__(self, initial_volume=initial_volume)
        MediaPlayerMixin.__init__(self)

        self.player = None
        self.track = vlc.Media(media_path)
        self.track.parse()
示例#9
0
    def __play(self):  # 실질적인 재생을 맡는 함수
        # 큐에 있는 곡 전부 다 없어질 때까지 반복
        import os

        while not self.queue.is_empty():
            item = self.queue.dequeue()
            if item.downloaded:
                print("%s 재생을 시작합니다." % item.name)
                self.player.set_media(vlc.Media(item.file))
                self.player.play()
                self.condition.wait(item.length)
                os.remove(item.file)
            else:
                for i in range(5):
                    print("%s 다운로드에 실패했습니다." % item.name)
                    print("남은 재시도 횟수 : %s" % (5 - i))
                    time.sleep(5)
                    if item.downloaded:
                        self.queue.insert(0, item)
                        break
                else:
                    self.queue.append(item)
                    print("%s 노래를 건너뜁니다." % item.name)
        print("대기열에 재생할 곡이 더 이상 없습니다.")
        self.__playing = False
示例#10
0
    def open_audio(self, file):
        if not has_vlc:
            return False
        self.media = None
        self.player = None
        if file is None:
            self.setVisible(False)
            return
        self.file = file
        media = vlc.Media(file)
        media.parse_with_options(parse_flag=vlc.MediaParseFlag.local,timeout=100000)
        
        self.slider.setMaximum(100)
        self.slider.setValue(0)

        t = QTime.fromMSecsSinceStartOfDay(media.get_duration())
        self.time.setMaximumTime(t)
        self.max_time.setText(t.toString("h:m:s"))

        self.media = media
        self.player = media.player_new_from_media()
        
        self.set_enabled_utils()
        self.setVisible()

        return self.is_valid()
示例#11
0
def playfile(number):
    global playing
    global pause
    media = '/media/pi/MP3USB/radioshows/' + files[number - 1]

    if pause is True and playing == number:
        player.set_pause(0)
        print("resume:")
        pause = False
        return

    elif playing == number:
        player.set_pause(1)
        print("paused:")
        pause = True

    elif playing != number:
        player.set_media(vlc.Media(media))
        player.play()
        pause = False
        print("playing:")

    playing = number
    print(playing)
    return playing
示例#12
0
    def play(self, song=None):
        self.seeking = False

        if self.playlist.is_empty():
            return

        if str(self.media_player.get_state()) == 'State.Paused':
            self.media_player.set_pause(0)
        else:
            song_artist, song_name, self.play_index = (song.artist, song.name, song.song_id) if song \
                else (playlist.songs[self.play_index].artist, playlist.songs[self.play_index].name, self.play_index)

            song_path = '../Music/' + ' - '.join(
                (song_artist, song_name)) + '.mp3'

            media = vlc.Media(song_path)

            self.media_player.set_media(media)
            self.media_player.play()
            self.now_playing_song = self.playlist.songs[self.play_index]

            self.now_playing_label.set(' - '.join((song_artist, song_name)))

        length = self.now_playing_song.length
        current_timestep = self.media_player.get_time() // 1000
        self.progress_bar.config(to=length)
        self.progress_bar.after(1000, lambda: self.progress(current_timestep))
示例#13
0
 def OnOpen(self):
     if os.path.isfile("sch.txt"):
         pass
         print("found sch.txt")
         print("playing from this file instead")
     else:
         print("sch.txt not found")
         fullname = askdirectory(initialdir="/", title="Select Directory")
         if os.path.isdir(fullname):
             video_frmt = [
                 '.mp4', '.m4a', '.m4v', '.f4v', '.f4a', '.m4b', '.m4r',
                 '.f4b', '.mov', '.wmv', '.wma', '.asf', '.webm', '.flv',
                 '.avi', '.wav', '.mkv'
             ]
             mastr = []
             hold = []
             mastrw = []
             for dir in os.listdir(fullname):
                 dirpath = os.path.join(fullname, dir).replace("\\", "/")
                 for path, directories, files in os.walk(dirpath):
                     for filename in files:
                         name, ext = os.path.splitext(filename)
                         if ext in video_frmt:
                             hold.append(
                                 os.path.join(path,
                                              filename).replace("\\", "/"))
                         else:
                             pass
                 if len(hold):
                     mastr.append(hold)
                 else:
                     pass
                 hold = []
             while mastr:
                 randitem = choice(mastr)
                 if len(randitem):
                     mastrw.append(randitem.pop(0))
                 else:
                     mastr.remove(randitem)
             with open('sch.txt', 'w') as f:
                 for fullpath in mastrw:
                     f.write(fullpath + '\n')
             print("created sch.txt")
     with open("sch.txt") as flplpay:
         sch_list = flplpay.read().split('\n')
         for path_line in sch_list:
             self.media = vlc.Media(path_line)
             self.media_list.add_media(self.media)
     self.media_list_player = vlc.MediaListPlayer()
     self.media_list_player.set_media_list(self.media_list)
     print("Created MediaListPlayer")
     if platform.system() == 'Windows':
         self.media_list_player.get_media_player().set_hwnd(
             self.GetHandle())
     else:
         self.media_list_player.get_media_player().set_xwindow(
             self.GetHandle())
     self.OnPlay()
     self.volslider.set(
         self.media_list_player.get_media_player().audio_get_volume())
示例#14
0
 def test_tracks_get(self):
     self.assertTrue(os.path.exists(SAMPLE))
     m = vlc.Media(SAMPLE)
     m.parse()
     # Audiotrack is the second one
     audiotrack = list(m.tracks_get())[1]
     self.assertEqual(audiotrack.i_original_fourcc, 0x6134706d)
     self.assertEqual(m.get_duration(), 5568)
示例#15
0
def effectSelectionChanged(event):
    selection = lb_effects.curselection()
    media_player_effects.stop()
    if selection:
        current_effects_media = vlc.Media(
            os.path.join(effects_folder, event.widget.get(selection[0])))
        media_player_effects.set_media(current_effects_media)
        media_player_effects.play()
示例#16
0
    def set_current_song(self):
        try:
            song = Song.objects.earliest()
        except:
            return

        if not song:
            return

        self.player.set_media(vlc.Media(song.audio_url))
示例#17
0
 def play_song(self, song_uri):
     """Play a given song_uri."""
     # TODO: This is a decent stub, but I need to start work on encapsulating the garbage VLC interface.
     media = vlc.Media(song_uri)
     self.mp.set_media(media)
     playing = self.mp.play()
     if playing == -1:
         raise UnspecifiedVLCError(
             "Encountered error while playing uri '%s', check the logs?" %
             (song_uri, ))
示例#18
0
 def __init__(self, src, **kwargs):
     import vlc
     global _vlc_media_player
     super(VlcMusicPlayer, self).__init__(**kwargs)
     if not _vlc_media_player:
         _vlc_media_player = vlc.MediaPlayer()
     self.media_player = _vlc_media_player
     self.src = src
     self.media_player.set_media(vlc.Media(src))
     self.played = False
示例#19
0
def cam_viewer_start():
  logging.info("CamViewer started")
  vlc_instance = vlc.Instance('--no-xlib')
  player = vlc_instance.media_player_new() 
  player.set_fullscreen(True)
  media = vlc.Media(cfg['CAMERA_URL']) 
  player.set_media(media) 
  player.video_set_scale(cfg['CAMERA_ZOOM'])
  player.play()
  return player
示例#20
0
文件: radio.py 项目: RickHutten/Radio
    def __init__(self, name: str, freq: float, file_name: str):
        if not os.path.exists(file_name):
            file_name = self.find_file_path(file_name)

        self.name: str = name
        self.frequency: float = freq
        self.file_name: str = file_name
        self.media: vlc.Media = vlc.Media(file_name)
        self.length: float = self._get_length()
        self.station_offset: int = random.randrange(0, self.length)
示例#21
0
 def test_tracks_get(self):
     self.assertTrue(os.path.exists(SAMPLE))
     m = vlc.Media(SAMPLE)
     m.parse()
     # Audiotrack is the second one
     audiotrack = list(m.tracks_get())[1]
     self.assertEqual(audiotrack.language, b"eng")
     self.assertEqual(audiotrack.description, b"Stereo")
     self.assertEqual(audiotrack.bitrate, 83051)
     self.assertEqual(m.get_duration(), 5568)
示例#22
0
    def _get_vlc_media(self, uri):
        """
        Creates a vlc_media object with the correct sout.

        :param str uri: URI to create media object with.
        :return: vlc.Media
        """
        cmd = VLCTools.generate_sout(self._server.clients, self._port)
        print cmd
        return vlc.Media(uri, cmd)
示例#23
0
文件: main.py 项目: mecubey/Pyplayer
def previous_audio():
    """
    previous_audio description
    goes back to previous audiofile in list
    """
    media_object.stop()
    try:
        media = vlc.Media(
            dir_name.get() + "/" +
            files_list[files_list.index(current_song.cget("text")) - 1])
        media_object.set_media(media)
        current_song.configure(
            text=files_list[files_list.index(current_song.cget("text")) - 1])
        media_object.play()
    except:
        media = vlc.Media(dir_name.get() + "/" + files_list[0])
        media_object.set_media(media)
        current_song.configure(
            text=files_list[files_list.index(current_song.cget("text")) - 1])
        media_object.play()
示例#24
0
    def __init__(self, *args, **kwargs):
        super(SoundPlayer, self).__init__(*args, **kwargs)

        initial_master_volume = self.node_params.get('master_volume', None)
        master_volume_mixer = self.node_params.get('mixer', '')
        default_initial_volume = self.node_params.get('default_volume', 100)

        player = self.node_params.get('player', 'pyglet')
        if player == 'vlc':
            self.sound_player = self.vlc_play_sound
        elif player == 'pyglet':
            self.sound_player = self.pyglet_play_sound
            self.pyglet_players = []
            loop = LoopingCall(self.pyglet_loop)
            loop.start(1 / 30)
        else:
            raise ValueError(
                "Bad player value ({}). Possible values are vlc or "
                "pyglet.".format(player))

        try:
            self.master_volume = MasterVolume(
                initial_volume=initial_master_volume,
                mixer=master_volume_mixer,
            )
        except Exception:
            logger.exception()
            logger.warning(
                "Unable to initialize the master volume controller. Further "
                "actions on the master volume will be ignored.")
            self.master_volume = None

        self.sounds = {}
        for sound in self.node_params.get('sounds', []):
            id_ = sound['id']
            path = sound['path']
            volume = sound.get('volume', default_initial_volume)

            if player == 'vlc':
                media = vlc.Media(path)
                media.parse()
                # / 1000 because we will be interested by the value in seconds
                duration = media.get_duration() / 1000
                self.sounds[id_] = {
                    'media': media,
                    'duration': duration,
                    'volume': volume,
                }
            else:
                media = pyglet.media.load(path, streaming=False)
                self.sounds[id_] = {
                    'media': media,
                    'volume': volume,
                }
示例#25
0
 def test_meta_get(self):
     self.assertTrue(os.path.exists(SAMPLE))
     m = vlc.Media(SAMPLE)
     m.parse()
     self.assertEqual(m.get_meta(vlc.Meta.Title), 'Title')
     self.assertEqual(m.get_meta(vlc.Meta.Artist), 'Artist')
     self.assertEqual(m.get_meta(vlc.Meta.Description), 'Comment')
     self.assertEqual(m.get_meta(vlc.Meta.Album), 'Album')
     self.assertEqual(m.get_meta(vlc.Meta.AlbumArtist), 'Album Artist')
     self.assertEqual(m.get_meta(vlc.Meta.Date), '2013')
     self.assertEqual(m.get_meta(vlc.Meta.Genre), 'Sample')
示例#26
0
 def play(self, url):
     self.status['text'] = 'Wait While Loading...'
     try:
         print('Wait While Loading')
         media = vlc.Media(url)
         self.player.set_media(media)
         self.player.play()
         print('playing')
         self.threading.Thread(target=self.duration).start()
     except Exception as e:
         self.status['text'] = "Error: " + str(e)
         print(e)
示例#27
0
    def AddTTSMessage(self, text):
        API = "https://streamlabs.com/polly/speak"
        PARAMS = {'text': text, 'voice':'Brian'}
        response = requests.post(url = API, data = PARAMS).json()
        logging.debug(response)
        if (response['success'] == True):
            audioUrl = response['speak_url']
            self.tts_player.media_list.add_media(vlc.Media(audioUrl))
            if (self.tts_enabled == True):
                self.tts_player.media_list_player.play()

        else:
            logging.critical("Error in TTS Message, you may be rate limited")
示例#28
0
文件: main.py 项目: mecubey/Pyplayer
def set_play_media():
    """
    set_play_media description
    checks if repeat is on -> plays same audiofile again
    checks if shuffle is on -> plays random audio file using random-module

    plays next audio file normally
    """

    global default_shuffle
    countdown_thread = threading.Thread(target=wait_test)
    media_object.stop()

    if (default_repeat == False):
        if (default_shuffle == False):
            try:
                media = vlc.Media(dir_name.get() + "/" + new_file_list[
                    new_file_list.index(current_song.cget("text")) + 1])
                current_song.configure(text=new_file_list[
                    new_file_list.index(current_song.cget("text")) + 1])
                media_object.set_media(media)
                media_object.play()
            except:
                media = vlc.Media(dir_name.get() + "/" + new_file_list[0])
                current_song.configure(text=new_file_list[0])
                media_object.set_media(media)
                media_object.play()
        else:
            random_audio = random.choice(new_file_list)
            media = vlc.Media(dir_name.get() + "/" + random_audio)
            current_song.configure(text=random_audio)
            media_object.set_media(media)
            media_object.play()
    else:
        media = vlc.Media(dir_name.get() + "/" + current_song.cget("text"))
        media_object.set_media(media)
        media_object.play()
    countdown_thread.start()
示例#29
0
        def play():
            if type == "stream":
                stream = pafy.new(media_url, gdata=False)
                try:
                    best_url = stream.getbestaudio().url
                except AttributeError:
                    best_url = stream.getbest().url
                media = vlc.Media(best_url)
                title = stream.title
            elif type == "file":
                media = vlc.Media(media_url)
                title = media_url

            player = vlc.MediaPlayer()
            player.audio_set_volume(volume)
            player.set_media(media)

            try:
                print(f"INFO -- Now playing: {title}")
                player.play()
            except:
                print("INFO -- Unable to play video...")
                sys.exit()
示例#30
0
def playaudio(key, file):

    # if player.set_pause(1):
    #     player.set_pause(0)
    #     print("resume")
    #
    state = True
    if event.key == key:
        track = vlc.Media('OLDRADIOSHOWS/' + file)
        print("Starting:" + file)
        player.set_media(track)
        player.play()
        state = True
    return state