コード例 #1
0
def play(station_id=-1):
    '''
        play a station and display it on LCD followed by '...'
    '''
    context['state'] = 'loading'

    playerList = context.get('playerList')
    if station_id == -1:
        station_id = context.get('current_station')
    else:
        context['current_station'] = station_id

    station = context.get('stations')[station_id]

    if playerList.is_playing():
        playerList.stop()

    print_lcd('%s...' % (station[0], ))

    if 'm3u' in station[1]:
        mediaList = vlc.MediaList([station[1]])
        print('MediaPlayerList')
    else:
        mediaList = vlc.MediaList()
        mediaList.add_media(station[1])
        print('MediaPlayer')

    playerList.set_media_list(mediaList)
    playerList.play()
コード例 #2
0
def song_player(param_db, param_sessionID, repeat, test):
    """
    Instantiate the media list player and its playlist.
    Playlist is created with one random song in it.
    :param param_db: The database object.
    :param param_sessionID: Current user's session ID.
    :param repeat: Flag for repeating a song which was previously played. If set to False, it will skip previously played songs.
    :param test: Flag for allowing console output. If set to False, it will not output messages to the console.
    """

    global media_list_player, playlist, db, sessionID, repeatFlag, testFlag

    db = param_db
    sessionID = param_sessionID
    repeatFlag = repeat
    testFlag = test

    playlist = vlc.MediaList()

    # Add a random song to the playlist.
    #   allSongs = [song['name'] for song in list(Tracklist.get_all_songs(db))]
    #  random_song = random.choice(allSongs)
    # path = os.path.relpath('./audio/tracks/' + random_song + '.mp3')
    # playlist.add_media(path)

    # Link playlist to media list player.
    media_list_player = vlc.MediaListPlayer()
    media_list_player.set_playback_mode(vlc.PlaybackMode.loop)
    media_list_player.set_media_list(playlist)

    # Add events for changing tracks.
    add_events()
コード例 #3
0
    def update_video(self):
        """Read list of files, convert to video time, and add video to queue.
        """
        window_start = self.parent.value('window_start')
        window_length = self.parent.value('window_length')
        d = self.parent.info.dataset

        try:
            videos, begsec, endsec = d.read_videos(window_start,
                                                   window_start + window_length)
        except OSError as er:
            lg.debug(er)
            self.idx_button.setText('NO VIDEO for this dataset')
            return
        except Exception as er:
            lg.debug(er)
            self.idx_button.setText(str(er))
            return

        lg.debug(f'Video: {begsec} - {endsec}')
        self.endsec = endsec
        videos = [str(v) for v in videos]  # make sure it's a str (not path)
        medialist = vlc.MediaList(videos)
        self.medialistplayer.set_media_list(medialist)

        self.cnt_video = 0
        self.n_video = len(videos)

        self.t = QTimer()
        self.t.timeout.connect(self.check_if_finished)
        self.t.start(100)

        self.medialistplayer.play()
        self.mediaplayer.set_time(int(begsec * 1000))
コード例 #4
0
    def set_playlist(self, playlist):
        self.playlist_index = -1
        self.playlist = playlist
        self.pause()

        media_list = vlc.MediaList()
        for song in playlist:
            media_list.add_media(song.path)

        self.player.set_media_list(media_list)
コード例 #5
0
    def __init__(self, target):
        self.target = target
        self.instance = vlc.Instance()

        self.medialist = vlc.MediaList()
        self.player = vlc.MediaListPlayer(self.instance)
        self.player.set_media_player(self.instance.media_player_new())
        self.player.set_media_list(self.medialist)

        self.mrl_map = {}
コード例 #6
0
 def __init__(self, parent, title=None):
     Tk.Frame.__init__(self, parent)
     self.parent = parent
     if title == None:
         title = "tk_vlc"
     self.parent.title(title)
     menubar = Tk.Menu(self.parent)
     self.parent.config(menu=menubar)
     fileMenu = Tk.Menu(menubar)
     fileMenu.add_command(label="Open", underline=0, command=self.OnOpen)
     fileMenu.add_command(label="Exit", underline=1, command=_quit)
     menubar.add_cascade(label="File", menu=fileMenu)
     self.media_list_player = None
     self.videopanel = ttk.Frame(self.parent)
     self.canvas = Tk.Canvas(self.videopanel).pack(fill=Tk.BOTH, expand=1)
     self.videopanel.pack(fill=Tk.BOTH, expand=1)
     ctrlpanel = ttk.Frame(self.parent)
     pause = ttk.Button(ctrlpanel, text="Pause", command=self.OnPause)
     play = ttk.Button(ctrlpanel, text="Play", command=self.OnPlay)
     stop = ttk.Button(ctrlpanel, text="Stop", command=self.OnStop)
     next = ttk.Button(ctrlpanel, text="Next", command=self.OnSkip)
     volume = ttk.Button(ctrlpanel, text="Volume", command=self.OnSetVolume)
     pause.pack(side=Tk.LEFT)
     play.pack(side=Tk.LEFT)
     stop.pack(side=Tk.LEFT)
     next.pack(side=Tk.LEFT)
     volume.pack(side=Tk.LEFT)
     self.volume_var = Tk.IntVar()
     self.volslider = Tk.Scale(ctrlpanel,
                               variable=self.volume_var,
                               command=self.volume_sel,
                               from_=0,
                               to=100,
                               orient=Tk.HORIZONTAL,
                               length=100)
     self.volslider.pack(side=Tk.LEFT)
     ctrlpanel.pack(side=Tk.BOTTOM)
     ctrlpanel2 = ttk.Frame(self.parent)
     self.scale_var = Tk.DoubleVar()
     self.timeslider_last_val = ""
     self.timeslider = Tk.Scale(ctrlpanel2,
                                variable=self.scale_var,
                                command=self.scale_sel,
                                from_=0,
                                to=1000,
                                orient=Tk.HORIZONTAL,
                                length=500)
     self.timeslider.pack(side=Tk.BOTTOM, fill=Tk.X, expand=1)
     self.timeslider_last_update = time.time()
     ctrlpanel2.pack(side=Tk.BOTTOM, fill=Tk.X)
     self.media_list = vlc.MediaList()
     self.timer = ttkTimer(self.OnTimer, 1.0)
     self.timer.start()
     self.parent.update()
