play mp3 without default player - python-3.x

I'm trying play mp3 without default player use, so I want try pyglet, but nothing works
import pyglet
music = pyglet.resource.media('D:/folder/folder/audio.mp3')
music.play()
pyglet.app.run()
I've tried it this way
music = pyglet.resource.media('D:\folder\folder\audio.mp3')
and like this:
music = pyglet.resource.media('D:\\folder\\folder\\audio.mp3')
but have this error
Traceback (most recent call last):
File "C:\Users\User\AppData\Roaming\Python\Python35\site-packages\pyglet\resource.py", line 624, in media
location = self._index[name]
KeyError: 'D:\folder\folder\audio.mp3'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:/PC/PyCharm_project/0_TEMP.py", line 3, in <module>
music = pyglet.resource.media('D:\folder\folder\audio.mp3')
File "C:\Users\User\AppData\Roaming\Python\Python35\site-packages\pyglet\resource.py", line 634, in media
raise ResourceNotFoundException(name)
pyglet.resource.ResourceNotFoundException: Resource "D:\folder\folder\audio.mp3" was not found on the path. Ensure that the filename has the correct captialisation.

It's because of the way you load the resource.
Try this code for instance:
import pyglet
music = pyglet.media.load(r'D:\folder\folder\audio.mp3')
music.play()
pyglet.app.run()
The way this works is that it loads a file and places it in a pyglet.resource.media container. Due to namespaces and other things, the code you wrote is only allowed to load resources from the working directory. So instead, you use pyglet.media.load which is able to load the resource you need into the current namespace (Note: I might be missusing the word "namespace" here, for lack of a better term without looking at the source code of pyglet, this is the best description I could come up with).
You could experiment by placing the .mp3 in the script folder and run your code again but with a relative path:
import pyglet
music = pyglet.resource.media('audio.mp3')
music.play()
pyglet.app.run()
But I'd strongly suggest you use pyglet.media.load() and have a look at the documentation

Related

Python stream audio from YouTube livestream

I'm interested in creating a python 3.9 program that streams audio from a YouTube livestream but unfortunately I can't get the video.getbestaudio() function to work and the function only returns the value null. Thus causing the null error on the next line.
Just in case you need to know I'm using the Pafy library to get the audio stream and the python-vlc library to play the audio. The script is also fully functional if I use a YouTube video that is not a livestream or use the video.getbest() function but this also creates a window displaying the video stream which is not what I want.
I was wondering how I could work around the error and create a functioning python script. I am open to use other methods if they properly work. Thanks for any help in advance!
Here is the error:
Traceback (most recent call last):
File "C:\Users\mjten\Desktop\Programing\Python\lofi.py", line 8, in <module>
playurl = best.url
AttributeError: 'NoneType' object has no attribute 'url'
Here is my code:
import pafy
import vlc
url = 'https://www.youtube.com/watch?v=5qap5aO4i9A'
video = pafy.new(url)
best = video.getbestaudio()
playurl = best.url
player = vlc.MediaPlayer(playurl)
player.play()
while True: pass
P.S Sorry for the bad code I'm just trying to figure out a working example in the meantime.
pip install pafy
pip install youtube_dl
import pafy
def stream(url):
video = pafy.new(url, ydl_opts={'nocheckcertificate': True})
print(video)
best = video.getbestaudio()
stream_urls = best.url
print(stream_urls)
stream('https://www.youtube.com/watch?v=5qap5aO4i9A')

Why error occurs during net.forward using second image in cv2?

