Skip to content

Commit

Permalink
Merge pull request #2 from bochecha/master
Browse files Browse the repository at this point in the history
Make pycanberra work with both Python 2 and 3
  • Loading branch information
totdb committed May 15, 2013
2 parents 65c3b3f + e110481 commit 88c53cd
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions pycanberra.py
Expand Up @@ -4,9 +4,20 @@
# License: LGPL 2.1
##########################################################################
from ctypes import *
import exceptions
import time

# This is inspired by the six module: http://pypi.python.org/pypi/six
import sys
if sys.version_info.major == 3:
string_types = str,
def b(s):
return s.encode("latin-1")
else:
string_types = basestring,
def b(s):
return s


# /**
# * CA_PROP_MEDIA_NAME:
# *
Expand Down Expand Up @@ -519,16 +530,16 @@ def GetApi():
# int ca_proplist_set(ca_proplist *p, const char *key, const void *data, size_t nbytes);


class CanberraException(exceptions.Exception):
class CanberraException(Exception):
def __init__(self, err, *args, **kwargs):
self._err = err
super(exceptions.Exception, self).__init__(*args, **kwargs)
super(Exception, self).__init__(*args, **kwargs)

def get_error(self):
return self._err

def __str__(self):
return super(exceptions.Exception, self).__str__() + " (error %d)" % self._err
return super(Exception, self).__str__() + " (error %d)" % self._err


class Canberra(object):
Expand Down Expand Up @@ -557,6 +568,8 @@ def destroy(self):
raise CanberraException(res, "Failed to destroy context")

def change_props(self, *args):
args = tuple(b(arg) if isinstance(arg, string_types) else arg
for arg in args)
res = GetApi().ca_context_change_props(self._handle, *args)
if res != CA_SUCCESS:
raise CanberraException(res, "Failed to change props")
Expand All @@ -574,11 +587,15 @@ def cache_full(self, props):
pass

def play(self, playId, *args):
args = tuple(b(arg) if isinstance(arg, string_types) else arg
for arg in args)
res = GetApi().ca_context_play(self._handle, playId, *args)
if res != CA_SUCCESS:
raise CanberraException(res, "Failed to play!")

def cache(self, *args):
args = tuple(b(arg) if isinstance(arg, string_types) else arg
for arg in args)
res = GetApi().ca_context_cache(self._handle, *args)
if res != CA_SUCCESS:
raise CanberraException(res, "Failed to cache")
Expand All @@ -597,6 +614,8 @@ def playing(self, playId):

def easy_play_sync(self, eventName):
""" play an event sound synchronously """
if isinstance(eventName, string_types):
eventName = b(eventName)
self.play(1,
CA_PROP_EVENT_ID, eventName,
None)
Expand Down

0 comments on commit 88c53cd

Please sign in to comment.