コード例 #7
0
def main():
    #print( "main" )
    global inputLen, prevInputLen, mediaList, mediaListPlayer, mediaPlayer, position

    # Wait the system to boot up correctly
    #time.sleep(10)

    # Open video player
    try:
        print(" load the video ")
        # create a list of media
        mediaList = vlc.MediaList()
        # and add itmes to it
        mediaList.add_media(pathToVideoFile1)
        mediaList.add_media(pathToVideoFile2)
        # create the player which will play that list
        mediaListPlayer = vlc.MediaListPlayer()
        mediaListPlayer.set_media_list(mediaList)
    except Exception as exc:
        print("something went wrong {}".format(exc))
        quit()

    mediaListPlayer.set_playback_mode(vlc.PlaybackMode.loop)
    mediaListPlayer.play_item(mediaList.item_at_index(0))
    mediaPlayer = mediaListPlayer.get_media_player()
    mediaPlayer.toggle_fullscreen()

    inputLen = getInputDevices()
    prevInputLen = inputLen

    # Main loop
    while True:
        # check is someone plugged in a mouse or a keyboard
        if (areThereNewInputsDevices()):
            # new input devices have been found
            # script must be stopped in order
            # to let space for the user to work
            # with the Pi

            # quit video player
            videoPlayer.stop(
            )  # will exit current vlc window (desktop will be visible)

            # kill all alive thread
            # find a way to do this

            # exit the python script
            quit()
        else:
            #print("position {}".format(position) )
            #if position >= 0.99:
            #	videoPlayer.set_position( 0.0 )
            time.sleep(0.1)
コード例 #8
0
 def createMediaList(self):
     self.mediaListPlayer.stop()
     # Get And Shuffle Tracks
     self.playlist = glob.glob('.\\Lib\*')
     random.shuffle(self.playlist)
     # Print Trax
     for song in self.playlist:
         print (song)
     # Set Media List
     self.mediaList = vlc.MediaList(self.playlist)
     self.mediaListPlayer.set_media_list(self.mediaList)
     self.mediaListPlayer.play()
コード例 #9
0
    def set(self, id, credentials):
        self.mrl_map = {}
        media = self._build_media(id, credentials)

        # Create new list
        self.medialist = vlc.MediaList()
        self.player.stop()
        self.player.set_media_list(self.medialist)

        self.medialist.lock()
        for media_item in media:
            self.medialist.add_media(media_item)
        self.medialist.unlock()
コード例 #10
0
def cb_switch_all_album(channel):
    global artist
    global current_mode
    lp.stop()
    if artist != "Unknown" and current_mode == "ALL":
        artist = re.sub("(!|\$|#|&|\"|\'|\(|\)|\||<|>|`|\\\|;)", r"\\\1",
                        artist)
        print "Creating", artist, "playlist."
        os.system('sudo -u no3z beet play %s' % artist)
        shuffle_m3u(in_query_m3u, out_query_m3u)
        ml = vlc.MediaList()
        ml.add_media(out_query_m3u)
        lp.set_media_list(ml)
        lp.play()
        current_mode = "ARTIST"
    elif current_mode == "ARTIST":
        print "Switch to all"
        shuffle_m3u(IN_PLAYLIST, PLAYLIST)
        ml = vlc.MediaList()
        ml.add_media(PLAYLIST)
        lp.set_media_list(ml)
        lp.play()
        current_mode = "ALL"
コード例 #11
0
ファイル: freezer.py プロジェクト: robertkarl/freezer
def play_album(thefreezer, args):
    outfname, _ = thefreezer.zip_album(args.album_to_zip)
    # -o forces overwrite lol
    subprocess.run(["unzip", "-qq", "-o", outfname, "-d", FREEZER_TMP_DIR])
    filelist = sorted(glob.glob(outfname[:-4] + "/*.mp3"))
    print(os.path.basename(outfname)[:-4])
    for f in filelist:
        print(os.path.basename(f))
    media_list = vlc.MediaList(filelist)
    player = vlc.MediaListPlayer()
    player.set_media_list(media_list)
    player.play()
    # Dump user into a PDB session. Songs can be controlled from there in
    # lieu of a real interface of some kind.
    l = loop_handler(player)
    l.go()
コード例 #12
0
ファイル: player.py プロジェクト: sorrowless/piplay
 def __init__(self, statusCallback=None):
     self.logger = logging.getLogger(__name__)
     self.path = None
     self.pathdict = {}
     self.player = None
     self.trackstatus = statusCallback  # We want to notify only from Manager
     try:
         self._list = vlc.MediaList()
         self._player = vlc.MediaPlayer()
         self.player = vlc.MediaListPlayer()
         self.player.set_media_player(self._player)
         self.player.set_media_list(self._list)
         self.player.event_manager().event_attach(
             vlc.EventType.MediaListPlayerNextItemSet,
             self.playInfo
         )
     except NameError:
         self.logger.error("Can't initialize vlc player instance. Missing \
                           libvlc in system?",
                           "Try to install VLC player")
コード例 #13
0
    def _prepare(self, url):
        def _cb(event):
            print "Event: ", event.type, event.u

        self._media_list_player = vlc.MediaListPlayer()
        self.player = vlc.MediaPlayer()
        self._media_list_player.set_media_player(self.player)

        media_list_player_event_manager = self._media_list_player.event_manager(
        )
        media_list_player_event_manager.event_attach(
            vlc.EventType.MediaListPlayerNextItemSet, _cb)

        media_list_player_event_manager = self.player.event_manager()
        media_list_player_event_manager.event_attach(
            vlc.EventType.MediaPlayerEndReached, _cb)
        media_list_player_event_manager.event_attach(
            vlc.EventType.MediaPlayerMediaChanged, _cb)

        media_list = vlc.MediaList()

        media_list.add_media(url)
        self._media_list_player.set_media_list(media_list)
        self.player.audio_set_volume(self.current_vol)
