I have a class that checks for suitable framebuffer, and it works fine. One a couple of computers (mostly embedded older boards) there is no framebuffer, so I remove the init(self): function and manually set it to run under X. Both ways work on their respective systems, I'm just tired of porting it every time I make a change.
Here is the working framebuffer code:
class wxdisplay :
screen = None;
def __init__(self):
"Ininitializes a new pygame screen using the framebuffer"
# Based on "Python GUI in Linux frame buffer"
# http://www.karoltomala.com/blog/?p=679
disp_no = os.getenv("DISPLAY")
if disp_no:
print "I'm running under X display = {0}".format(disp_no)
# Check which frame buffer drivers are available
# Start with fbcon since directfb hangs with composite output
drivers = ['fbcon', 'directfb', 'svgalib']
found = False
for driver in drivers:
# Make sure that SDL_VIDEODRIVER is set
if not os.getenv('SDL_VIDEODRIVER'):
os.putenv('SDL_VIDEODRIVER', driver)
try:
pygame.display.init()
except pygame.error:
print 'Driver: {0} failed.'.format(driver)
continue
found = True
break
if not found:
raise Exception('No suitable video driver found!')
size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
print "Framebuffer size: %d x %d" % (size[0], size[1])
self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN)class wxdisplay :
And here is the non-framebuffered version:
class wxdisplay :
pygame.init()
size = (1024, 768)
screen = pygame.display.set_mode(size)
print "Framebuffer size: %d x %d" % (size[0], size[1])
I would like to try and initialize the framebuffer and if it fails, try and just run it on the console. Every thing I have try'd or if'd or excepted fails...
class wxdisplay :
def __init__(self):
# Try to use framebuffer, and use the local X server if not there
try:
screen = None;
"Ininitializes a new pygame screen using the framebuffer"
# Based on "Python GUI in Linux frame buffer"
# http://www.karoltomala.com/blog/?p=679
disp_no = os.getenv("DISPLAY")
print("disp_no " +disp_no)
if disp_no:
print "I'm running under X display = {0}".format(disp_no)
# Check which frame buffer drivers are available
# Start with fbcon since directfb hangs with composite output
drivers = ['fbcon', 'directfb', 'svgalib', 'xvfb', 'Xvfb']
found = False
for driver in drivers:
# Make sure that SDL_VIDEODRIVER is set
if not os.getenv('SDL_VIDEODRIVER'):
os.putenv('SDL_VIDEODRIVER', driver)
try:
print("Driver: "+driver)
pygame.display.init()
except pygame.error:
print 'Driver: {0} failed.'.format(driver)
continue
found = True
print("break")
break
if not found:
raise Exception('No suitable video driver found!')
size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
print "Framebuffer size: %d x %d" % (size[0], size[1])
self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
except:
print('No suitable Framebuffer found!')
pygame.init()
size = (1024, 768)
print "X server size: %d x %d" % (size[0], size[1])
self.screen = pygame.display.set_mode(size)
fails with:
starting from __main__ call
disp_no localhost:11.0
I'm running under X display = localhost:11.0
Driver: fbcon
Driver: fbcon failed.
Driver: directfb
commandline read: python
commandline read: ./PiWxDisplay.py
~~~~~~~~~~~~~~~~~~~~~~~~~~| DirectFB 1.2.10 |~~~~~~~~~~~~~~~~~~~~~~~~~~
(c) 2001-2008 The world wide DirectFB Open Source Community
(c) 2000-2004 Convergence (integrated media) GmbH
----------------------------------------------------------------
(*) DirectFB/Core: Single Application Core. (2012-05-20 13:17)
(!) Direct/Util: opening '/dev/fb0' and '/dev/fb/0' failed
--> No such file or directory
(!) DirectFB/FBDev: Error opening framebuffer device!
(!) DirectFB/FBDev: Use 'fbdev' option or set FRAMEBUFFER environment variable.
(!) DirectFB/Core: Could not initialize 'system_core' core!
--> Initialization error!
Driver: directfb failed.
Driver: svgalib
Driver: svgalib failed..
No suitable Framebuffer found!
X server size: 1024 x 768
Traceback (most recent call last):
File "./PiWxDisplay.py", line 366, in <module>
wxdisplay().start_screen()
File "./PiWxDisplay.py", line 66, in __init__
self.screen = pygame.display.set_mode(size)
pygame.error: No available video device
I obviously don't fully understand how to initialize pygame correctly. How would I get it to
Check for a FB driver
Use the X server if the FB driver detection fails
Late answer but I wish I would have tried that earlier :
You may need to be root to use a frame buffer driver.
(It helped in my case: RaspberryPi 2 without X running but with a screen connected. I can now open a display through SSH or directly on the RPi)
You have already changed the SDL_VIDEODRIVER environment to check only for fb devices.
I'd suggest using this before your pygame.init() call in your exception handler:
os.putenv('SDL_VIDEODRIVER', 'x11')
or unset the SDL_VIDEODRIVER environment var, so that pygame.init() doesn't think it's already dealt with.
see: http://www.pygame.org/docs/ref/display.html#pygame.display.init
Related
Here is my python code that I am using. I am trying to use a wii remote to trigger a buzzer. I thought this would be an interesting use for my old wii remote. The code that interacts with the buzzer works fine because I used an example script to test it. However, when I try and run it I keep getting this one error (see bottom). I am new to python and would appreciate any help.
import cwiid
from gpiozero import LED
import time
import os
Buzzer1 = LED(17)
Buzzer2 = LED(27)
def ConnectRemote():
os.system("rfkill unblock bluetooth")
print 'Press 1+2 On The Remote...'
global wm
wm = wiid.Wiimote()
print 'Connection Established!\n'
wm.led = 1
wm.rumble = 1
time.sleep(0.25)
wm.rumble = 0
time.sleep(0.5)
wm.rpt_mode = cwiid.RPT_BTN
def TryToConnect():
while True:
ConnectRemote()
break
while True:
buttons = wm.state['buttons']
#shutdown function using plus and minus buttons
if (buttons - cwiid.BTN_PLUS - cwiid.BTN_MINUS == 0):
print '\nClosing Connection To Wiimote'
wm.rumble = 1
time.sleep(0.25)
wm.rumble = 0
os.system("rfkill block bluetooth")
TryToConnect()
if (buttons & cwiid.BTN_A):
print 'Buzzer On'
Buzzer1.on()
Buzzer2.on()
else:
Buzzer1.off()
Buzzer2.off()
and yet I keep getting an error of
Traceback (most recent call last):
File "WiimoteLEDs.py", line 36, in <module>
buttons = wm.state['buttons']
NameError: global name 'wm' is not defined
Can anyone help? Thanks in advance
I think you should initialized variable wm before using this variable in function.
This bug is related to 'Global name not defined'
I'm trying to save video files on a raspberry pi with python2.7 and opencv. The code shown below consistently saves several video files (size 16-18 Mb) to a usb but after the first few files the file sizes drop to 6 kb and appear to be empty since they won't open.
I opened task manager to monitor the memory usage by python during the saving and noticed that the RSS memory continually increases until roughly 200 MB which is when the video files start showing up blank.
Is that a sure indicator of a memory leak, or should I run other tests?
Is there something wrong in the below code that isn't releasing variables properly?
import cv2
import numpy as np
import datetime
dispWidth = 640
dispHeight = 480
FPS = 6
SetupNewVideoFile = True # state variable
VidCaptureDurationMinutes = 3
filepath = '/media/pi/9CEE-5383/Videos/'
i = 1 # counter for the video file names
fourcc = cv2.cv.CV_FOURCC('X','V','I','D')
while True:
# timer section that ends running file saves and triggers a new file save
Now = datetime.datetime.now() # refresh current time
delta = Now - VidCaptureStartTime
print('delta: ',delta.seconds,delta.days)
if ((delta.seconds/60) >= VidCaptureDurationMinutes) and delta.days >= 0:
print('delta: ',delta.seconds,delta.days)
SetupNewVideoFile = True
Vidoutput.release()
cap.release()
# setting up new file saves
if SetupNewVideoFile:
SetupNewVideoFile = False
title = "Video_"+str(i)+".avi"
i += 1
fullpath = filepath + title
print(fullpath)
Vidoutput = cv2.VideoWriter(fullpath, fourcc, FPS,(dispWidth,dispHeight))
VidCaptureStartTime = datetime.datetime.now() # updating video start time
cap = cv2.VideoCapture(-1) # start video capture
ret, frame = cap.read()
if ret: # display and save if a frame was successfully read
cv2.imshow('webcam',frame)
Vidoutput.write(frame) # save the frames
key = cv2.waitKey(1) & 0xFF
if key == ord('q'): # quits program
break
# clean up
cap.release()
Vidoutput.release()
cv2.destroyAllWindows()
cv2.waitKey(1) # these seem to be needed to flush the cv actions
cv2.waitKey(1)
cv2.waitKey(1)
cv2.waitKey(1)
After some more trouble shooting and help from the pympler module functions and tutorials (https://pythonhosted.org/Pympler/muppy.html) my problems still looked like a memory leak but I was unable to solve the specific error.
This other S.O. post (Releasing memory in Python) mentioned improvements in memory management made in version 3.3 of Python:
"In Python 3.3 the small object allocator was switched to using anonymous memory maps instead of the heap, so it should perform better at releasing memory."
So I switched over to Python 3.3 and now the code saves valid video files well past the error out time I saw previously.
This isn't an answer as to why the blank files were occurring, but at least it's a solution.
I have moved on to messing with Pygame recently, and I started following tutorials. Everything has ran fine up until I reached a program that looks like so:
"""
A python graphics introduction.
This simple program draws lines at a 45 degree angle from one side
of the screen to the other.
"""
# Import a library of functions called 'pygame'
import pygame
from pygame import font
# Initialize the game engine
pygame.init()
# Set the height and width of the screen
size = (400, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Intro to Graphics")
#Loop until the user clicks the close button.
done = False
clock = pygame.time.Clock()
# Loop as long as done == False
while not done:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
# All drawing code happens after the for loop and but
# inside the main while not done loop.
# Clear the screen and set the screen background
screen.fill(WHITE)
# Select the font to use, size, bold, italics
font = pygame.font.SysFont('Calibri', 25, True, False)
# Render the text. "True" means anti-aliased text.
# Black is the color. This creates an image of the
# letters, but does not put it on the screen
text = font.render("My text", True, BLACK)
# Put the image of the text on the screen at 250x250
screen.blit(text, [250, 250])
# Go ahead and update the screen with what we've drawn.
# This MUST happen after all the other drawing commands.
pygame.display.flip()
# This limits the while loop to a max of 60 times per second.
# Leave this out and we will use all CPU we can.
clock.tick(60)
# Be IDLE friendly
pygame.quit()
When ran I get an error at font = pygame.font.SysFont('Calibri', 25, True, False) that looks like:
RuntimeWarning: use font: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/font.so, 2): Library not loaded: /usr/X11/lib/libfreetype.6.dylib
Referenced from: /Library/Frameworks/SDL_ttf.framework/Versions/A/SDL_ttf
Reason: image not found
(ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/font.so, 2): Library not loaded: /usr/X11/lib/libfreetype.6.dylib
Referenced from: /Library/Frameworks/SDL_ttf.framework/Versions/A/SDL_ttf
Reason: image not found)
pygame.font.init()
Traceback (most recent call last):
File "IntroGraphics.py", line 15, in <module>
pygame.font.init()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py", line 70, in __getattr__
raise NotImplementedError(MissingPygameModule)
NotImplementedError: font module not available
(ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/font.so, 2): Library not loaded: /usr/X11/lib/libfreetype.6.dylib
Referenced from: /Library/Frameworks/SDL_ttf.framework/Versions/A/SDL_ttf
Reason: image not found)
I have looked on here for an answer, and the only other post about it involves 32-bit Pygame with 64-bit Python. I have made sure both of them are running 32-bit (Despite the fact it's a 64-bit machine. Pygame is only 32-bit.). I am running Python 2.7.9 Fresh Install
Other places say it's a problem with SDL, but I am inexperienced with SDL and I wouldn't know what to do.
Has anyone else had this problem?
The fonts that are available to pygame might be different on different computers. I suggest seeing if the font you want to use is included on your computer. You can see the all the available fonts with this command:
pygame.font.get_fonts()
# returns a list of available fonts
You can also get the system's default fort by using this command:
pygame.font.get_default_font()
# returnes the name of the default font
You can use this code to check your font:
if 'Calibri' in pygame.font.get_fonts():
font_name = 'Calibri'
else:
font_name = pygame.font.get_default_font()
I am trying in ubuntu 12.04 to play the wav files using the pyaudio and selecting the output device index - USB Advanced Audio Device: USB Audio (hw:1,0) .
If I will select Frame rate 48000.000000 wav file and selected the output device index - USB Audio it's working fine ,I am able to hear .BUT
But if i choose Frame rate 16000.000000 wav file and selected the output device index - USB Audio it's working fine ,I am NOT able to hear,It's showing the following error :
Expression 'SetApproximateSampleRate( pcm, hwParams, sr )' failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 1968
Expression 'PaAlsaStreamComponent_InitialConfigure( &self->playback, outParams, self->primeBuffers, hwParamsPlayback, &realSr )' failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 2646
Expression 'PaAlsaStream_Configure( stream, inputParameters, outputParameters, sampleRate, framesPerBuffer, &inputLatency, &outputLatency, &hostBufferSizeMode )' failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 2767
Traceback (most recent call last):
File "speech.py", line 34, in <module>
output=True)
File "/usr/lib/pymodules/python2.7/pyaudio.py", line 714, in open
stream = Stream(self, *args, **kwargs)
File "/usr/lib/pymodules/python2.7/pyaudio.py", line 396, in __init__
self._stream = pa.open(**arguments)
IOError: [Errno Invalid sample rate] -9997
same sampling rate 16 k if I will select "default " device index it's working fine .My Code is simple to get the audio device output index and I am passing the output device index id
import pyaudio
import wave
import sys
if len(sys.argv) < 2:
print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
sys.exit(-1)
"""wf = wave.open('C:/Users/arunku2x/Desktop/bar_opening.wav', 'rb')"""
wf = wave.open(sys.argv[1], 'rb')
p = pyaudio.PyAudio()
count = p.get_device_count()
devices = []
for i in range(count):
devices.append(p.get_device_info_by_index(i))
for i, dev in enumerate(devices):
print "%d - %s" % (i, dev['name'])
print "Sample Width %f" % wf.getsampwidth()
print "Number of channels %d" % wf.getnchannels()
print "Frame rate %f" % wf.getframerate()
#x = p.is_format_supported(rate = wf.getframerate(),output_device = 4 ,output_channels = wf.getnchannels(),output_format= p.get_format_from_width(wf.getsampwidth()))
#print "format .............x %d" % x
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output_device_index =4,#here 4 means - USB Audio device
output=True)
data = wf.readframes(1024)
while data != '':
stream.write(data)
data=wf.readframes(1024)
Using PyAudio to play the sound .
Let me know if you any idea to work the 16k sampling rate using PyAudio with USB audio device.
Using LibVLC, I'm trying to save a stream while playing it. This is the python code:
import os
import sys
import vlc
if __name__ == '__main__':
filepath = <either-some-url-or-local-path>
movie = os.path.expanduser(filepath)
if 'http://' not in filepath:
if not os.access(movie, os.R_OK):
print ( 'Error: %s file is not readable' % movie )
sys.exit(1)
instance = vlc.Instance("--sub-source marq --sout=file/ps:example.mpg")
try:
media = instance.media_new(movie)
except NameError:
print ('NameError: % (%s vs Libvlc %s)' % (sys.exc_info()[1],
vlc.__version__, vlc.libvlc_get_version()))
sys.exit(1)
player = instance.media_player_new()
player.set_media(media)
player.play()
#dont exit!
while(1):
continue
It saves the video stream to a file example.mpg. As per this doc, the command to save a stream is this :
--sout=file/ps:example.mpg
which I've using when creating an instance of vlc.Instance:
instance = vlc.Instance("--sub-source marq --sout=file/ps:example.mpg")
But the problem is that it only saves the stream, it doesn't play the stream simultaneously.
Is there any way (in LibVLC) I can save the stream (to a local file) while paying it?
Although, I'm looking for a solution in Python 3.3.1 but it is fine if there is any C or C++ solution.
I've created a similar, but not duplicate, topic yesterday.
Idea:
The basic idea is simple enough. You have to duplicate the output stream and redirect it to a file. This is done, as Maresh correctly pointed out, using the sout=#duplicate{...} directive.
Working Solution:
The following solution works on my machine ™. I've tested it on Ubuntu 12.10 with VLC v2.0.3 (TwoFlower) and Python 2.7.1. I think it should also work on Python 3 since most of the heavy lifting is done by libVlc anyway.
import os
import sys
import vlc
if __name__ == '__main__':
#filepath = <either-some-url-or-local-path>
movie = os.path.expanduser(filepath)
if 'http://' not in filepath:
if not os.access(movie, os.R_OK):
print ( 'Error: %s file is not readable' % movie )
sys.exit(1)
instance = vlc.Instance("--sout=#duplicate{dst=file{dst=example.mpg},dst=display}")
try:
media = instance.media_new(movie)
except NameError:
print ('NameError: % (%s vs Libvlc %s)' % (sys.exc_info()[1],
vlc.__version__, vlc.libvlc_get_version()))
sys.exit(1)
player = instance.media_player_new()
player.set_media(media)
player.play()
#dont exit!
while(1):
continue
Helpful Links
The Command-Line help was essential to decipher the plethora of VLCs
command line options.
Chapter 3 of VLC streaming HowTo. Explains the structure of the stream output, its directives and describes of the various available modules. Chapter 4 shows some examples.
LibVLC API documentation in case you want to change media option at
runtime
Update - Saving YouTube videos:
The above code doesn't play nice with YouTube. I searched around and discovered that an additional transcode directive can be used to convert YouTube's video stream to a regular video format. I used #transcode{vcodec=mp4v,acodec=mpga,vb=800,ab=128,deinterlace}
vcodec=mp4v is the video format you want to encode in (mp4v is MPEG-4, mpgv is MPEG-1, and there is also h263, DIV1, DIV2, DIV3, I420, I422, I444, RV24, YUY2).
acodec=mpga is the audio format you want to encode in (mpga is MPEG audio layer 2, a52 is A52 i.e. AC3 sound).
vb=800 is the video bitrate in Kbit/s.
ab=128 is the audio bitrate in Kbit/s.
deinterlace tells VLC to deinterlace the video on the fly.
The updated code looks like this:
import os
import sys
import vlc
if __name__ == '__main__':
#filepath = <either-some-url-or-local-path>
filepath = "http://r1---sn-nfpnnjvh-1gil.c.youtube.com/videoplayback?source=youtube&newshard=yes&fexp=936100%2C906397%2C928201%2C929117%2C929123%2C929121%2C929915%2C929906%2C929907%2C929125%2C929127%2C925714%2C929917%2C929919%2C912512%2C912515%2C912521%2C906838%2C904485%2C906840%2C931913%2C904830%2C919373%2C933701%2C904122%2C932216%2C936303%2C909421%2C912711%2C907228%2C935000&sver=3&expire=1373237257&mt=1373214031&mv=m&ratebypass=yes&id=1907b7271247a714&ms=au&ipbits=48&sparams=cp%2Cid%2Cip%2Cipbits%2Citag%2Cratebypass%2Csource%2Cupn%2Cexpire&itag=45&key=yt1&ip=2a02%3A120b%3Ac3c6%3A7190%3A6823%3Af2d%3A732c%3A3577&upn=z3zzcrvPC0U&cp=U0hWSFJOVV9KUUNONl9KSFlDOmt4Y3dEWFo3dDFu&signature=D6049FD7CD5FBD2CC6CD4D60411EE492AA0E9A77.5D0562CCF4E10A6CC53B62AAFFF6CB3BB0BA91C0"
movie = os.path.expanduser(filepath)
savedcopy = "yt-stream.mpg"
if 'http://' not in filepath:
if not os.access(movie, os.R_OK):
print ( 'Error: %s file is not readable' % movie )
sys.exit(1)
instance = vlc.Instance("--sout=#transcode{vcodec=mp4v,acodec=mpga,vb=800,ab=128,deinterlace}:duplicate{dst=file{dst=%s},dst=display}" % savedcopy)
try:
media = instance.media_new(movie)
except NameError:
print ('NameError: % (%s vs Libvlc %s)' % (sys.exc_info()[1],
vlc.__version__, vlc.libvlc_get_version()))
sys.exit(1)
player = instance.media_player_new()
player.set_media(media)
player.play()
#dont exit!
while(1):
continue
A couple of important points:
I've used MPEG audio and video codecs in the transcode directive. It seems to be important to use a matching extensions for the output file (mpg in this case). Otherwise VLC gets confused when opening the saved file for playback. Keep that in mind if you decide to switch to another video format.
You cannot add a regular YouTube URL as filepath. Instead you have to specify the location of the video itself. That's the reason why the filepath that I've used looks so cryptic. That filepath corresponds to video at http://www.youtube.com/watch?v=GQe3JxJHpxQ. VLC itself is able to extract the video location from a given YouTube URL, but libVLC doesn't do that out of the box. You'll have to write your own resolver to do that. See this related SO question. I followed this approach to manually resolve the video location for my tests.
I think you need to duplicate the output in order to play and record it at the same time:
vlc.Instance("--sub-source marq --sout=#stream_out_duplicate{dst=display,dst=std{access=file,mux=ts,dst=/path/file.mpg}}")
or
libvlc_media_add_option(media, ":sout=#stream_out_duplicate{dst=display,dst=std{access=file,mux=ts,dst=/path/file.mpg}}")
Did you try adding to the list of options the following option?
--sout-display
i.e.
instance = vlc.Instance("--sub-source marq --sout=file/ps:example.mpg --sout-display")
Some time ago in a sample code in the active state website i saw someone played and recorded a MP3 file using VLC using the vlc.py module. You can take a look at it's sample code to see how to duplicate a stream. I copied th code here for you (I copied it from http://code.activestate.com/recipes/577802-using-vlcpy-to-record-an-mp3-and-save-a-cue-file/):
import vlc
import time
import os
def new_filename(ext = '.mp3'):
"find a free filename in 00000000..99999999"
D = set(x[:8] for x in os.listdir('.')
if (x.endswith(ext) or x.endswith('.cue')) and len(x) == 12)
for i in xrange(10**8):
s = "%08i" %i
if s not in D:
return s
def initialize_cue_file(name,instream,audiofile):
"create a cue file and write some data, then return it"
cueout = '%s.cue' %name
outf = file(cueout,'w')
outf.write('PERFORMER "%s"\n' %instream)
outf.write('TITLE "%s"\n' %name)
outf.write('FILE "%s" WAVE\n' %audiofile)
outf.flush()
return outf
def initialize_player(instream, audiofile):
"initialize a vlc player which plays locally and saves to an mp3file"
inst = vlc.Instance()
p = inst.media_player_new()
cmd1 = "sout=#duplicate{dst=file{dst=%s},dst=display}" %audiofile
cmd2 ="no-sout-rtp-sap"
cmd3 = "no-sout-standard-sap"
cmd4 ="sout-keep"
med=inst.media_new(instream,cmd1,cmd2,cmd3,cmd4)
med.get_mrl()
p.set_media(med)
return p, med
def write_track_meta_to_cuefile(outf,instream,idx,meta,millisecs):
"write the next track info to the cue file"
outf.write(' TRACK %02i AUDIO\n' %idx)
outf.write(' TITLE "%s"\n' %meta)
outf.write(' PERFORMER "%s"\n' %instream)
m = millisecs // 60000
s = (millisecs - (m*60000)) // 1000
hs = (millisecs - (m*60000) - (s*1000)) //10
ts = '%02i:%02i:%02i' %(m,s,hs)
outf.write(' INDEX 01 %s\n' %ts)
outf.flush()
def test():
#some online audio stream for which this currently works ....
instream = 'http://streamer-mtc-aa05.somafm.com:80/stream/1018'
#if the output filename ends with mp3 vlc knows which mux to use
ext = '.mp3'
name = new_filename(ext)
audiofile = '%s%s' %(name,ext)
outf = initialize_cue_file(name,instream,audiofile)
p,med = initialize_player(instream, audiofile)
p.play()
np = None
i = 0
while 1:
time.sleep(.1)
new = med.get_meta(12)
if new != np:
i +=1
t = p.get_time()
print "millisecs: %i" %t
write_track_meta_to_cuefile(outf,instream,i,new,t)
np = new
print "now playing: %s" %np
if __name__=='__main__':
test()
Perhaps you need to clone your output, as suggested on the forum?