I am testing out python opencv (cv2) to detect multiple images using openvino DNN models.
My code for first detection:
import cv2
dog=cv2.imread("dog.jfif")
cat=cv2.imread("cat.jfif")
net=cv2.dnn.readNet("ssd_mobilenetv2_fp16_scale2.xml","ssd_mobilenetv2_fp16_scale2.bin")
blob=cv2.dnn.blobFromImage(dog)
net.setInput(blob)
out=net.forward()
Until here, no error is shown and print (out) shows that the "dog" detection is successful.
But then when i continue the next detection of "cat" image by adding the next few lines:
blob=cv2.dnn.blobFromImage(cat)
net.setInput(blob)
out=net.forward()
And I get:
>>> out = net.forward()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
cv2.error: OpenCV(4.3.0-openvino) ../opencv/modules/dnn/src/ie_ngraph.cpp:522: error: (-215:Assertion failed) !isInitialized() in function 'initPlugin'
Why does this error occur? What is the correct way to do for the second detection?
Probably you can try to run the dog and cat detection separately because the program might confuse of those 2 inputs that came at the same time during the implementation of blob.
Another workaround is, if you still want them to work simultaneously, name the blob differently such as:
For dog:
blob1=cv2.dnn.blobFromImage(dog)
net.setInput(blob1)
For cat
blob2=cv2.dnn.blobFromImage(cat)
net.setInput(blob2)
so that the function net.setInput(blob) doesn't get confuse on which input it should refer to.
Thanks!

How to add a new method to an existing import in python? Specifically moviepy

For whatever reason, Python is not allowing me to access a custom method I created in moviepy's preview.py file. I just want to know how to correctly implement it into the file. For reference, before I changed the name of the method, it was working correctly.
I checked at least two __init.py__ files and they were effectively empty. I couldn't find if methods are initialized anywhere, and is probably what I'm missing.
I also tried restarting Git Bash and that didn't work either (another solution I saw).
Original:
#convert_masks_to_RGB
def preview(clip, fps=15, audio=True, audio_fps=22050, audio_buffersize=3000,
audio_nbytes=2, fullscreen=False):
Changed:
#requires_duration
#convert_masks_to_RGB
def preview_custom(clip, marker_overlay="marker_overlay.png", fps=15, audio=True, audio_fps=22050, audio_buffersize=3000,
audio_nbytes=2, fullscreen=False):
There are more than a few differences between the changed and original method, however at the moment the only result I expect is having the method be called correctly. Error is below:
Traceback (most recent call last):
File "T3AJM.py", line 249, in <module>
main()
File "T3AJM.py", line 34, in main
GUI_main_menu()
File "T3AJM.py", line 85, in GUI_main_menu
GUI_play_markers()
File "T3AJM.py", line 125, in GUI_play_markers
video.preview_custom(marker_overlay=TEMP_OVERLAY_FILE)
AttributeError: 'VideoFileClip' object has no attribute 'preview_custom'
Thank you for your time.
I'm not even sure if this technically fixes the problem, but just doing:
from moviepy.video.io.preview import *
and
preview_custom(video, marker_overlay=TEMP_OVERLAY_FILE)
fixed the problem. I have no idea why I had to change the way it was called, as doing clip.preview(), or in this case video.preview() worked perfectly fine before, but whatever.

Moviepy - Output video not playable