コード例 #14
0
GPIO.add_event_detect(NEXT, GPIO.FALLING, callback=cb_next, bouncetime=300)
GPIO.add_event_detect(PREV, GPIO.FALLING, callback=cb_prev, bouncetime=300)
GPIO.add_event_detect(CHANGE,
                      GPIO.FALLING,
                      callback=cb_switch_all_album,
                      bouncetime=300)

i = vlc.Instance('-A', 'alsa,none' '--alsa-audio-device default')
p = vlc.MediaPlayer()
lp = vlc.MediaListPlayer()
lp.set_media_player(p)

mp_ev = p.event_manager()
mp_ev.event_attach(vlc.EventType.MediaPlayerMediaChanged, mediachanged, p)

ml = vlc.MediaList()

shuffle_m3u(IN_PLAYLIST, PLAYLIST)

ml.add_media(PLAYLIST)
lp.set_media_list(ml)
lp.play()

try:
    while True:
        time.sleep(1)

except KeyboardInterrupt:
    GPIO.cleanup()  # clean up GPIO on CTRL+C exit
GPIO.cleanup()  # clean up GPIO on normal exit
コード例 #15
0
ファイル: test.py プロジェクト: bradlindblad/biblepi
 def test_wrapper_medialist(self):
     mrl1 = "/tmp/foo.avi"
     mrl2 = "/tmp/bar.avi"
     l = vlc.MediaList([mrl1, mrl2])
     self.assertEqual(l[1].get_mrl(), "file://" + mrl2)
コード例 #16
0
ファイル: radio.py プロジェクト: RickHutten/Radio
 def _load_media(player: vlc.MediaListPlayer, media: vlc.Media):
     """Loads the media to the MediaListPlayer"""
     ml: vlc.MediaList = vlc.MediaList()
     ml.add_media(media)
     player.stop()
     player.set_media_list(ml)
