VLC Media Player API - python

I am trying to stream an online video using VLC media player. But the URL I'm receiving is random, so that URL needs to be linked to the VLC media player online stream. Is there any APIs that enables the random online video to be played ?
A small understanding of the project that I'm building...
I have a device that will receive the URL from the server and will play it on a screen.
Earlier I was playing it via a web browser. But this time I want it to implement it using a media player.Thus my question, is there any API for VLC media player that can be used to stream online videos?
*** BTW I'm using python to write my scripts.

As wizzwizz4 stated the vlc.py program is available # https://wiki.videolan.org/Python_bindings along with example code for wxpython, pyQt and pyGtk
The documentation is here: https://www.olivieraubert.net/vlc/python-ctypes/doc/
Here is a rough bit of code, which runs from the command line, to give you a start
import requests
import vlc
import time
import os
#Test data a local file, a couple of radio stations and a video to cover all the bases
urls = [
'file:///home/rolf/Music/H5O.mp3',
'http://www.lounge-radio.com/listen128.m3u',
'http://network.absoluteradio.co.uk/core/audio/aacplus/live.pls?service=acbb',
'http://statslive.infomaniak.ch/playlist/energy90s/energy90s-high.mp3/playlist.pls',
'http://streaming.radio.rtl2.fr/rtl2-1-44-128',
'http://clips.vorwaerts-gmbh.de/VfE_html5.mp4'
]
#Define playlist extensions
playlists = set(['pls','m3u'])
#Define vlc playing Status values
playing = set([1,2,3,4])
Instance = vlc.Instance()
# Loop over urls provided
for url in urls:
print ("\n\nLooking for:", url)
# Grab file extension
ext = (url.rpartition(".")[2])[:3]
found = False
# Test if url is a local file or remote
if url[:4] == 'file':
if os.path.isfile(url[7:]):
found = True
else:
print ('Error: File ', url[7:], ' Not found')
continue
else:
try:
r = requests.get(url, stream=True)
found = r.ok
except ConnectionError as e:
print('failed to get stream: {e}'.format(e=e))
continue
if found:
player = Instance.media_player_new()
Media = Instance.media_new(url)
Media_list = Instance.media_list_new([url])
Media.get_mrl()
player.set_media(Media)
# if url is a playlist load list_player else use player
if ext in playlists:
list_player = Instance.media_list_player_new()
list_player.set_media_list(Media_list)
if list_player.play() == -1:
print ("\nError playing playlist")
else:
if player.play() == -1:
print ("\nError playing Stream")
#=========================================================#
# #Use this code for 15 second samples
print ('Sampling ', url, ' for 15 seconds')
time.sleep(15)
#
#=========================================================#
# #Use this code to play audio until it stops
# print ('Playing ', url, ' until it stops')
# time.sleep(5) #Give it time to get going
# while True:
# if ext in playlists:
# state = list_player.get_state()
# if state not in playing:
# break
# else:
# state = player.get_state()
# if state not in playing:
# break
#=========================================================#
if ext in playlists:
list_player.stop()
else:
player.stop()
else:
print ('\nError getting the audio')

If the URL is to the stream / video file, you can just open it directly in VLC like you would anything else. If it's to an HTML document, you'll need to extract the URL of the actual stream.

Related

How to add "pytube" downloading info to tqdm Progress Bar?