I'm using the library moviepy on Linux Mint 18.1.
Specifically, it's moviepy 0.2.3.2 on python 3.5.2
Since I'm getting started, I tried this simple script, which should concatenate two videos one after the other:
import moviepy.editor as mp
video1 = mp.VideoFileClip("short.mp4")
video2 = mp.VideoFileClip("motivation.mp4")
final_video = mp.concatenate_videoclips([video1,video2])
final_video.write_videofile("composition.mp4")
The two videos are short random videos that I downloaded from YouTube. They both play perfectly, both with VLC and the standard video player provided with Linux Mint.
The script runs fine with no errors, with the final message:
[MoviePy] >>>> Building video composition.mp4
[MoviePy] Writing audio in compositionTEMP_MPY_wvf_snd.mp3
100%|██████████████████████████████| 1449/1449 [00:23<00:00, 59.19it/s]
[MoviePy] Done.
[MoviePy] Writing video composition.mp4
100%|██████████████████████████████| 1971/1971 [11:34<00:00, 2.84it/s]
[MoviePy] Done.
[MoviePy] >>>> Video ready: composition.mp4
The file is indeed created, and it also have a size (about 20 MB). However, when I try to play it, nothing happens: it seems to be corrupted. The standard video player even tells me that "there is no video stream to be played".
If I try to do the same with the interactive console, and use final_video.preview(), I get an AttributeError, along with this traceback:
In [5]: final_video.preview()
Exception in thread Thread-417:
Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "<decorator-gen-211>", line 2, in preview
File "/usr/local/lib/python3.5/dist-packages/moviepy/decorators.py", line 54, in requires_duration
return f(clip, *a, **k)
File "/usr/local/lib/python3.5/dist-packages/moviepy/audio/io/preview.py", line 49, in preview
sndarray = clip.to_soundarray(tt,nbytes=nbytes, quantize=True)
File "<decorator-gen-184>", line 2, in to_soundarray
File "/usr/local/lib/python3.5/dist-packages/moviepy/decorators.py", line 54, in requires_duration
return f(clip, *a, **k)
File "/usr/local/lib/python3.5/dist-packages/moviepy/audio/AudioClip.py", line 107, in to_soundarray
fps = self.fps
AttributeError: 'CompositeAudioClip' object has no attribute 'fps'
and the video seems frozen at the first frame.
I don't have any clue, since everything seems to work fine (except with the preview, which doesn't work because of the error). I tried to reinstall ffmpeg, but no succes: everything is exactly the same. Without any useful error, I can't figure out how to fix this problem. Can anyone help me?
EDIT: What are the 4 magic letters? R-T-F-M! I solved the problem by setting the kwarg method of mp.concatenate_videoclips to compose, since the original videos have a different frame size.
To hopefully figure out what's going on, I decided to take a more systematic approach, following these steps:
Create a virtual environment with no packages other than moviepy and its dependencies
Use videos from a different source
Try different codecs and/or other different parameters
Dig into the source code of moviepy
Sacrifice a goat to the Angel of Light, the Deceiver, the Father of Lies, the Roaring Lion, Son of Perdition Satan Lucifer
In each case I will this script (test.py):
import moviepy.editor as mp
video1 = mp.VideoFileClip("short.mp4")
video2 = mp.VideoFileClip("motiv_30.mp4")
final_video = mp.concatenate_videoclips([video1,video2])
final_video.write_videofile("composition.mp4")
with some minor changes, when needed. I'll update this post as I follow the steps.
1. Create a virtual environment
I created a virtual environment using virtualenv, activated it and installed moviepy with pip. This is the output of pip freeze:
decorator==4.0.11
imageio==2.1.2
moviepy==0.2.3.2
numpy==1.13.3
olefile==0.44
Pillow==4.3.0
tqdm==4.11.2
All with python 3.5.2.
After running test.py, the video is created, with no apparent problems. However, the video can't be played, neither by VLC nor by the default video player of Linux Mint 18.1.
Then, I noticed that mp.concatenate_videoclips has the kwarg method, which is by default set to chain. In the documentation, I read that:
- method="compose", if the clips do not have the same
resolution, the final resolution will be such that no clip has
to be resized.
So, I tried to use the kwarg method="compose", since the two videos have different frame sizes and... it worked. I am an idiot. Oh well, no goats for Satan, I suppose. Lesson learned: RTFM
I was having the same trouble.
I fond the solution at https://zulko.github.io/moviepy/FAQ.html
It turns out that the video cannot have a odd ratio like 1080 x 351, so you just have to check if it's not even them add ou subtract one from that.

Pywinauto and Installshield