コード例 #17
0
def returnmessage(message, sender_id):
    """
    Act accordingly based on the action asked by user

    :param message: action asked by user
    :param sender_id: sender id
    :return message: text message to send
    :return message1: flag for image send
    """
    # flush the std output
    sys.stdout.flush()

    bkmessage = message
    message = message.split(' ')

    # contant value saved in the variables
    mess = 'Sorry ask again'
    mess1 = None
    message = [i.lower() for i in message]
    print "sender id is ", sender_id
    if 'song' in message:  # for playing song related to artist and album
        # check for the playlist for specific artist
        if 'artist' in message:

            # check if the song is playing
            # if player is in play status,  stop the song and play the new song based on artist playlist
            if mlplayer.is_playing():
                mlplayer.stop()
            # read the csv file in which the songs and artist and album names are saved
            try:
                df = pd.read_csv('songs.csv')
            except Exception:
                mess = 'invalid csv file'

                return mess, mess1
            try:
                df1 = df.set_index('artist')
                of_index = message.index('artist')
                artist_name = message[of_index + 1]
                mess = artist_name
                artist_namelist = list(df.loc[:]['artist'])

                # check for the artist name in list of artists
                if artist_name in artist_namelist:
                    # create a playlist of songs for speicific artist
                    artist_songs = []
                    artist_songlist = list(df1.get_value(artist_name, 'songs'))
                    for i in artist_songlist:
                        new1 = address + i
                        artist_songs.append(new1)

                    # python-vlc plugin used to play the song
                    medialist = vlc.MediaList(artist_songs)
                    mlplayer.set_media_list(medialist)
                    mlplayer.set_media_player(pl)
                    mlplayer.play()
                    mess = 'Playing list song'

                else:
                    mess = "Sorry, artist is not available"

            except Exception:
                mess = 'something went wrong'

        if 'album' in message:
            # check for the playlist for specific album
            if mlplayer.is_playing():
                mlplayer.stop()

            try:
                # read the csv file of songs
                df = pd.read_csv('songs.csv')
            except Exception:
                mess = 'invalid csv file'
                return mess, mess1

            try:
                df11 = df.set_index('album')
                of_index1 = message.index('album')
                album_name = message[of_index1 + 1]
                mess = album_name
                album_namelist = list(df.loc[:]['album'])
                mess = album_namelist[0]

                # check for album name in list
                if album_name in album_namelist:
                    # create a playlist for specific album name
                    album_songs = []
                    album_songlist = list(df11.get_value(album_name, 'songs'))
                    mess = 'in for loop'
                    mess = album_songlist[0]

                    for i in album_songlist:
                        new1 = address + i
                        album_songs.append(new1)

                    mess = album_songs[0]
                    medialist1 = vlc.MediaList(album_songs)
                    mlplayer.set_media_list(medialist1)
                    mlplayer.set_media_player(pl)
                    mlplayer.play()
                    mess = 'Playing album list song'

                else:
                    mess = "Sorry, album is not available"

            except Exception:
                mess = 'something wrong album is performed'

    elif 'next' in message:  # for next song
        if mlplayer.is_playing():
            # play the next song in playlist
            mlplayer.next()
            mess = 'playing the next song'

        else:
            mess = 'No song is playing yet'

    elif 'previous' in message:  # for previous song
        if mlplayer.is_playing():
            # play the previous song in playlist
            mlplayer.previous()
            mess = 'playing the previous song'

        else:
            mess = 'previous song is not performed'

    elif 'pause' in message:  # for pausing song
        if mlplayer.is_playing():
            # pause the current song
            mlplayer.pause()
            mess = 'pausing the song'

        else:
            mess = 'pausing song is not performed'

    elif 'title' in message or 'name' in message:  # title of song
        if mlplayer.is_playing():
            # get the title of the current song
            media = pl.get_media()
            title_song = media.get_meta(vlc.Meta.Title)
            mess = title_song

        else:
            mess = 'no song is played yet'

    elif 'play' in message:  # play the song
        if mlplayer.is_playing():
            mess = 'already playing'

        else:
            mlplayer.play()
            mess = 'Playing song'

    elif 'stop' in message:  # stop the song
        if mlplayer.is_playing():
            mlplayer.stop()
            mess = 'Stopping the recent song'

        else:
            mess = 'No song is played yet'

    elif 'volume' in message:  # increase or decrease the volume of song
        if 'increase' in message:
            try:
                if mlplayer.is_playing():
                    # increase the volume of song by 10
                    print str(pl.audio_get_volume())
                    mess = '\nCurrent volume is  ' + str(pl.audio_get_volume())
                    volume = pl.audio_get_volume() + 10
                    print volume
                    if volume > 100:
                        mess = mess + '\n\nWarning:--  Volume above 100 may cause problem\n\n'
                    pl.audio_set_volume(volume)
                    mess = mess + '\nVolume increased to value  ' + str(volume)

            except Exception:
                mess = mess + '\n  Error:--- Increased volume is not performed\n'

        elif 'decrease' in message:
            try:
                if mlplayer.is_playing():
                    # decrease the volume of song by 10
                    mess = '\nCurrent volume is  ' + str(pl.audio_get_volume())
                    volume = pl.audio_get_volume() - 10
                    if volume > 100:
                        mess = mess + '\n\nWarning:--  Volume above 100 may cause problem\n\n'
                pl.audio_set_volume(volume)
                mess = mess + '\nVolume decreased to value  ' + str(volume)
            except Exception:
                mess = mess + '\n   Error:--- Decreased volume is not performed\n'

    elif 'change' in message:  # change the volume of song to any number
        try:
            to_index = message.index('to')
            if mlplayer.is_playing():
                data_vol_index = int(message[to_index + 1])
                print data_vol_index
                pl.audio_set_volume(data_vol_index)

                # warn user for max volume
                if data_vol_index > 100:
                    mess = "Warning:-- Volume above 100 may cause problem \
                            ..\n\n Changed the volume to %d " % (
                        data_vol_index)
        except Exception:
            print "Error:-- Changing volume cannot ber performed"

    elif 'time' in message and len(
            message) < 5:  # for asking time related info.
        mess = datetime.datetime.now().strftime('%I %M  %p %d %B %Y %A ')

    elif 'morning' in message or 'afternoon' in message or 'night' in message or 'evening' in message or 'noon' in message:  # greeting
        # Check for reminders for the user
        current_hour = datetime.datetime.now().hour
        current_greeting = check_time(current_hour)

        # return the current greeting to the user
        mess = 'Hey its ' + current_greeting[5:] + ' ,  ' + current_greeting

        # check for reminders for the current day
        reminders = reminder_details(current_greeting)
        if reminders:
            mess = 'Your reminder for todays is :--\n'

        for reminder in reminders:
            mess = mess + ' ' + reminder + '\n'

        else:
            mess = 'No reminder for today'

    elif 'hey' in message or 'hi' in message or 'hello' in message:  # greeting to user
        # regular greetings to the user
        greet_message = random.choice([
            'Hi,  good to see you', 'Hello,  good to see you',
            'Hey,   nice to see you'
        ])
        mess = greet_message + ' ' + u'\U0001f600'.encode('utf8')

    elif 'die' in message:  # rolling a die
        # roll a die and generate the number between 0 and 6
        mess = random.randint(0, 7)

    elif 'flip' in message and 'coin' in message:  # flip a coin
        mess = u'\U0001F604'

    elif 'you' in message or 'your' in message or 'yourself' in message or 'yourselves' in message:  # assistant info
        # get the assistant informations
        if 'are' in message or 'know' in message or 'explain' in message or 'name' in message:
            mess = 'I am your Pi Assistant, How can I help You'

    elif 'date' in message and len(message) <= 5:

        if 'tomorrow' in message:
            tomorrow = datetime.date.today() + datetime.timedelta(days=1)
            mess = tomorrow.strftime("%B %d %Y %A")

        elif 'yesterday' in message:
            yesterday = datetime.date.today() - datetime.timedelta(days=1)
            mess = yesterday.strftime("%B %d %Y %A")

        else:
            today = datetime.date.today()
            mess = today.strftime("%B %d %Y %A")

    elif 'weather' in message:  # weather informations
        # check for weather for any city using pyown weather spi
        placesinfo = bkmessage[11:].upper()
        mess = weatherinfo(placesinfo)

    elif 'today' in message and 'reminder' in message or 'todays' in message:  # check for greetings
        # check for greetings
        dateq = 'good morning'
        reminders = greetings(dateq)
        if reminders:
            mess = 'Your reminder for todays is :--\n'
            for reminder in reminders:
                mess = mess + ' ' + reminder + '\n'
        else:
            mess = 'No reminder for today'

    elif 'camera' in message:  # took a picture though camera
        try:
            # capture a image and upload it to cloud/git
            images_name = datetime.datetime.now().strftime('%I%M%S%p')
            images_name = images_name + '.jpeg'

            # command to capture image
            cmd = 'fswebcam -r 1920x1080 --set brightness=50%  '
            cmd = cmd + images_name
            print 'cmd is ' + str(cmd)
            os.system(cmd)

            # upload pic to git
            os.system('git add -A')
            os.system("git commit -m 'latest comit' ")
            os.system('git push  -f origin master')

            imageslink = github_link + images_name + '?raw=true'
            print imageslink
            mess = imageslink
            images.append(mess)
            mess = 'Images is captured\n\n The Captured image is at location:--' + imageslink

        except Exception:
            mess = 'no image available'

    elif 'capture' in message:
        # capturing a images
        if 'image' in message:
            lastimages = images[-1]
            mess = lastimages
        mess1 = 'images'

    elif 'video' in message:  # capturing a videos
        try:
            if len(videos) >= 1:

                lastvideo = videos[-1]
                mess = 'The Videos is captured\n and locations is at:-- \n\n '
                os.system('git add -A')
                os.system('git commit -m "videos commit" ')
                os.system('git push origin master')
                mess = lastvideo
            else:
                mess = 'Sorry, no video is captured'
        except Exception:
            mess = 'Sorry video is not available'

    elif 'video' in message:
        try:
            # capture a videos
            s = datetime.datetime.now().strftime('%I%M%S%p')
            s = s + '.mp4'
            cmd = 'ffmpeg -t 10  -f v4l2 -framerate 25 -video_size 640x800 -i /dev/video0   '
            cmd = cmd + s
            print 'cmd is ' + str(cmd)
            os.system(cmd)

            mess = ' Videos of 10 second is captured\n '
            imageslink1 = github_link + s + '?raw=true'
            videos.append(imageslink1)

        except Exception:
            mess = 'no video available'

    elif 'list' in message:  #  get a list of artist and album
        try:
            df1 = pd.read_csv('songs.csv')
        except Exception:
            mess = 'invalid csv file '
            return mess, mess1

        if 'artist' in message:
            artistlistname = set(list(df1.loc[:]['artist']))
            l1 = ''
            for j in artistlistname:
                l1 = l1 + j + '\n'
            mess = 'The available artist  are:--\n' + l1
            print artistlistname
        elif 'album' in message:
            albumlistname = set(list(df1.loc[:]['album']))
            l1 = ''
            for j in albumlistname:
                l1 = l1 + j + '\n'
            mess = 'The available album  are:--\n' + l1
            print albumlistname

    elif 'lights' in message or 'light' in message:  # light on/off
        if 'off' in message:
            # GPIO.output(26,  GPIO.LOW)
            mess = 'Lights off'
        elif 'on' in message:
            # GPIO.output(26,  GPIO.HIGH)
            mess = 'Lights on'

        elif 'fan' in message:
            if 'off' in message:
                #    GPIO.output(12,  GPIO.LOW)
                mess = 'fan off'
            elif 'on' in message:
                #   GPIO.output(12,  GPIO.HIGH)
                mess = 'fan on'

    elif 'remind' in message and 'me' in message:  # remind the messsage for user
        if not os.path.exists('remind.csv'):
            file('remind.csv', 'w').close()
            fdremind = pd.DataFrame(columns=[
                'date', 'month', 'time_info_data', 'time_info_min',
                'time_info_time', 'reminder'
            ])
            fdremind.to_csv('remind.csv', index=False)

        try:
            remindcsv = pd.read_csv('remind.csv')
        except Exception:
            mess = 'Invalid remind csv file'
            return mess, mess1