I am trying make a YouTube video downloader.
I want make a progress bar while downloading the YouTube video but I cant get any info (how many MB have been downloaded or how many video MB).
I don't know if this is possible with python or not. Here is my code so far:
import time , os
from pytube import YouTube
from tqdm import tqdm
al = str(input("C4ommand:"))
if al == "4":
af = input("Link:")
you = YouTube(af)
try:
os.mkdir("Download")
except:
pass
time.sleep(2)
time.sleep(1)
res = you.streams.get_highest_resolution()
a = res.download()
with tqdm(total=100) as pbar:
for i in range(10):
time.sleep(0.5)
pbar.update(10)
print(af + "Link downloading....")
b = open("\Download", "w")
b.write(a)
b.close()
print("Downloaded")
To access the progress of the download, you can use the on_progress_callback argument when creating a YouTube instance.
The pytube quickstart says the following:
The on_progress_callback function will run whenever a chunk is downloaded from a video, and is called with three arguments: the stream, the data chunk, and the bytes remaining in the video. This could be used, for example, to display a progress bar.
from pytube import Stream
from pytube import YouTube
from tqdm import tqdm
def progress_callback(stream: Stream, data_chunk: bytes, bytes_remaining: int) -> None:
pbar.update(len(data_chunk))
url = "http://youtube.com/watch?v=2lAe1cqCOXo"
yt = YouTube(url, on_progress_callback=progress_callback)
stream = yt.streams.get_highest_resolution()
print(f"Downloading video to '{stream.default_filename}'")
pbar = tqdm(total=stream.filesize, unit="bytes")
path = stream.download()
pbar.close()
print(f"Saved video to {path}")
Sample output:
Downloading video to 'YouTube Rewind 2019 For the Record YouTubeRewind.mp4'
100%|██████████████████████████████| 87993287/87993287 [00:17<00:00, 4976219.51bytes/s]
Saved video to /tmp/testing/YouTube Rewind 2019 For the Record YouTubeRewind.mp4
Pytube has a built-in progress bar, but it does not use tqdm. Please see https://stackoverflow.com/a/60678355/5666087 for more information.

"Unable to locate element" exception with WebDriver in python

I'm getting an "Unable to locate element" exception while running the below code. My expected output is "Button not found. This should not happen."
My code:
driver = webdriver.Chrome()
driver.get(byPassUrl)
driver.find_element_by_xpath("//*[#id='__next']/div/div[1]/div[2]/div/div[1]/div[2]/div/div[1]/div[1]/span/button").click()
time.sleep(3)
emails = driver.find_element_by_css_selector("input[type='email']")
emails.send_keys("mymail.com")
driver.find_element_by_css_selector("input[type='password']").send_keys("abcxyz")
driver.find_element_by_xpath('//button[text()="Log In"]').click()
time.sleep(3)
def delay(waiting_time=5):
driver.implicitly_wait(waiting_time)
audioBtnFound = False
def bypasscaptcha():
try:
# switch to recaptcha audio control frame
driver.switch_to.default_content()
frames = driver.find_element_by_xpath("/html/body/div[3]/div[2]").find_elements_by_tag_name("iframe")
driver.switch_to.frame(frames[0])
delay()
driver.find_element_by_id("recaptcha-audio-button").click()
# get the mp3 audio file
src = driver.find_element_by_id("audio-source").get_attribute("src")
print("[INFO] Audio src: %s" % src)
# download the mp3 audio file from the source
urllib.request.urlretrieve(src, os.path.normpath(os.getcwd() + "\\sample.mp3"))
delay()
# load downloaded mp3 audio file as .wav
try:
sound = pydub.AudioSegment.from_mp3(os.path.normpath(os.getcwd() + "\\sample.mp3"))
sound.export(os.path.normpath(os.getcwd() + "\\sample.wav"), format="wav")
sample_audio = sr.AudioFile(os.path.normpath(os.getcwd() + "\\sample.wav"))
except Exception:
print("[ERR] Please run program as administrator or download ffmpeg manually, "
"http://blog.gregzaal.com/how-to-install-ffmpeg-on-windows/")
# translate audio to text with google voice recognition
r = sr.Recognizer()
with sample_audio as source:
audio = r.record(source)
key = r.recognize_google(audio)
print("[INFO] Recaptcha Passcode: %s" % key)
delay()
# key in results and submit
driver.find_element_by_id("audio-response").send_keys(key.lower())
driver.find_element_by_id("audio-response").send_keys(Keys.ENTER)
except Exception as e:
print(e)
try:
driver.switch_to.default_content()
frames = driver.find_element_by_xpath("/html/body/div[3]/div[2]").find_elements_by_tag_name("iframe")
driver.switch_to.frame(frames[0])
delay()
driver.find_element_by_id("recaptcha-audio-button").click()
audioBtnFound = driver.find_element_by_id("recaptcha-audio-button").is_displayed()
except Exception as e:
print("audioBtn not found")
num = 1
if audioBtnFound:
try:
while True:
print(num)
num += 1
bypasscaptcha()
delay()
#if eye button found do bypasscaptcha
try:
driver.find_element_by_id("recaptcha-image-button").click()
print("Fail captcha")
delay()
bypasscaptcha()
except Exception as e:
print("Pass captcha")
audioBtnFound = False
break
except Exception as e:
print(e)
print('Caught. Need to change proxy now')
else:
print('Button not found. This should not happen.')
If I run the above code I get "Unable to Locate Element Exception".I know that when i log in and no need to bypass captcha this element can not be found "
driver.find_element_by_xpath("/html/body/div[3]/div[2]").find_elements_by_tag_name("iframe")
but how can I deal with this problem.
Thank you so much
iframes tags can be directly found using their tag name or //iframe xpath. you do not have to look for them after /html/body/div[3]/div[2]
Directly try :
all_iframes = find_elements_by_tag_name("iframe")
and now you have the list of iframe on the page.
if you know the number, then you can switch it like the way you have switched in your code.
it may be that selenium does not see the tag it needs, or you have registered an incorrect search. Set the search by id or css_selector. Don't do everything in one line, first find
driver.find_element_by_xpath("/html/body/div[3]/div[2]")
then look for
driver.find_elements_by_tag_name("iframe")

