473,542 Members | 2,128 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Sun audio blocks, even when run in a thread

The class below is intended to play a Sun audio file (.au) in the
background while the main thread, which is servicing a GUI, continues
without impact. It doesn't work. For a sound file that takes 3-5
seconds to play, the main thread hangs for that long. I have run this
many times, with changes in printouts and insertion of strategic
sleeps to try to make sure that the player thread gives up control,
but apparently the call to audioObj.write( audioString ) is atomic --
NOTHING happens in the main thread until it returns. I have tested
this with print statements and sleeps in the main thread instead of a
GUI, and you can see the program's output simply halt while the sound
is audible. I have also looked for delays at dataLock.acquir e() and
not found any.

Help, suggestions, explanation or work-around??

Thanks.

Bruce Bon

_______________ _______________ _

import time
import sunaudiodev
from thread import *

class AudioPlayer:

def __init__( self, owner ):
'''Constructor. '''
self.soundQueue = []
self.terminateF lag = False
self.dataLock = allocate_lock()
print 'AudioPlayer: starting playerThread... '
print ' main thread ID = ', get_ident()
self.playerThre ad = start_new_threa d( self.__playerTh read, ()
)
def playAudio( self, audio ):
self.dataLock.a cquire()
self.soundQueue .append( audio ) # put to end of list
self.dataLock.r elease()

def terminate( self ):
self.dataLock.a cquire()
self.terminateF lag = True
self.dataLock.r elease()
time.sleep(1)

def __playerThread( self ):
'''Function to be executed in background thread, to play
sounds.'''
print '__playerThread () starting: ID = ', get_ident()
while True:
# Check terminateFlag and soundQueue
audio = None
self.dataLock.a cquire()
if self.terminateF lag:
self.dataLock.r elease()
print '__playerThread (): terminating playerThread... '
exit()
l = len(self.soundQ ueue)
if l > 0:
audio = self.soundQueue .pop(0) # get from beginning
of list
self.dataLock.r elease()

if audio == None:
time.sleep( 1.0 ) # poll queue 1/second
else:
# Read the .au file
auReadObj = open( audio, 'r' )
audioString = auReadObj.read( )
auReadObj.close ()

# Open the audio device and play the sound
try:
audioObj = sunaudiodev.ope n('w')
except sunaudiodev.err or:
print 'ERROR __playerThread: ' + \
'Failed to open Sun audio device.'
else:
audioObj.write( audioString )
audioObj.close( )
Jul 18 '05 #1
2 2486
I converted this module to using threading instead of thread -- same behavior.
Jul 18 '05 #2
[posted and mailed]

Br*******@Subar uTelescope.org (Bruce Bon) wrote in
news:18******** *************** ***@posting.goo gle.com:
The class below is intended to play a Sun audio file (.au) in the
background while the main thread, which is servicing a GUI, continues
without impact. It doesn't work. For a sound file that takes 3-5
seconds to play, the main thread hangs for that long. I have run this
many times, with changes in printouts and insertion of strategic
sleeps to try to make sure that the player thread gives up control,
but apparently the call to audioObj.write( audioString ) is atomic --
NOTHING happens in the main thread until it returns. I have tested
this with print statements and sleeps in the main thread instead of a
GUI, and you can see the program's output simply halt while the sound
is audible. I have also looked for delays at dataLock.acquir e() and
not found any.

Help, suggestions, explanation or work-around??
no sorry, not for your problem directly...
_if_ there is a bug in the python module. it maybe, if the sunaudiodev is
implemented in C and forgets to release the GIL during the io operation.
altough i doubt it somehow, bugs in python itself are rare....

but, i can comment on your code ;-)

look at the module "Queue" that would save you the lock and all its
problems if you doo it manualy. it has also a get() function that can
block, so you dont need your poll loop with a sleep.

if you insist on using locks, consider try: ... finally: clasues, with
lock.release() in the finally block, so that you dont produce a deadlock,
even on exceptions.

i always use the "threading" module. its much cleaner in my option. i have
seen you tried it too :-)

chris
import time
import sunaudiodev
from thread import *

class AudioPlayer:

def __init__( self, owner ):
'''Constructor. '''
self.soundQueue = []
self.terminateF lag = False
self.dataLock = allocate_lock()
print 'AudioPlayer: starting playerThread... '
print ' main thread ID = ', get_ident()
self.playerThre ad = start_new_threa d( self.__playerTh read, ()
)
def playAudio( self, audio ):
self.dataLock.a cquire()
self.soundQueue .append( audio ) # put to end of list
self.dataLock.r elease()

def terminate( self ):
self.dataLock.a cquire()
self.terminateF lag = True
self.dataLock.r elease()
time.sleep(1)

def __playerThread( self ):
'''Function to be executed in background thread, to play
sounds.'''
print '__playerThread () starting: ID = ', get_ident()
while True:
# Check terminateFlag and soundQueue
audio = None
self.dataLock.a cquire()
if self.terminateF lag:
self.dataLock.r elease()
print '__playerThread (): terminating playerThread... '
exit()
l = len(self.soundQ ueue)
if l > 0:
audio = self.soundQueue .pop(0) # get from beginning
of list
self.dataLock.r elease()

if audio == None:
time.sleep( 1.0 ) # poll queue 1/second
else:
# Read the .au file
auReadObj = open( audio, 'r' )
audioString = auReadObj.read( )
auReadObj.close ()

# Open the audio device and play the sound
try:
audioObj = sunaudiodev.ope n('w')
except sunaudiodev.err or:
print 'ERROR __playerThread: ' + \
'Failed to open Sun audio device.'
else:
audioObj.write( audioString )
audioObj.close( )


--
Chris <cl******@gmx.n et>

Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

20
5902
by: Hung Jung Lu | last post by:
Hi, I know people have talked about it before, but I am still really confused from reading the old messages. When I talk about code blocks, I am not talking about Lisp/Ruby/Perl, so I am not making comparisons. If you have a file, in Python you could do:
24
1952
by: Dave Benjamin | last post by:
Guido gave a good, long interview, available at IT Conversations, as was recently announced by Dr. Dobb's Python-URL! The audio clips are available here: http://www.itconversations.com/shows/detail545.html http://www.itconversations.com/shows/detail559.html I'd like to comment on a few parts of that interview. One thing Guido mentions...
7
5972
by: Noor | last post by:
please tell the technique of centralize exception handling without try catch blocks in c#.
1
4287
by: Ron Provost | last post by:
Hello, I'm developing a piece of software to assist illiteraate adults to learn to read. I'm trying to figure out how, if possible, to make audio playback asynchrnous but still controllable. I'm using python 2.4 with pymedia on XP. I started out with the example in the tutorials section of the pymedia website. The pymedia docs imply to...
1
2150
by: Laura T. | last post by:
Hi, I've this kind a program, using sockets to communicate with the clients. One of the clients can be a web browser (like IE). When using IE as a client, the transmission blocks completely, and IE times out after a long time while stating opening from http://localhost:7765... I have a main thread that starts TCPListener and listens and...
1
2141
by: JC | last post by:
Hi, I have to play a streaming audio. So in a thread I play audio as follow thread{ //some code for(;;){ //some code waveOutPrepareHeader(hwo, &(whdr), sizeof(WAVEHDR)); waveOutWrite(hwo, &(whdr), sizeof(WAVEHDR));
0
2218
by: smimon | last post by:
Hi I'm trying to run a DTS package from a ASP.NET web page using System.Diagnostics.Process. This DTS takes up to 10 minutes to complete, during which, output is generated which i would like to trap and output to a client. Having read a bit of literature about this, i realise that it is necessary to start a new thread to report on the...
8
14926
by: raylopez99 | last post by:
I have the latest version of Visual Studio 2008 Professional, which allows you to create resource files (this is the .resx file, no?), unlike the Express version, which does not. I am trying to cut and paste code that MSDN recommends for playing a simple wav file from inside an embedded file, like presumeably the 'resources' file .resx is. ...
3
3437
by: AWW | last post by:
Using XP and VB 2005, it seemed like a good idea to save audio in the clipboard and then play it with backgroundworker. Cannot find a good Clipboard audio example anywhere - just SetAudio and GetAudio. And an example seems to do a SwapAudio which makes no sense. Basically I want to spool or simulate spooling of audio. So is this reasonable...
0
7571
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7721
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7670
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5867
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5246
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4880
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
1798
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
943
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
620
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.