###########################   remind module   ###########################################################
#remind me <message_data> at  4 pm dec 31
#remind me <message_data> at 4 pm dec
#remind me <message_data> at 4 dec 31
#remind me <message_data> at 4 pm 31

    elif 'remind' in message and 'me' in message:
        if not os.path.exists('remind.csv'):
            file('remind.csv', 'w').close()
            fdremind = pd.DataFrame(columns=[
                'date', 'month', 'time_info_data', 'time_info_min',
                'time_info_time', 'reminder'
            ])
            fdremind.to_csv('remind.csv', index=False)

        try:
            remindcsv = pd.read_csv('remind.csv')
        except Exception:
            mess = 'Invalid remind csv file'
            return mess, mess1

        if len(message) == 2:
            mess = 'Invalid format\n\nremind me < message data> at < time >  < date>        \n'
            return mess, mess1

        elif 'at' in message:
            start = message.index('me')
            stop = message.index('at')
            if (stop - start) <= 1:
                mess = 'No message  received'
            else:
                timedata_min = 0
                count = 0
                message_data = message[start + 1:stop]
                message1 = message[stop + 1:len(message)]
                print message1
                print len(message1)
                message2 = filter(None, message1)
                print message2
                if len(message2) == 4:  # remidn me for call at dec 12 4 pm
                    for i in message2:
                        if i in valid_month:
                            print i
                            month = i
                            monthindex = message.index(i)
                            count = 1
                    if count == 0:
                        mess = 'Invalid month entered'
                        return mess, mess1
                    datemonth = message[monthindex - 1]
                    try:
                        date1 = int(datemonth)
                        # print date1
                        mess = date1
                        if date1 not in range(0, 32):
                            mess = 'Error:- Invalid Date entered'
                            return mess, mess1
                    except Exception:
                        try:
                            date1 = int(message[monthindex + 1])
                            # print date1
                            mess = date1
                            if date1 not in range(0, 32):
                                mess = 'Error:-- invalid date entered'
                                return mess, mess1
                        except Exception:
                            mess = '\nMonth is missing.please try again\n'
                            return mess, mess1

                    print 'date is {date}and month is {month}'.format(
                        date=date1, month=month)

                    if 'am' in message2:
                        amindex = message.index('am')
                        v_time = message[amindex]
                        amdata = message[amindex - 1]
                        try:
                            timedata = int(amdata)
                            print timedata
                        except Exception:
                            try:
                                timedata = int(message[amindex + 1])
                                print timedata
                            except Exception:
                                print 'Time is missing'
                                mess = 'Time is missing'
                                return mess, mess1
                    elif 'pm' in message2:
                        pmindex = message.index('pm')
                        v_time = message[pmindex]
                        pmdata = message[pmindex - 1]
                        try:
                            timedata = int(pmdata)
                            #mess = mess + pmdata1
                        except Exception:
                            try:
                                timedata = int(message[pmindex + 1])

                            except Exception:
                                print 'Time is missing'
                                mess = 'Time is missing'
                                return mess, mess1
                    else:
                        mess = 'Invalid time format'
                        return mess, mess1
                    mess = 'Message reminded for {date}{month}'.format(
                        date=date1, month=month)

                    if timedata not in range(
                            0, 13) or timedata_min not in range(0, 61):
                        mess = 'Invalid time and month'
                        return mess, mess1

                    else:  # remind me for call a freind at 4 30 pm dec 12
                        for i in message2:
                            if i in valid_month:
                                print i
                                month = i
                                monthindex = message.index(i)
                                count = 1
                        if count == 0:
                            mess = 'Invalid month entered'
                            return mess, mess1
                        datemonth = message[monthindex - 1]
                        try:
                            date1 = int(datemonth)
                            # print date1
                            mess = date1
                            if date1 not in range(0, 32):
                                mess = 'Error:- Invalid Date entered'
                                return mess, mess1
                        except Exception:
                            try:
                                date1 = int(message[monthindex + 1])
                                # print date1
                                mess = date1
                                if date1 not in range(0, 32):
                                    mess = 'Error:-- invalid date entered'
                                    return mess, mess1
                            except Exception:
                                mess = '\nMonth is missing.please try again\n'
                                return mess, mess1
                            print 'datetttttttttt is {date}and month is {month}'.format(
                                date=date1, month=month)

                            if 'am' in message2:
                                amindex = message.index('am')
                                v_time = message[amindex]
                                amdata = message[amindex - 1]
                                print 'amdata is {am}'.format(am=amdata)
                                try:
                                    timedata_min = int(amdata)
                                    timedata = int(message[amindex - 2])
                                    print timedata
                                    print timedata_min
                                except Exception:
                                    try:
                                        timedata = int(message[amindex + 1])
                                        timedata_min = int(message[amindex +
                                                                   2])
                                        print timedata
                                        print timedata_min
                                    except Exception:
                                        print 'Time is missing'
                                        mess = 'Time is missing'
                                        return mess, mess1
                            elif 'pm' in message2:
                                pmindex = message.index('pm')
                                v_time = message[pmindex]
                                pmdata = message[pmindex - 1]

                                try:

                                    timedata = int(message[pmindex - 2])
                                    print timedata
                                    print timedata_min
                                    #			mess = mess + pmdata1
                                except Exception:
                                    try:
                                        timedata = int(message[pmindex + 1])
                                        timedata_min = int(message[pmindex +
                                                                   2])

                                    except Exception:
                                        print 'Time is missing'
                                        mess = 'Time is missing'
                                        return mess, mess1
                            else:
                                mess = 'Invalid time format'
                                return mess, mess1
                            mess = 'Message reminded for {date}{month}'.format(
                                date=date1, month=month)
                            if timedata not in range(
                                    0, 13) or timedata_min not in range(0, 61):
                                mess = 'Invalid time and month'
                                return mess, mess1

                        remindcsv.loc[len(remindcsv) + 1] = [
                            date1, month, timedata, timedata_min, v_time,
                            message_data
                        ]
                        remindcsv.to_csv('remind.csv', index=False)

    return mess, mess1
