Hoping someone can help me solve this puzzle.
Using python-vlc 3.0.16120 - I'm trying to stream over http from a Python script on Windows.
It works using this command line:
"C:\Program Files\VideoLAN\VLC\vlc.exe" sample-mp4-file.mp4 --sout="#transcode{vcodec=h264,acodec=mpga,ab=128,channels=2,samplerate=44100,scodec=none}:duplicate{dst=http{mux=ffmpeg{mux=flv},dst=:8080/}", :no-sout-all :sout-keep
However, this code (using the same sout) doesn't seem to work.
import vlc
inst = vlc.Instance("""--sout="#transcode{vcodec=h264,acodec=mpga,ab=128,channels=2,samplerate=44100,scodec=none}:duplicate{dst=http{mux=ffmpeg{mux=flv},dst=:8080/}", :no-sout-all :sout-keep""")
med = inst.media_new("sample-mp4-file.mp4")
p = med.player_new_from_media()
p.play()
while True:
pass
Does anyone have any suggestions
TIA
This code works- don't ask me why
import vlc
inst = vlc.Instance()
param=[
"sample-mp4-file.mp4"
,"sout=#transcode{vcodec=h264,acodec=mpga,ab=128,channels=2,samplerate=44100,scodec=none}:duplicate{dst=http{mux=ffmpeg{mux=flv},dst=:8080/}"
]
Media = inst.media_new(*param)
player = Media.player_new_from_media()
player.play()
while True:
pass
Related
I would like to play video with python-vlc module. I wrote the following code. My computer is MacOS Catalina.
#!/usr/bin/env python3
import vlc
p = vlc.MediaPlayer("mediafile.mp4")
p.play()
while True:
pass
But the python3 interpreter threw the following errors.
[00007f89b9661950] caopengllayer vout display error: No drawable-nsobject found!
[00007f89b9661950] macosx vout display error: No drawable-nsobject nor vout_window_t found, passing over.
[00007f89b30530f0] main video output error: video output creation failed
[00007f89b9650c00] main decoder error: failed to create video output
[h264 # 0x7f89b407c000] get_buffer() failed
[h264 # 0x7f89b407c000] thread_get_buffer() failed
[h264 # 0x7f89b407c000] decode_slice_header error
[h264 # 0x7f89b407c000] no frame!
I guessed that this code didn't make a frame displaying the video. It'll be a main cause of this error, I think.
However, I can not come up with a solution of this problem.
Please tell me how to play video with python-vlc module!!
I think the possible reason is, it requires an active hwnd where it can show the video.
So you need an GUI and set hwnd to that player.
Here is my code for Tkinter Window.You can also check out different GUI based example From Github
import vlc
from tkinter import *
root=Tk()
instance=vlc.Instance()
p=instance.media_player_new()
p.set_hwnd(root.winfo_id())
p.set_media(instance.media_new(path_to_media))
p.play()
root.mainloop()
And if you r using Mac ,then as per the example
you should use instaed of this line
p.set_hwnd(root.winfo_id())
try:
libtk = 'libtk%s.dylib' % (Tk.TkVersion,)
prefix = getattr(sys, 'base_prefix', sys.prefix)
libtk = joined(prefix, 'lib', libtk)
dylib = cdll.LoadLibrary(libtk)
# getNSView = dylib.TkMacOSXDrawableView is the
# proper function to call, but that is non-public
# (in Tk source file macosx/TkMacOSXSubwindows.c)
# and dylib.TkMacOSXGetRootControl happens to call
# dylib.TkMacOSXDrawableView and return the NSView
_GetNSView = dylib.TkMacOSXGetRootControl
# C signature: void *_GetNSView(void *drawable) to get
# the Cocoa/Obj-C NSWindow.contentView attribute, the
# drawable NSView object of the (drawable) NSWindow
_GetNSView.restype = c_void_p
_GetNSView.argtypes = c_void_p,
del dylib
except (NameError, OSError): # image or symbol not found
def _GetNSView(unused):
return None
libtk = "N/A"
h = root.winfo_id() # .winfo_visualid()?
# XXX 1) using the videopanel.winfo_id() handle
# causes the video to play in the entire panel on
# macOS, covering the buttons, sliders, etc.
# XXX 2) .winfo_id() to return NSView on macOS?
v= _GetNSView(h)
if v:
p.set_nsobject(v)
else:
p.set_xwindow(h)# plays audio, no video
I think this will work:
import vlc
media = vlc.MediaPlayer("1.mp4")
media.play()
It just takes a media filename for you.
Make sure the video is in the same folder as the script.
I am using Python 3.5.3 on Windows 8.1 x64 and i need play audio from here
I have tried pyaudio, but it gives me only white noise and error occurred after a few runs of pyaudio (pyaudio module 'pyaudio' has no attribute 'PyAudio').
Please, advise me how better play the streaming audio from url, using Python...
P.S. I already got the song title and artist name with this code:
import requests
import time
import datetime
print(datetime.datetime.now())
import re
url = 'http://prem1.rockradio.com:80/bluesrock?9555ae7caa92404c73cade1d'
encoding = 'latin1'
info = ''
radio_session = requests.Session()
while True:
radio = radio_session.get(url, headers={'Icy-MetaData': '1'}, stream=True)
metaint = int(radio.headers['icy-metaint'])
stream = radio.raw
audio_data = stream.read(metaint)
meta_byte = stream.read(1)
if (meta_byte):
meta_length = ord(meta_byte) * 16
meta_data = stream.read(meta_length).rstrip(b'\0')
stream_title = re.search(br"StreamTitle='([^']*)';", meta_data)
if stream_title:
stream_title = stream_title.group(1).decode(encoding, errors='replace')
if info != stream_title:
print('Now playing: ', stream_title)
info = stream_title
else:
pass
else:
print('No StreamTitle!')
time.sleep(1)
If you are open for external libraries, you can install vlc binding for python using pip install python-vlc
And use player method to play audio file directly from URL as below.
import vlc
import time
url = 'http://prem1.rockradio.com:80/bluesrock?9555ae7caa92404c73cade1d'
#define VLC instance
instance = vlc.Instance('--input-repeat=-1', '--fullscreen')
#Define VLC player
player=instance.media_player_new()
#Define VLC media
media=instance.media_new(url)
#Set player media
player.set_media(media)
#Play the media
player.play()
Advantage of vlc player is that you can play most media types directly from URL (not just mp3) and also perform player like options such as
>>> player.pause() #pause play back
>>> player.play() #resume play back
>>> player.stop() #stop play back
I have this function and I need to close the file before exiting the function say("some text").
def say(self, text):
tts = gTTS(text, lang='fr')
file="text.mp3"
tts.save(file)
audio = MP3(file)
p = vlc.MediaPlayer(file)
p.play()
time.sleep((audio.info.length)) #to avoid it listening to itself
p.stop()
return file
Because If I don't do this, I have this error
OS Error: [Errno -9993] Illegal combination of I/O device
I think that this error occurs because I'm trying to listen just after the call of the function say and the file is still open.
nb: I'm working with Python 3
Though i am not to experienced with TTS, shouldnt it work if you just do close(os.getcwd()+'/'+file)?
I apologise if the question is so stupid but I am new in linux and python.
The point is that I need to write a python script which will detect connected usb stick and write a file to it. I use opensuse(but script shoild work with any linux distro. in ideal case). Current version can detect usb and write a file if that usb is mounted. But on my machine usb is mounted only if I browse it in file manager. Until that usb detected as a partion but without mount point. So, how can I force the system to mount usb or how can I write a file using devname or devpath or another information what I can get from hal manager. I can not use "mount" command because it requires a root permission
Simplified Source code:
import dbus, gobject, os
class DeviceAddedListener:
def __init__(self):
self.bus = dbus.SystemBus()
self.hal_manager_obj = self.bus.get_object( "org.freedesktop.Hal", "/org/freedesktop/Hal/Manager")
self.hal_manager = dbus.Interface(self.hal_manager_obj, "org.freedesktop.Hal.Manager")
self.hal_manager.connect_to_signal("DeviceAdded", self.added)
def show(self, name, udi):
d_object = self.bus.get_object('org.freedesktop.Hal', udi)
d_interface = dbus.Interface(d_object,'org.freedesktop.Hal.Device')
if d_interface.QueryCapability("volume"):
print name
props = [ "block.device", "volume.label", "volume.is_mounted", "volume.mount_point", "volume.size"]
for p in props:
print '\t', p, " = ",
try:
print d_interface.GetProperty(p)
except:
print "Fail"
def added(self, udi):
self.show("DeviceAdded", udi)
self.bus.add_signal_receiver(self.property_modified,
"PropertyModified",
"org.freedesktop.Hal.Device",
"org.freedesktop.Hal",
udi,
path_keyword = "sending_device" )
def property_modified(self, numupdates, updates, sending_device = None):
self.show("PropertyModified", sending_device)
if __name__ == '__main__':
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
loop = gobject.MainLoop()
DeviceAddedListener()
print "running"
loop.run()
The output when usb plugged in
DeviceAdded
block.device = /dev/sdb1
volume.label = #
volume.is_mounted = 0
volume.mount_point =
volume.size = 4009722368
The output when usb plugged in and mounted
block.device = /dev/sdb1
volume.label = #
volume.is_mounted = 1
volume.mount_point = /media/#
volume.size = 4009722368
Thanks for any help!
You will have to use mount because the kernel controls mounting partitions within the operating system for security reasons. You can use mount without superuser/administrator privileges. Try something like this:
Make sure that the directory (/mnt/usb1/) you are mounting to already exists, and then
mount /dev/sdb1 /mnt/usb1 -o noauto,users,rw,umask=0
There's also something called autofs that does allow automatic mounting:
http://linuxconfig.org/automatically-mount-usb-external-drive-with-autofs
The HAL it's discontinued, I think so better use UDisks to work with pen USB. Then, you can use methods FilesystemMount and FilesystemUnmount, I create one example here (https://gist.github.com/3037221) and have oficial documantation here (http://hal.freedesktop.org/docs/udisks/Device.html#Device.FilesystemMount).
I'm looking for a method to play midi files in python.
It seems python does not support MIDI in its standard library.
After I searched, I found some python midi librarys such as pythonmidi.
However, most of them can only create and read MIDI file without playing function.
I would like to find a python midi library including playing method.
Any recommendations? Thanks!
The pygame module can be used to play midi files.
http://www.pygame.org/docs/ref/music.html
See the example here:
http://www.daniweb.com/software-development/python/code/216979
a whole bunch of options available at:
http://wiki.python.org/moin/PythonInMusic
and also here which you can modify to suit your purpose:
http://xenon.stanford.edu/~geksiong/code/playmus/playmus.py
Just to add a minimal example (via DaniWeb):
# conda install -c cogsci pygame
import pygame
def play_music(midi_filename):
'''Stream music_file in a blocking manner'''
clock = pygame.time.Clock()
pygame.mixer.music.load(midi_filename)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
clock.tick(30) # check if playback has finished
midi_filename = 'FishPolka.mid'
# mixer config
freq = 44100 # audio CD quality
bitsize = -16 # unsigned 16 bit
channels = 2 # 1 is mono, 2 is stereo
buffer = 1024 # number of samples
pygame.mixer.init(freq, bitsize, channels, buffer)
# optional volume 0 to 1.0
pygame.mixer.music.set_volume(0.8)
# listen for interruptions
try:
# use the midi file you just saved
play_music(midi_filename)
except KeyboardInterrupt:
# if user hits Ctrl/C then exit
# (works only in console mode)
pygame.mixer.music.fadeout(1000)
pygame.mixer.music.stop()
raise SystemExit
pretty_midi can generate the waveform for you, you can then play it with e.g. IPython.display.Audio
from IPython.display import Audio
from pretty_midi import PrettyMIDI
sf2_path = 'path/to/sf2' # path to sound font file
midi_file = 'music.mid'
music = PrettyMIDI(midi_file=midi_file)
waveform = music.fluidsynth(sf2_path=sf2_path)
Audio(waveform, rate=44100)
Use pygame to play your midi file. Examples are here or here
I find that midi2audio works well.
Example:
from midi2audio import FluidSynth
#Play MIDI
FluidSynth().play_midi('input.mid')
#Synthesize MIDI to audio
# Note: the default sound font is in 44100 Hz sample rate
fs = FluidSynth()
fs.midi_to_audio('input.mid', 'output.wav')
# FLAC, a lossless codec, is recommended
fs.midi_to_audio('input.mid', 'output.flac')
On macOS, you can use the pyObjC library to access the OS's own MIDI handling routines. This script will play midi files given as arguments.
#!/usr/bin/env python3
from AVFoundation import AVMIDIPlayer
from Foundation import NSURL
import time
import sys
def myCompletionHandler():
return
def playMIDIFile(filepath):
midiFile = NSURL.fileURLWithPath_(filepath)
midiPlayer, error = AVMIDIPlayer.alloc().initWithContentsOfURL_soundBankURL_error_(midiFile, None, None)
if error:
print (error)
sys.exit(1)
MIDItime = midiPlayer.duration()
midiPlayer.prepareToPlay()
midiPlayer.play_(myCompletionHandler)
if not midiPlayer.isPlaying:
midiPlayer.stop()
else:
time.sleep(MIDItime)
return
if __name__ == "__main__":
for filename in sys.argv[1:]:
playMIDIFile(filename)