Pytube error: urllib.error.HTTPError: HTTP Error 404: Not Found

from pytube import YouTube
url = 'https://youtu.be/7hvcJK5-OLI'
my_video = YouTube(url)
print("=================== Video Title ====================")
print(my_video.title) # This prints the title of the youtube video
print("=================== Thumbnail Image ====================")
print(my_video.thumbnail_url) # This prints the thumbnail link in terminal
print("=================== Download Video ====================")
choise = input("Do you want to download mp3 or mp4: ")
if choise.lower() == 'mp4':
my_video = my_video.streams.get_highest_resolution() # We set the resolusion of the video
elif choise.lower() == 'mp3':
my_video = my_video.streams.get_audio_only() # To get only audio we set this
else:
print("Invalid option! ")
exit()
my_video.download()
This is my code. I am trying to make simple youtube downloader for project but it keep throwing HTTP Error: 404, although even my url is correct
You just need to update pytube to latest version 10.8.5
Just run pip install --upgrade pytube

How can i use my python script as proxy for urls

i have a script that check the input link, if it's equivalent to one i specified in the code, then it will use my code, else it open the link in chrome.
i want to make that script kind of as a default browser, as to gain speed compared to opening the browser, getting the link with an help of an extension and then send it to my script using POST.
i used procmon to check where the process in question query the registry key and it seem like it tried to check HKCU\Software\Classes\ChromeHTML\shell\open\command so i added a some key there and in command, i edited the content of the key with my script path and arguments (-- %1)(-- only here for testing purposes)
unfortunately, once the program query this to send a link, windows prompt to choose a browser instead of my script, which isn't what i want.
Any idea?
in HKEY_CURRENT_USER\Software\Classes\ChromeHTML\Shell\open\command Replace the value in default with "C:\Users\samdra.r\AppData\Local\Programs\Python\Python39\pythonw.exe" "[Script_path_here]" %1
when launching a link, you'll be asked to set a default browser only once (it ask for a default browser for each change you make to the key):
i select chrome in my case
as for the python script, here it is:
import sys
import browser_cookie3
import requests
from bs4 import BeautifulSoup as BS
import re
import os
import asyncio
import shutil
def Prep_download(args):
settings = os.path.abspath(__file__.split("NewAltDownload.py")[0]+'/settings.txt')
if args[1] == "-d" or args[1] == "-disable":
with open(settings, 'r+') as f:
f.write(f.read()+"\n"+"False")
print("Background program disabled, exiting...")
exit()
if args[1] == "-e" or args[1] == "-enable":
with open(settings, 'r+') as f:
f.write(f.read()+"\n"+"True")
link = args[-1]
with open(settings, 'r+') as f:
try:
data = f.read()
osupath = data.split("\n")[0]
state = data.split("\n")[1]
except:
f.write(f.read()+"\n"+"True")
print("Possible first run, wrote True, exiting...")
exit()
if state == "True":
asyncio.run(Download_map(osupath, link))
async def Download_map(osupath, link):
if link.split("/")[2] == "osu.ppy.sh" and link.split("/")[3] == "b" or link.split("/")[3] == "beatmapsets":
with requests.get(link) as r:
link = r.url.split("#")[0]
BMID = []
id = re.sub("[^0-9]", "", link)
for ids in os.listdir(os.path.abspath(osupath+("/Songs/"))):
if re.match(r"(^\d*)",ids).group(0).isdigit():
BMID.append(re.match(r"(^\d*)",ids).group(0))
if id in BMID:
print(link+": Map already exist")
os.system('"'+os.path.abspath("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe")+'" '+link)
return
if not id.isdigit():
print("Invalid id")
return
cj = browser_cookie3.load()
print("Downloading", link, "in", os.path.abspath(osupath+"/Songs/"))
headers = {"referer": link}
with requests.get(link) as r:
t = BS(r.text, 'html.parser').title.text.split("·")[0]
with requests.get(link+"/download", stream=True, cookies=cj, headers=headers) as r:
if r.status_code == 200:
try:
id = re.sub("[^0-9]", "", link)
with open(os.path.abspath(__file__.split("NewAltDownload.pyw")[0]+id+" "+t+".osz"), "wb") as otp:
otp.write(r.content)
shutil.copy(os.path.abspath(__file__.split("NewAltDownload.pyw")[0]+id+" "+t+".osz"),os.path.abspath(osupath+"/Songs/"+id+" "+t+".osz"))
except:
print("You either aren't connected on osu!'s website or you're limited by the API, in which case you now have to wait 1h and then try again.")
else:
os.system('"'+os.path.abspath("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe")+'" '+link)
args = sys.argv
if len(args) == 1:
print("No arguments provided, exiting...")
exit()
Prep_download(args)
you obtain the argument %1 (the link) with sys.argv()[-1] (since sys.argv is a list) and from there, you just check if the link is similar to the link you're looking for (in my case it need to look like https://osu.ppy.sh/b/ or https://osu.ppy.sh/beatmapsets/)
if that's the case, do some code, else, just launch chrome with chrome executable and the link as argument. and if the id of the beatmap is found in the Songs folder, then i also open the link in chrome.
to make it work in the background i had to fight with subprocesses and even more tricks, and at the end, it started working suddenly with pythonw and .pyw extension.

Detect the end of a song using Spotipy

I'm using Spotipy and LyricsGenius to open lyrics on a web browser from a terminal.
I can open a url for one song, but have to run the script each time to run consecutively. What are some ways to detect the end of a song using Spotipy?
import spotipy
import webbrowser
import lyricsgenius as lg
...
# Create our spotifyObject
spotifyObject = spotipy.Spotify(auth=token)
# Create out geniusObject
geniusObject = lg.Genius(access_token)
...
while True:
currently_playing = spotifyObject.currently_playing()
artist = currently_playing['item']['artists'][0]['name']
title = currently_playing['item']['name']
search_query = artist + " " + title
# if (currently_playing has changed):
song = geniusObject.search_songs(search_query)
song_url = song['hits'][0]['result']['url']
webbrowser.open(song_url)
webbrowser.open(song_url)
I was reading relevant threads such as this, this, and read through documentation but could not find an answer to my question if this could be handled by Spotipy. I would appreciate any suggestions, thank you.
I used time.sleep(length) with the argument 'length' standing for the remaining duration of a current track.

Categories

Resources