コード例 #18
0
#!/usr/bin/env python 

import curses
import vlc
import time

active = 0

# Screen operations
stdscr = curses.initscr()
scrH = stdscr.getmaxyx()[0]
scrW = stdscr.getmaxyx()[1]

# VLC operations
files = vlc.MediaList()
player = vlc.MediaListPlayer()
player.set_media_list(files)

def init_scr():
    # Colors
    curses.start_color()
    curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_WHITE)
    curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK)
    curses.init_pair(3, curses.COLOR_CYAN, curses.COLOR_BLACK)
    curses.init_pair(4, curses.COLOR_RED, curses.COLOR_BLACK)

    # Add the title of the program
    title = "M_PLAYER"
    titleX = int(scrW/2) - int(len(title)/2)
    stdscr.addstr(0, titleX, title, curses.color_pair(1))
コード例 #19
0
leds = gpiozero.LEBboard(9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, pwm=True)

#setting which mp3 folder to use
if len(sys.argv) <=1:
    print('Please specify a folder') #for testing, won't be kept for non-lcd V1
    sys.exit(1)
folder = sys.argv[1]
files = glob.glob(folder+"/*.mp3")
if len(files) == 0:
    print('No mp3 files in directory', folder,'..exiting') #for testing, won't be kept for non-lcd V1
    sys.exit(1)

#vlc player setup
player = vlc.MediaPlayer()
#playlist setup
medialist = vlc.MediaList(files)
#linking it all
mlplayer = vlc.MediaListPlayer()
mlplayer.set_media_player(player)
mlplayer.set_media_list(medialist)

#defining the shutdown button
def shutdown():
    check_call(['sudo', 'poweroff'])
while True:
    if playpausebutton.is_pressed:
        if mlplayer.is_playing():
            mlplayer.pause() #pauses the music when the playpausebutton is pressed
        else:
            mlplayer.play() #plays the music when the playpausebutton is pressed
    elif stopbutton.is_pressed:
コード例 #20
0
        if (fnmatch.fnmatch(fullname, '*.mp3')
                or fnmatch.fnmatch(fullname, '*.flac')
                or fnmatch.fnmatch(fullname, '*.m4a')):
            flist.append(fullname)
alist = []
for root, dirs, files in os.walk(alarm_path, followlinks=True):
    for name in files:
        fullname = os.path.join(root, name)
        if (fnmatch.fnmatch(fullname, '*.mp3')
                or fnmatch.fnmatch(fullname, '*.flac')
                or fnmatch.fnmatch(fullname, '*.m4a')):
            alist.append(fullname)
instance = vlc.Instance()
player = instance.media_player_new()
station = vlc.MediaList([
    "http://network.absoluteradio.co.uk/core/audio/aacplus/live.pls?service=achq"
])
radio = vlc.Instance().media_list_player_new()
radio.set_media_list(station)
count = "-1"
alarm_time = "25:00"
ID = 0
normal_volume = 50
alarm_volume = 20
alarm_checker = view_db(alarm_time, ID)
alarm_time = alarm_checker[0]
ID = alarm_checker[1]
while True:
    show_clock(tm)
    if GPIO.input(10) == False:
        tm.show("STOP")
コード例 #21
0
ファイル: juke.py プロジェクト: techbelly/jukebox
def play_list(songs, player, current_song):
    player.stop()
    medialist = vlc.MediaList(songs)
    player.set_media_list(medialist)
    player.current_song = current_song
    player.play()
コード例 #22
0
ファイル: dqmusicbox.py プロジェクト: anhvanthe/dqmusicbox
    exit(1)