My application is packaged using InstallShield. The first thing that happens when you execute the exe is that IS extracts the msi file; this takes about 10 seconds.
I can't look for my main window until the msi extraction is done, so I use time.sleep. Then I look for and find the handle of my window. But the call to app.window_(handle=1234).Wait("enabled", timeout=25, retry_interval=0.5) blows up with these error messages.
*C:\python32>python test.py
| [2558122] |
Traceback (most recent call last):
File "test.py", line 16, in <module>
dlg = app.Window_(handle=hwnd).Wait("enabled", timeout=25, retry_interval=0.
5)
File "C:\python32\lib\site-packages\pywinauto\application.py", line 380, in Wa
it
WaitUntil(timeout, retry_interval, lambda: self.__check_all_conditions(check
_method_names))
File "C:\python32\lib\site-packages\pywinauto\timings.py", line 292, in WaitUn
til
func_val = func(*args)
File "C:\python32\lib\site-packages\pywinauto\application.py", line 380, in <l
ambda>
WaitUntil(timeout, retry_interval, lambda: self.__check_all_conditions(check
_method_names))
File "C:\python32\lib\site-packages\pywinauto\application.py", line 337, in __
check_all_conditions
check = getattr(self, check_name)
File "C:\python32\lib\site-packages\pywinauto\application.py", line 252, in __
getattr__
ctrls = _resolve_control(self.criteria)
File "C:\python32\lib\site-packages\pywinauto\application.py", line 755, in _r
esolve_control
criteria)
File "C:\python32\lib\site-packages\pywinauto\timings.py", line 356, in WaitUn
tilPasses
func_val = func(*args)
File "C:\python32\lib\site-packages\pywinauto\application.py", line 522, in _g
et_ctrl
findwindows.find_window(**criteria[0]))
File "C:\python32\lib\site-packages\pywinauto\controls\HwndWrapper.py", line 1
80, in __new__
new_class = cls.FindWrapper(handle)
File "C:\python32\lib\site-packages\pywinauto\controls\HwndWrapper.py", line 1
12, in FindWrapper
class_name = handleprops.classname(handle)
File "C:\python32\lib\site-packages\pywinauto\handleprops.py", line 94, in cla
ssname
win32functions.GetClassName (handle, ctypes.byref(class_name), 256)
ctypes.ArgumentError: argument 1: <class 'TypeError'>: Don't know how to convert
parameter 1*
This is the code. I am an experienced programmer but a Python newbie. I have worked on this all day, googled my brains out, and have tried everything I can think of. Thanks in advance.
from pywinauto import application
from pywinauto import findwindows
app = application.Application()
app.start("MyInstallShieldApp.exe")
time.sleep(15)
hwnd=findwindows.find_windows(title=u"InstallShield Wizard", class_name="MsiDialogCloseClass")
print ("|", str(hwnd), "|")
dlg = app.Window_(handle=hwnd).Wait("enabled", timeout=25, retry_interval=0.5)
The problem in hwnd, it is a list, but handle=hwnd requires an int.
You should use find_window instead of find_windows or use only the first handle from hwnd, e.g.
hwnd = findwindows.find_windows(...
dlg = app.Window_(handle=hwnd[0])...
Also it may be useful for you to use SWAPY - UI inspector & code generator for pywinauto.
This question is a year old, but hopefully this will help anyone else in the same position. I initially had something similar to OP and was completely lost because I figured it would be as simple as the 7zip installation example provided in the pywinauto github repo. What I found, however, is that the actual installation opens up in a second process, defeating the point of opening the application with Application().start() to launch and hook onto the program simultaneously.
What I did was I used the Inspect program from the Windows SDK to locate the names of the elements and the window that held them once InstallShield was done extracting the .msi file. Instead of opening the InstallShield executable with start(), I used the subprocess module's popen() function to open the installer and then used Application().connect() to hook into the installer once it was extracted via InstallShield. Below is a rough version of what I did to get this functional, mixing my findings with the examples, documentation, and the OP:
import time
import subprocess
from pywinauto import application
# Open the module via Popen
# I tried using run() first but that prevented the click for reasons unknown
subprocess.Popen(r"C:\Users\fixer446\My Documents\InstallationFiles\Setup.exe")
# Let InstallShield extract the files and the installer load completely
time.sleep(15)
# Hook onto the newly opened setup window
app = application.Application().connect(title="Setup.WindowName", class_name="MsiDialogCloseClass")
# Work with the window and the controls within as advertised in pywinauto
# You may have to play around with this a little
installer = app["Setup.WindowName"]
installer["Next >"].Wait("enabled")
installer["Next >"].Click()
Hope this helps.
app.Window_(...) can take the same arguments as find_windows(...). Yeah, it's not highlighted in the docs now. But the code might be shorter:
from pywinauto import application
from pywinauto import findwindows
app = application.Application()
app.start("MyInstallShieldApp.exe")
# the dialog may not exist yet here
dlg_spec = app.Window_(title=u"InstallShield Wizard", class_name="MsiDialogCloseClass")
# after this line the dialog exists or exception is raised
dlg = dlg_spec.Wait("enabled", timeout=25, retry_interval=0.5)
# dlg is a DialogWrapper object (for really existing dialog)
You may read more detailed description of 2-level WindowSpecification concept in this answer.
I will move it into the docs with coming pywinauto 0.6.0 (a bit later).

Resources