else:
    msg = 'Number of music files found: {}'.format(len(music_files))
    logger.info(msg)

try:
    player = vlc.MediaPlayer()
except:
    logger.error("Unable to create vlc.MediaPlayer() object. Exiting.")
    cleanup()
    sys.exit(1)
else:
    logger.info("vlc.MediaPlayer() object created.")

try:
    medialist = vlc.MediaList(music_files)
except:
    logger.error(
        "Unable to create vlc.MediaList(music_files) object. Exiting.")
    cleanup()
    sys.exit(1)
else:
    logger.info("vlc.MediaList(music_files) created.")

try:
    mlplayer = vlc.MediaListPlayer()
except:
    logger.error("Unable to create vlc.MediaListPlayer() oboject. Exiting.")
    cleanup()
    sys.exit(1)
else:
コード例 #23
0
ファイル: test.py プロジェクト: s772970282/python-vlc
 def test_wrapper_medialist(self):
     mrl1 = '/tmp/foo.avi'
     mrl2 = '/tmp/bar.avi'
     l = vlc.MediaList( [mrl1, mrl2] )
     self.assertEqual(l[1].get_mrl(), 'file://' + mrl2)
コード例 #24
0
def returnmessage(message,sender_id):
    sys.stdout.flush()
   
    bkmessage = message
    recess_id = sender_id
    message = message.split(' ')
    mess = 'Sorry ask again'
    mess1 = None
    message = [i.lower() for i in message]


    if 'song' in message:   # for playing song related to artist and album

        if 'artist' in message:
            if mlplayer.is_playing():
                mlplayer.stop()
            #df1 = df.set_index('artist')
	    try:
	        df = pd.read_csv('songs.csv')
            except:
		mess = 'invalid csv file'
		
		return mess,mess1
	    try:
                df1 = df.set_index('artist')
	        of_index = message.index('artist')
	        artist_name = message[of_index + 1]
	        mess = artist_name
                artist_namelist = list(df.loc[:]['artist'])
	        if artist_name in  artist_namelist:
	            artist_songs = []
		    artist_songlist = list(df1.get_value(artist_name,'songs'))
		    for i in artist_songlist:
		        new1 = songs_path + i
		        artist_songs.append(new1)
                
			
                
                    medialist = vlc.MediaList(artist_songs)
                    mlplayer.set_media_list(medialist)
                    mlplayer.set_media_player(pl)

	            mlplayer.play()
		    mess = 'Playing list song'
		    
		else:
		    mess = "Sorry,artist is not available"
		    

	    except:
	        mess = 'something wrong is performed'
		



	
        if 'album' in message:
            if mlplayer.is_playing():
                mlplayer.stop()
            
	    try:
	        df = pd.read_csv('songs.csv')
            except:
		mess = 'invalid csv file'
		
		return mess,mess1
	    try:
                df11 = df.set_index('album')
	        of_index1 = message.index('album')
	        album_name = message[of_index1 + 1]
	        mess = album_name
                album_namelist = list(df.loc[:]['album'])
		mess = album_namelist[0]
	        if album_name in  album_namelist:
	            album_songs = []
		    album_songlist = list(df11.get_value(album_name,'songs'))
		    mess = 'in for loop'
		    mess = album_songlist[0]
		    for i in album_songlist:
		        new1 = songs_path + i
		        album_songs.append(new1)
                    mess = album_songs[0]
                
			
                
                    medialist1 = vlc.MediaList(album_songs)
                    mlplayer.set_media_list(medialist1)
                    mlplayer.set_media_player(pl)

	            mlplayer.play()
		    mess = 'Playing album list song'
		    
		else:
		    mess = "Sorry,album is not available"
		    
	    except:
	        mess = 'something wrong album is performed'
		


        elif 'next' in message:			# for next song
	    if mlplayer.is_playing():
                mlplayer.next()
		mess = 'playing the next song'
		
	    else:
	        mess = 'No song is playing yet'
		


	elif 'previous' in message:               # for previous song
	    if mlplayer.is_playing():
                mlplayer.previous()
		mess = 'playing the previous song'
		
	    else:
		mess = 'previous song is not performed'   
		


	elif 'pause' in message:               # for pausing song
	    if mlplayer.is_playing():
	        mlplayer.pause()
		mess = 'pausing the song'
		
	    else:
	        mess = 'pausing song is not performed'
		
	elif 'title' in message or 'name' in message:   # title of song
	    if mlplayer.is_playing():
	        media = pl.get_media()
		title_song = media.get_meta(vlc.Meta.Title)
		mess = title_song
		
	    else:
		mess = 'no song is played yet'
		
	

    if 'play' in message:
        if mlplayer.is_playing():
            mess = 'already playing'
	    
	else:
	    mlplayer.play()
	    mess = 'Playing song'
	    
    elif 'stop' in message:
	if mlplayer.is_playing():
            mlplayer.stop()
	    mess = 'Stopping the recent song'
	    
	else:
	    mess = 'No song is played yet'
    
    elif 'volume' in message:
        if 'increase' in message:
	    try: 
	        if mlplayer.is_playing():
                 		 
		
		    print str(pl.audio_get_volume())
		    mess = '\nCurrent volume is  ' + str(pl.audio_get_volume())
		    volume = pl.audio_get_volume() + 10
		    print volume
		    if volume > 100:
		        mess = mess + '\n\nWarning:--  Volume above 100 may cause problem\n\n'
		    pl.audio_set_volume(volume)
		    mess = mess + '\nVolume increased to value  ' + str(volume)

	    except:
	        mess = mess +  '\n  Error:--- Increased volume is not performed\n'

	elif 'decrease' in message:
	    try:
	        if mlplayer.is_playing():

	            mess = '\nCurrent volume is  ' + str(pl.audio_get_volume())
		    volume = pl.audio_get_volume() - 10
		    if volume > 100:
		        mess = mess + '\n\nWarning:--  Volume above 100 may cause problem\n\n'
		    pl.audio_set_volume(volume)
		    mess = mess + '\nVolume decreased to value  ' + str(volume)
	    except:
	        mess = mess +  '\n   Error:--- Decreased volume is not performed\n' 


	elif 'change' in message:
	    try:
	        to_index = message.index('to')
	    	if mlplayer.is_playing():
		    data_vol_index = int(message[to_index +1])
		    print data_vol_index
		    pl.audio_set_volume(data_vol_index)
	            if data_vol_index > 100:
		        mess =  "Warning:-- Volume above 100 may cause problem..\n\n Changed the volume to %d " %(data_vol_index)
	    except:
	        print "Error:-- Changing volume cannot ber performed"

	   
    elif 'time' in message and len(message) < 5:                        # for asking time related info.
        mess = datetime.datetime.now().strftime('%I %M  %p %d %B %Y %A ')
	

    elif 'morning' in message  or 'afternoon' in message  or 'night' in message:  # greeting 
        date = datetime.datetime.now().hour
        dateq = check_date(date)
	mess = 'hey its ' + dateq[5:] + ' , ' + dateq
	
    elif 'hey' in message or 'hi' in message or 'hello' in message:
        messig = random.choice(['Hi, good to see you','Hello, good to see you','Hey,  nice to see you'])
	mess = messig + ' ' + u'\U0001f600'.encode('utf8')
    elif 'die' in message:		# rolling a die
	    mess = random.randint(0,7)
	    
	    
    elif 'flip'in message and 'coin' in message: # flip a coin
	    #mess = random.choice(['head','tail'])
             mess =  u'\U0001F604'
	    
    elif  'you' in message or 'your' in message or 'yourself' in message or 'yourselves' in message:

        if 'are' in message  or 'know' in message or 'explain' in message or 'name' in message:
	    mess = 'I am your Pi Assistant,How can I help You'
	   
    elif 'date' in message and len(message) <= 5:
            if 'tomorrow' in message:
                tomorrow = datetime.date.today() + datetime.timedelta(days=1)
		mess =  tomorrow.strftime("%B %d %Y %A")
		
            elif 'yesterday' in message:
                yesterday = datetime.date.today() - datetime.timedelta(days=1)
		mess = yesterday.strftime("%B %d %Y %A")
		

	    
	    else:
                today = datetime.date.today()
		mess =  today.strftime("%B %d %Y %A")
		
    
    elif 'weather' in message:
######################### pyowm   weather map api for weather api ###############################


	placesinfo = bkmessage[11:].upper()
	owm = pyowm.OWM(APIKEY)
	
	try:

	    observation = owm.weather_at_place(placesinfo)
	    w = observation.get_weather()
	    temp_details = w.get_temperature('celsius')

	    mess = placesinfo + '\n' +  'Weather informations are as folllow:--'  + '\n' + str(w) + '\n' + 'Temerature details are:--   ' + str(temp_details['temp_max']) + ' celsius' 
	    

   	 
	except:
	    mess = 'Sorry no places available'    
	    
#    elif 'images' in message:

    elif 'camera' in message:
	try:
	    start = int(datetime.datetime.now().strftime('%S'))
  	    s = datetime.datetime.now().strftime('%I%M%S%p')
	    s = s + '.jpeg'
	#s = 'downloads.jpeg'
	    script_commands = 'sh script2.sh'
	    script_commands = script_commands + ' ' + s 
	    cmd = 'fswebcam -r 1920x1080 --set brightness=50%  '
	    cmd = cmd + s
	    print 'cmd is ' + str( cmd)
	    os.system(cmd)
	    os.system('git add -A')
	    os.system("git commit -m 'latest comit' ")
	    os.system('git push origin master')
	   # os.system(script_commands)

	    imageslink = github_link + s +'?raw=true'
	    print imageslink
            mess = imageslink
	#mess = 'https://github.com/koshtinikhilesh/hello_world/blob/master/downloads.jpeg?raw=true'
	    images.append(mess)
            mess = 'Images is captured\n\n The Captured image is at location:--' + imageslink
        
	    
	   # mess1 = 'images'
	except:
	    mess = 'no image available'


    elif 'capture' in message:
        if 'image' in message:
            lastimages = images[-1]
            mess = lastimages
	    mess1 = 'images'

	elif 'video' in message:
	    try:
	        if len(videos) >= 1:
                
	            lastvideo = videos[-1]
	            mess = 'The Videos is captured\n and locations is at:-- \n\n '
	            os.system('git add -A')
	            os.system('git commit -m "videos commit" ')
	            os.system('git push origin master')
                    mess = lastvideo
                else:
	            mess = 'Sorry,no video is captured'
	    except:
	        mess = 'Sorry video is not available'


    elif 'video' in message:
	try:
	
	    start = int(datetime.datetime.now().strftime('%S'))
  	    s = datetime.datetime.now().strftime('%I%M%S%p')
	    s = s + '.mp4'
	    
	    cmd = 'ffmpeg -t 10  -f v4l2 -framerate 25 -video_size 640x800 -i /dev/video0   '
	    cmd = cmd + s
	    print 'cmd is ' + str( cmd)
	    os.system(cmd)
	    
            mess = ' Videos of 10 second is captured\n '
	    imageslink1 = github_link + s +'?raw=true'
            videos.append(imageslink1)
	   
	except:
	    mess = 'no video available'

    elif 'list' in message:
	try:
	    df1 = pd.read_csv('songs.csv')
	except:
	    mess = 'invalid csv file '
	    return mess,mess1
	
        if 'artist' in message:
	    artistlistname = set(list(df1.loc[:]['artist']))
	    l1 = ''
	    for j in artistlistname:
	        l1 = l1 + j + '\n'
	    mess = 'The available artist  are:--\n'  + l1
	    print artistlistname 
	elif 'album' in message:
	    albumlistname = set(list(df1.loc[:]['album']))
	    l1 = ''
	    for j in albumlistname:
	        l1 = l1 + j + '\n'
	    mess = 'The available album  are:--\n'  + l1
	    print albumlistname