Beispiel #1
0
def get_devices():
    dev_list, dev_index = pyo.pa_get_output_devices()
    res = []
    for idx, dev_name in enumerate(dev_list):
        res.append(
            dict(idx=dev_index[idx],
                 name=dev_name,
                 channels=pyo.pa_get_output_max_channels(dev_index[idx])))
    return res
Beispiel #2
0
def soundInit(device=''):
    global soundPresent, mixer, server, pyoPresent
    try:
        pa_device_index = Ice.Application.communicator().getProperties().getPropertyWithDefault('RenderingEngine.PADevice', None)
    except:
        pa_device_index = None

    if pyoPresent:
        try:
            pyo.pa_list_devices()
            server = pyo.Server()
            server.setDuplex(0)
            pai = None
            if pa_device_index:
                try:
                    pai = int(pa_device_index)
                    server.setOutputDevice(pai)
                    Logger.trace("info", "Sound system using device" + str(pai) + " (was defined in RenderingEngine.PADevice)")
                except:
                    Logger.warning("Sound system was passed an invalid device from ICE, trying default device")
            if not pai and hasattr(pyo, "PYO_VERSION") and pyo.PYO_VERSION == "0.4.0": # only try to use ASIO if the new version of pyo is installed
                out_devices = pyo.pa_get_output_devices()
                od_index = 0
                for od in out_devices[0]:
                    if "ASIO" in od:
                        pai = int(out_devices[1][od_index])
                        server.setOutputDevice(pai)
                        Logger.trace("info", "Found ASIO device, using device " + str(pai))                        
                        break
                    od_index += 1
            if not pai:
                Logger.trace("info", "Sound system using default device " + str(pyo.pa_get_default_output()))
            server.boot()
            server.start()
            if server.getIsStarted() == 0:
                Logger.warning("Sound has not started up, trying mono")
                server.setNchnls(1)
                server.boot()
                server.start()
            if server.getIsStarted() == 0:
                Logger.warning("Sound has still not started up, giving up")
                soundPresent = False
            else:
    #            server.gui(locals())
                mixer = pyo.Mixer()
                mixer.out()
                soundPresent = True
                Logger.trace("info", "Sound system up and running")
        except:
            Logger.warning("SoundInit failed, pyaudio could not initialise, sound will not be available")
            soundPresent = False
            raise
    if not soundPresent:
        Logger.warning("pyo is not present, sound will not be available")
Beispiel #3
0
 def GetAudioOutputs(self):
     if not hasattr(self, '_audio_outputs'):
         output_device_names, output_device_indexes = pyo.pa_get_output_devices()
         default_output_index = pyo.pa_get_default_output()
         audio_outputs = {}
         for output_index, output_name in zip(output_device_indexes, output_device_names):
             output_max_channels = pyo.pa_get_output_max_channels(output_index)
             audio_outputs[output_index] = {
                 'name': output_name,
                 'default': bool(output_index == default_output_index),
                 'channels': output_max_channels,
             }
         setattr(self, '_audio_outputs', audio_outputs)
     return getattr(self, '_audio_outputs')
Beispiel #4
0
 def getAvailableAudioMidiDrivers(self):
     inputDriverList, inputDriverIndexes = pa_get_input_devices()
     selectedInputDriver = inputDriverList[inputDriverIndexes.index(
         pa_get_default_input())]
     outputDriverList, outputDriverIndexes = pa_get_output_devices()
     selectedOutputDriver = outputDriverList[outputDriverIndexes.index(
         pa_get_default_output())]
     midiDriverList, midiDriverIndexes = pm_get_input_devices()
     if midiDriverList == []:
         selectedMidiDriver = ""
     else:
         selectedMidiDriver = midiDriverList[midiDriverIndexes.index(
             pm_get_default_input())]
     return inputDriverList, selectedInputDriver, outputDriverList, selectedOutputDriver, midiDriverList, selectedMidiDriver
Beispiel #5
0
def getAvailableAudioMidiDrivers():
    inputDriverList, inputDriverIndexes = pa_get_input_devices()
    defaultInputDriver = inputDriverList[inputDriverIndexes.index(
        pa_get_default_input())]
    outputDriverList, outputDriverIndexes = pa_get_output_devices()
    defaultOutputDriver = outputDriverList[outputDriverIndexes.index(
        pa_get_default_output())]
    midiDriverList, midiDriverIndexes = pm_get_input_devices()
    if midiDriverList == []:
        defaultMidiDriver = ""
    else:
        defaultMidiDriver = midiDriverList[midiDriverIndexes.index(
            pm_get_default_input())]
    return inputDriverList, inputDriverIndexes, defaultInputDriver, outputDriverList, outputDriverIndexes, \
            defaultOutputDriver, midiDriverList, midiDriverIndexes, defaultMidiDriver
Beispiel #6
0
    def __init__(self):
        """Constructor for music_player"""
        """Make sure to call add_gui once initialized"""
        self.instruments = [] #instrument/track volume is here
        self.tempo = 120.0 #BPM (for now)
        self.global_volume = 0.75 #between 0 and 1
        self.page_index = 0 #1st page
        self.play_all = False
        self.playhead_index = 0
        self.beat_index = 0

        self.server = Server(duplex=0)
        """Set proper output device for latency-free playback on Windows"""
        """Source: https://groups.google.com/d/msg/pyo-discuss/9fvFiGbch3c/tzJTfbpLUY8J"""
        if platform.system() == "Windows":
            out_devices = pa_get_output_devices()
            od_index = 0
            for od in out_devices[0]:
                if "Primary Sound Driver" in od:
                    pai = int(out_devices[1][od_index])
                    self.server.setOutputDevice(pai)
                    break
                od_index += 1

        self.server.boot()
        self.server.start()

        metronome_time = self.SECONDS_PER_MIN / self.tempo
        self.metronome = Metro(time=metronome_time)
        self.metronome_callback = TrigFunc(self.metronome, function=self.step)
        
        # Create instruments
        wavetable_a = WaveInstrument(self, WaveInstrument.BASS)
        wavetable_b = WaveInstrument(self, WaveInstrument.LEAD)
        drums = DrumInstrument(self)
        
        self.instruments.append(wavetable_a)
        self.instruments.append(wavetable_b)
        self.instruments.append(drums)

        self.mixer_setup()
Beispiel #7
0
def getAvailableAudioMidiDrivers():
    inDefault = pa_get_default_input()
    inDriverList, inDriverIndexes = pa_get_input_devices()
    if inDefault in inDriverIndexes:
        defaultInputDriver = inDriverList[inDriverIndexes.index(inDefault)]
    else:
        defaultInputDriver = ""
    outDriverList, outDriverIndexes = pa_get_output_devices()
    outDefault = pa_get_default_output()
    if outDefault in outDriverIndexes:
        defaultOutputDriver = outDriverList[outDriverIndexes.index(outDefault)]
    else:
        defaultOutputDriver = ""
    midiDefault = pm_get_default_input()
    midiDriverList, midiDriverIndexes = pm_get_input_devices()
    if midiDefault in midiDriverIndexes:
        defaultMidiDriver = midiDriverList[midiDriverIndexes.index(midiDefault)]
    else:
        defaultMidiDriver = ""
    return (inDriverList, inDriverIndexes, defaultInputDriver,
            outDriverList, outDriverIndexes, defaultOutputDriver,
            midiDriverList, midiDriverIndexes, defaultMidiDriver)
Beispiel #8
0
def getAvailableAudioMidiDrivers():
    inDefault = pa_get_default_input()
    inDriverList, inDriverIndexes = pa_get_input_devices()
    if inDefault in inDriverIndexes:
        defaultInputDriver = inDriverList[inDriverIndexes.index(inDefault)]
    else:
        defaultInputDriver = ""
    outDriverList, outDriverIndexes = pa_get_output_devices()
    outDefault = pa_get_default_output()
    if outDefault in outDriverIndexes:
        defaultOutputDriver = outDriverList[outDriverIndexes.index(outDefault)]
    else:
        defaultOutputDriver = ""
    midiDefault = pm_get_default_input()
    midiDriverList, midiDriverIndexes = pm_get_input_devices()
    if midiDefault in midiDriverIndexes:
        defaultMidiDriver = midiDriverList[midiDriverIndexes.index(midiDefault)]
    else:
        defaultMidiDriver = ""
    return (inDriverList, inDriverIndexes, defaultInputDriver,
            outDriverList, outDriverIndexes, defaultOutputDriver,
            midiDriverList, midiDriverIndexes, defaultMidiDriver)
Beispiel #9
0
    def _GetDevicesDict(self):
        pa_input = pyo.pa_get_input_devices()
        pa_output = pyo.pa_get_output_devices()
        pm_input = pyo.pm_get_input_devices()
        pm_output = pyo.pm_get_output_devices()

        i = 0
        pa_input_list = []
        for d in pa_input[0]:
            pa_input_list.append([i, d])
            i += 1

        i = 0
        pa_output_list = []
        for d in pa_output[0]:
            pa_output_list.append([i, d])
            i += 1

        i = 0
        pm_input_list = []
        for d in pm_input[0]:
            pm_input_list.append([i, d])
            i += 1

        i = 0
        pm_output_list = []
        for d in pm_output[0]:
            pm_output_list.append([i, d])
            i += 1

        return {
            'a_input': pa_input_list,
            'a_output': pa_output_list,
            'm_input': pm_input_list,
            'm_output': pm_output_list
        }
Beispiel #10
0
def init(rate=44100, stereo=True, buffer=128):
    """setup the pyo (sound) server
    """
    global pyoSndServer, Sound, audioDriver, duplex, maxChnls
    Sound = SoundPyo
    global pyo
    try:
        assert pyo
    except NameError:  # pragma: no cover
        import pyo
        # can be needed for microphone.switchOn(), which calls init even
        # if audioLib is something else

    # subclass the pyo.Server so that we can insert a __del__ function that
    # shuts it down skip coverage since the class is never used if we have
    # a recent version of pyo

    class _Server(pyo.Server):  # pragma: no cover
        # make libs class variables so they don't get deleted first
        core = core
        logging = logging

        def __del__(self):
            self.stop()
            # make sure enough time passes for the server to shutdown
            self.core.wait(0.5)
            self.shutdown()
            # make sure enough time passes for the server to shutdown
            self.core.wait(0.5)
            # this may never get printed
            self.logging.debug('pyo sound server shutdown')

    if '.'.join(map(str, pyo.getVersion())) < '0.6.4':
        Server = _Server
    else:
        Server = pyo.Server

    # if we already have a server, just re-initialize it
    if 'pyoSndServer' in globals() and hasattr(pyoSndServer, 'shutdown'):
        pyoSndServer.stop()
        # make sure enough time passes for the server to shutdown
        core.wait(0.5)
        pyoSndServer.shutdown()
        core.wait(0.5)
        pyoSndServer.reinit(sr=rate,
                            nchnls=maxChnls,
                            buffersize=buffer,
                            audio=audioDriver)
        pyoSndServer.boot()
    else:
        if platform == 'win32':
            # check for output device/driver
            devNames, devIDs = pyo.pa_get_output_devices()
            audioDriver, outputID = _bestDriver(devNames, devIDs)
            if outputID is None:
                # using the default output because we didn't find the one(s)
                # requested
                audioDriver = 'Windows Default Output'
                outputID = pyo.pa_get_default_output()
            if outputID is not None:
                logging.info('Using sound driver: %s (ID=%i)' %
                             (audioDriver, outputID))
                maxOutputChnls = pyo.pa_get_output_max_channels(outputID)
            else:
                logging.warning(
                    'No audio outputs found (no speakers connected?')
                return -1
            # check for valid input (mic)
            # If no input device is available, devNames and devIDs are empty
            # lists.
            devNames, devIDs = pyo.pa_get_input_devices()
            audioInputName, inputID = _bestDriver(devNames, devIDs)
            # Input devices were found, but requested devices were not found
            if len(devIDs) > 0 and inputID is None:
                defaultID = pyo.pa_get_default_input()
                if defaultID is not None and defaultID != -1:
                    # default input is found
                    # use the default input because we didn't find the one(s)
                    # requested
                    audioInputName = 'Windows Default Input'
                    inputID = defaultID
                else:
                    # default input is not available
                    inputID = None
            if inputID is not None:
                msg = 'Using sound-input driver: %s (ID=%i)'
                logging.info(msg % (audioInputName, inputID))
                maxInputChnls = pyo.pa_get_input_max_channels(inputID)
                duplex = bool(maxInputChnls > 0)
            else:
                maxInputChnls = 0
                duplex = False
        # for other platforms set duplex to True (if microphone is available)
        else:
            audioDriver = prefs.general['audioDriver'][0]
            maxInputChnls = pyo.pa_get_input_max_channels(
                pyo.pa_get_default_input())
            maxOutputChnls = pyo.pa_get_output_max_channels(
                pyo.pa_get_default_output())
            duplex = bool(maxInputChnls > 0)

        maxChnls = min(maxInputChnls, maxOutputChnls)
        if maxInputChnls < 1:  # pragma: no cover
            msg = ('%s.init could not find microphone hardware; '
                   'recording not available')
            logging.warning(msg % __name__)
            maxChnls = maxOutputChnls
        if maxOutputChnls < 1:  # pragma: no cover
            msg = ('%s.init could not find speaker hardware; '
                   'sound not available')
            logging.error(msg % __name__)
            return -1

        # create the instance of the server:
        if platform in ['darwin', 'linux2']:
            # for mac/linux we set the backend using the server audio param
            pyoSndServer = Server(sr=rate,
                                  nchnls=maxChnls,
                                  buffersize=buffer,
                                  audio=audioDriver)
        else:
            # with others we just use portaudio and then set the OutputDevice
            # below
            pyoSndServer = Server(sr=rate, nchnls=maxChnls, buffersize=buffer)

        pyoSndServer.setVerbosity(1)
        if platform == 'win32':
            pyoSndServer.setOutputDevice(outputID)
            if inputID is not None:
                pyoSndServer.setInputDevice(inputID)
        # do other config here as needed (setDuplex? setOutputDevice?)
        pyoSndServer.setDuplex(duplex)
        pyoSndServer.boot()
    core.wait(0.5)  # wait for server to boot before starting te sound stream
    pyoSndServer.start()
    try:
        Sound()  # test creation, no play
    except pyo.PyoServerStateException:
        msg = "Failed to start pyo sound Server"
        if platform == 'darwin' and audioDriver != 'portaudio':
            msg += "; maybe try prefs.general.audioDriver 'portaudio'?"
        logging.error(msg)
        core.quit()
    logging.debug('pyo sound server started')
    logging.flush()
Beispiel #11
0
def initPyo(rate=44100, stereo=True, buffer=128):
    """setup the pyo (sound) server
    """
    global pyoSndServer, Sound, audioDriver, duplex, maxChnls
    Sound = SoundPyo
    global pyo
    try:
        assert pyo
    except NameError:  # pragma: no cover
        import pyo  # microphone.switchOn() calls initPyo even if audioLib is something else
    #subclass the pyo.Server so that we can insert a __del__ function that shuts it down
    # skip coverage since the class is never used if we have a recent version of pyo
    class _Server(pyo.Server):  # pragma: no cover
        core=core #make libs class variables so they don't get deleted first
        logging=logging
        def __del__(self):
            self.stop()
            self.core.wait(0.5)#make sure enough time passes for the server to shutdown
            self.shutdown()
            self.core.wait(0.5)#make sure enough time passes for the server to shutdown
            self.logging.debug('pyo sound server shutdown')#this may never get printed
    if '.'.join(map(str, pyo.getVersion())) < '0.6.4':
        Server = _Server
    else:
        Server = pyo.Server

    # if we already have a server, just re-initialize it
    if 'pyoSndServer' in globals() and hasattr(pyoSndServer,'shutdown'):
        pyoSndServer.stop()
        core.wait(0.5)#make sure enough time passes for the server to shutdown
        pyoSndServer.shutdown()
        core.wait(0.5)
        pyoSndServer.reinit(sr=rate, nchnls=maxChnls, buffersize=buffer, audio=audioDriver)
        pyoSndServer.boot()
    else:
        if platform=='win32':
            #check for output device/driver
            devNames, devIDs=pyo.pa_get_output_devices()
            audioDriver,outputID=_bestDriver(devNames, devIDs)
            if outputID is None:
                audioDriver = 'Windows Default Output' #using the default output because we didn't find the one(s) requested
                outputID = pyo.pa_get_default_output()
            if outputID is not None:
                logging.info('Using sound driver: %s (ID=%i)' %(audioDriver, outputID))
                maxOutputChnls = pyo.pa_get_output_max_channels(outputID)
            else:
                logging.warning('No audio outputs found (no speakers connected?')
                return -1
            #check for valid input (mic)
            devNames, devIDs = pyo.pa_get_input_devices()
            audioInputName, inputID = _bestDriver(devNames, devIDs)
            if inputID is None:
                audioInputName = 'Windows Default Input' #using the default input because we didn't find the one(s) requested
                inputID = pyo.pa_get_default_input()
            if inputID is not None:
                logging.info('Using sound-input driver: %s (ID=%i)' %(audioInputName, inputID))
                maxInputChnls = pyo.pa_get_input_max_channels(inputID)
                duplex = bool(maxInputChnls > 0)
            else:
                maxInputChnls = 0
                duplex=False
        else:#for other platforms set duplex to True (if microphone is available)
            audioDriver = prefs.general['audioDriver'][0]
            maxInputChnls = pyo.pa_get_input_max_channels(pyo.pa_get_default_input())
            maxOutputChnls = pyo.pa_get_output_max_channels(pyo.pa_get_default_output())
            duplex = bool(maxInputChnls > 0)

        maxChnls = min(maxInputChnls, maxOutputChnls)
        if maxInputChnls < 1:  # pragma: no cover
            logging.warning('%s.initPyo could not find microphone hardware; recording not available' % __name__)
            maxChnls = maxOutputChnls
        if maxOutputChnls < 1:  # pragma: no cover
            logging.error('%s.initPyo could not find speaker hardware; sound not available' % __name__)
            return -1

        # create the instance of the server:
        if platform in ['darwin', 'linux2']:
            #for mac/linux we set the backend using the server audio param
            pyoSndServer = Server(sr=rate, nchnls=maxChnls, buffersize=buffer, audio=audioDriver)
        else:
            #with others we just use portaudio and then set the OutputDevice below
            pyoSndServer = Server(sr=rate, nchnls=maxChnls, buffersize=buffer)

        pyoSndServer.setVerbosity(1)
        if platform=='win32':
            pyoSndServer.setOutputDevice(outputID)
            if inputID is not None:
                pyoSndServer.setInputDevice(inputID)
        #do other config here as needed (setDuplex? setOutputDevice?)
        pyoSndServer.setDuplex(duplex)
        pyoSndServer.boot()
    core.wait(0.5)#wait for server to boot before starting te sound stream
    pyoSndServer.start()
    try:
        Sound()  # test creation, no play
    except pyo.PyoServerStateException:
        msg = "Failed to start pyo sound Server"
        if platform == 'darwin' and audioDriver != 'portaudio':
            msg += "; maybe try prefs.general.audioDriver 'portaudio'?"
        logging.error(msg)
        core.quit()
    logging.debug('pyo sound server started')
    logging.flush()
Beispiel #12
0
    def __init__(self, view):
        """Controller Class

        Arguments
        ----------
        view : Class view
            MVC
        Parameters
        ----------
        camera : camera.Camera()
            camera init
        previous_angle : int
            previous detected angle
        feat : np.ndarray
            [pos, radius, theme]
        stone_feat : np.ndarray
            [pos, radius, theme]
        contour_config_v : int
            erode and dilate iter value
        output_device_index : int
            number of output devices
        path_finder : []
            List of sonic anchors in scene
        calibration_pts : []
            Calibrated Points (edges of the sandbox)
        path_finder_max : int
            max number of sonic anchors in scene
        min_move : int
            init value of moving steps in pixels
        stop_flag_init : bool
            init vaule of stop playining music flag
        stop_flag : bool
            opposit of stop playining music flag after init is set
        music_playing_flag : bool
            mixer stop music flag
        stones_act_flag : bool
            Stone wave animation flag
        time_stamp_activation = time.time()
            Time stamp for timing, several usage
        stop_time : time.time()
            Timer for stop fading out and in e.g.
        start_time : time.time()
            Timer for stop fading out and in e.g.
        audio_controller : AudioController()
            AudioController Instance
        cap : np.ndarray
            Image cap frame
        c_saveimg : int
            iterator for naming saved image file
        logs : Logs()
            logs instance for saving params

        """
        import matplotlib
        print "cv2"+cv2.__version__
        print "usb"+usb.__version__
        print "matplotlib"+matplotlib.__version__

        self.view = view
        self.camera = camera.Camera()
        self.view.register(self)
        # self.previous_angle = 0
        self.feat = None
        self.stone_feat = None
        self.contour_config_v = 2
        self.output_device_index = 0
        self.path_finder = []
        self.calibration_pts = []
        self.path_finder_max = 5
        self.min_move = 0
        self.stop_flag_init = True
        self.stop_flag = False
        self.music_playing_flag = False
        self.stones_act_flag = False
        self.time_stamp_activation = time.time()
        self.stop_time = time.time()
        self.start_time = time.time()
        self.audio_controller = None
        self.cap = None
        self.c_saveimg = 0
        self.maxVol = 80
        # self.logs = Logs()
        for i in range(0,self.path_finder_max):
            self.path_finder.append(pfc.PathFinder())
            self.path_finder[i].set_current_point(randint(100,250),randint(100,250))
        self.snapshot_trigger = False
        view.setSliderDefault()
        n_out_channel = pa_get_output_max_channels(self.output_device_index+1)
        self.devicelist = pa_get_output_devices()

        self.updateDeviceList()
        self.sched_device = Scheduler()
        self.sched_device.start()
        self.sched_device.add_interval_job(self.updateDeviceList, seconds=20)

        self.theme = audio_theme.AudioTheme('water')
        self.view.register_buttons()
        self.view.show()
Beispiel #13
0
def initPyo(rate=44100, stereo=True, buffer=128):
    """setup the pyo (sound) server
    """
    global pyoSndServer, Sound, audioDriver, duplex, maxChnls
    Sound = SoundPyo
    if not "pyo" in locals():
        import pyo  # microphone.switchOn() calls initPyo even if audioLib is something else
    # subclass the pyo.Server so that we can insert a __del__ function that shuts it down
    class _Server(pyo.Server):
        core = core  # make libs class variables so they don't get deleted first
        logging = logging

        def __del__(self):
            self.stop()
            self.core.wait(0.5)  # make sure enough time passes for the server to shutdown
            self.shutdown()
            self.core.wait(0.5)  # make sure enough time passes for the server to shutdown
            self.logging.debug("pyo sound server shutdown")  # this may never get printed

    if ".".join(map(str, pyo.getVersion())) < "0.6.4":
        Server = _Server
    else:
        Server = pyo.Server

    # if we already have a server, just re-initialize it
    if globals().has_key("pyoSndServer") and hasattr(pyoSndServer, "shutdown"):
        pyoSndServer.stop()
        core.wait(0.5)  # make sure enough time passes for the server to shutdown
        pyoSndServer.shutdown()
        core.wait(0.5)
        pyoSndServer.reinit(sr=rate, nchnls=maxChnls, buffersize=buffer, audio=audioDriver)
        pyoSndServer.boot()
    else:
        if platform == "win32":
            # check for output device/driver
            devNames, devIDs = pyo.pa_get_output_devices()
            audioDriver, outputID = _bestDriver(devNames, devIDs)
            if outputID:
                logging.info("Using sound driver: %s (ID=%i)" % (audioDriver, outputID))
                maxOutputChnls = pyo.pa_get_output_max_channels(outputID)
            else:
                logging.warning("No audio outputs found (no speakers connected?")
                return -1
            # check for valid input (mic)
            devNames, devIDs = pyo.pa_get_input_devices()
            audioInputName, inputID = _bestDriver(devNames, devIDs)
            if inputID is not None:
                logging.info("Using sound-input driver: %s (ID=%i)" % (audioInputName, inputID))
                maxInputChnls = pyo.pa_get_input_max_channels(inputID)
                duplex = bool(maxInputChnls > 0)
            else:
                duplex = False
        else:  # for other platforms set duplex to True (if microphone is available)
            audioDriver = prefs.general["audioDriver"][0]
            maxInputChnls = pyo.pa_get_input_max_channels(pyo.pa_get_default_input())
            maxOutputChnls = pyo.pa_get_output_max_channels(pyo.pa_get_default_output())
            duplex = bool(maxInputChnls > 0)

        maxChnls = min(maxInputChnls, maxOutputChnls)
        if maxInputChnls < 1:
            logging.warning("%s.initPyo could not find microphone hardware; recording not available" % __name__)
            maxChnls = maxOutputChnls
        if maxOutputChnls < 1:
            logging.error("%s.initPyo could not find speaker hardware; sound not available" % __name__)
            return -1

        # create the instance of the server:
        if platform in ["darwin", "linux2"]:
            # for mac/linux we set the backend using the server audio param
            pyoSndServer = Server(sr=rate, nchnls=maxChnls, buffersize=buffer, audio=audioDriver)
        else:
            # with others we just use portaudio and then set the OutputDevice below
            pyoSndServer = Server(sr=rate, nchnls=maxChnls, buffersize=buffer)

        pyoSndServer.setVerbosity(1)
        if platform == "win32":
            pyoSndServer.setOutputDevice(outputID)
            if inputID:
                pyoSndServer.setInputDevice(inputID)
        # do other config here as needed (setDuplex? setOutputDevice?)
        pyoSndServer.setDuplex(duplex)
        pyoSndServer.boot()
    core.wait(0.5)  # wait for server to boot before starting te sound stream
    pyoSndServer.start()
    try:
        Sound()  # test creation, no play
    except pyo.PyoServerStateException:
        msg = "Failed to start pyo sound Server"
        if platform == "darwin" and audioDriver != "portaudio":
            msg += "; maybe try prefs.general.audioDriver 'portaudio'?"
        logging.error(msg)
        core.quit()
    logging.debug("pyo sound server started")
    logging.flush()
Beispiel #14
0
def initPyo(rate=44100, stereo=True, buffer=128):
    """setup the pyo (sound) server
    """
    global pyoSndServer, Sound, audioDriver, duplex
    Sound = SoundPyo
    #subclass the pyo.Server so that we can insert a __del__ function that shuts it down
    class Server(pyo.Server):
        core=core #make libs class variables so they don't get deleted first
        logging=logging
        def __del__(self):
            self.stop()
            self.core.wait(0.5)#make sure enough time passes for the server to shutdown
            self.shutdown()
            self.core.wait(0.5)#make sure enough time passes for the server to shutdown
            self.logging.debug('pyo sound server shutdown')#this may never get printed

    #check if we already have a server and kill it
    if hasattr(pyoSndServer,'shutdown'):
        #this doesn't appear to work!
        pyoSndServer.stop()
        core.wait(0.5)#make sure enough time passes for the server to shutdown
        pyoSndServer.shutdown()
        pyoSndServer.reinit(sr=rate, nchnls=2, buffersize=buffer, duplex=1, audio=audioDriver)
        pyoSndServer.boot()
    else:
        #create the instance of the server
        if platform=='win32':
            #check for output device/driver
            devNames, devIDs=pyo.pa_get_output_devices()
            audioDriver,outputID=_bestDriver(devNames, devIDs)
            if outputID:
                logging.info('Using sound driver: %s (ID=%i)' %(audioDriver, outputID))
            else:
                logging.warning('No audio outputs found (no speakers connected?')
                return -1
            #check for valid input (mic)
            devNames, devIDs = pyo.pa_get_input_devices()
            junk, inputID=_bestDriver(devNames, devIDs)
            if inputID:
                duplex=True
            else:
                duplex=False
        else:#for other platforms set duplex to True
            audioDriver = prefs.general['audioDriver'][0]
            duplex=True
        if platform=='darwin':
            #for mac we set the backend using the server audio param
            pyoSndServer = Server(sr=rate, nchnls=2, buffersize=buffer, audio=audioDriver, duplex=duplex)
        else:
            #with others we just use portaudio and then set the OutputDevice below
            pyoSndServer = Server(sr=rate, nchnls=2, buffersize=buffer, duplex=duplex)
        pyoSndServer.setVerbosity(1)
        if platform=='win32':
            pyoSndServer.setOutputDevice(outputID)
            if inputID:
                pyoSndServer.setInputDevice(inputID)
        #do other config here as needed (setDuplex? setOutputDevice?)
        pyoSndServer.boot()
    core.wait(0.5)#wait for server to boot before starting te sound stream
    pyoSndServer.start()
    logging.debug('pyo sound server started')
    logging.flush()
Beispiel #15
0
def initPyo(rate=44100, stereo=True, buffer=128):
    """setup the pyo (sound) server
    """
    global pyoSndServer, Sound, audioDriver, duplex, maxChnls
    Sound = SoundPyo
    if not 'pyo' in locals():
        import pyo  # microphone.switchOn() calls initPyo even if audioLib is something else
    #subclass the pyo.Server so that we can insert a __del__ function that shuts it down
    class _Server(pyo.Server):
        core=core #make libs class variables so they don't get deleted first
        logging=logging
        def __del__(self):
            self.stop()
            self.core.wait(0.5)#make sure enough time passes for the server to shutdown
            self.shutdown()
            self.core.wait(0.5)#make sure enough time passes for the server to shutdown
            self.logging.debug('pyo sound server shutdown')#this may never get printed
    if '.'.join(map(str, pyo.getVersion())) < '0.6.4':
        Server = _Server
    else:
        Server = pyo.Server

    # if we already have a server, just re-initialize it
    if globals().has_key('pyoSndServer') and hasattr(pyoSndServer,'shutdown'):
        pyoSndServer.stop()
        core.wait(0.5)#make sure enough time passes for the server to shutdown
        pyoSndServer.shutdown()
        core.wait(0.5)
        pyoSndServer.reinit(sr=rate, nchnls=maxChnls, buffersize=buffer, audio=audioDriver)
        pyoSndServer.boot()
    else:
        if platform=='win32':
            #check for output device/driver
            devNames, devIDs=pyo.pa_get_output_devices()
            audioDriver,outputID=_bestDriver(devNames, devIDs)
            if outputID:
                logging.info('Using sound driver: %s (ID=%i)' %(audioDriver, outputID))
                maxOutputChnls = pyo.pa_get_output_max_channels(outputID)
            else:
                logging.warning('No audio outputs found (no speakers connected?')
                return -1
            #check for valid input (mic)
            devNames, devIDs = pyo.pa_get_input_devices()
            audioInputName, inputID = _bestDriver(devNames, devIDs)
            if inputID is not None:
                logging.info('Using sound-input driver: %s (ID=%i)' %(audioInputName, inputID))
                maxInputChnls = pyo.pa_get_input_max_channels(inputID)
                duplex = bool(maxInputChnls > 0)
            else:
                duplex=False
        else:#for other platforms set duplex to True (if microphone is available)
            audioDriver = prefs.general['audioDriver'][0]
            maxInputChnls = pyo.pa_get_input_max_channels(pyo.pa_get_default_input())
            maxOutputChnls = pyo.pa_get_output_max_channels(pyo.pa_get_default_output())
            duplex = bool(maxInputChnls > 0)

        maxChnls = min(maxInputChnls, maxOutputChnls)
        if maxInputChnls < 1:
            logging.warning('%s.initPyo could not find microphone hardware; recording not available' % __name__)
            maxChnls = maxOutputChnls
        if maxOutputChnls < 1:
            logging.error('%s.initPyo could not find speaker hardware; sound not available' % __name__)
            return -1

        # create the instance of the server:
        if platform=='darwin':
            #for mac we set the backend using the server audio param
            pyoSndServer = Server(sr=rate, nchnls=maxChnls, buffersize=buffer, audio=audioDriver)
        else:
            #with others we just use portaudio and then set the OutputDevice below
            pyoSndServer = Server(sr=rate, nchnls=maxChnls, buffersize=buffer)

        pyoSndServer.setVerbosity(1)
        if platform=='win32':
            pyoSndServer.setOutputDevice(outputID)
            if inputID:
                pyoSndServer.setInputDevice(inputID)
        #do other config here as needed (setDuplex? setOutputDevice?)
        pyoSndServer.setDuplex(duplex)
        pyoSndServer.boot()
    core.wait(0.5)#wait for server to boot before starting te sound stream
    pyoSndServer.start()
    try:
        Sound()  # test creation, no play
    except pyo.PyoServerStateException:
        msg = "Failed to start pyo sound Server"
        if platform == 'darwin' and audioDriver != 'portaudio':
            msg += "; maybe try prefs.general.audioDriver 'portaudio'?"
        logging.error(msg)
        core.quit()
    logging.debug('pyo sound server started')
    logging.flush()
Beispiel #16
0
    def __init__(self):
        wx.Dialog.__init__(self, None, pos=(200, 200), title="Device Setup",
                           style=wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
        self._gbs = wx.GridBagSizer(vgap=5, hgap=5)

        config_filename = "config.ini"
        if os.path.exists(os.path.join(SCRIPT_PATH, "custom_config.ini")):
            config_filename = "custom_config.ini"

        config = config_file_io.read(os.path.join(SCRIPT_PATH, config_filename))

        sr_list = ["44100", "48000", "88200", "96000"]
        sr_label = wx.StaticText(self, label="Sample Rate")
        self._gbs.Add(sr_label, pos=(0, 0))
        self._sr_choice = wx.Choice(self, choices=sr_list)
        self._sr_choice.SetSelection(sr_list.index(str(config['server']['sr'])))
        self._gbs.Add(self._sr_choice, pos=(1, 0), flag=wx.EXPAND)

        nchnls_list = ["1", "2", "3", "4"]
        nchnls_label = wx.StaticText(self, label="Channels")
        self._gbs.Add(nchnls_label, pos=(2, 0))
        self._nchlns_choice = wx.Choice(self, choices=nchnls_list)
        self._nchlns_choice.SetSelection(nchnls_list.index(str(config['server']['nchnls'])))
        self._gbs.Add(self._nchlns_choice, pos=(3, 0), flag=wx.EXPAND)

        buffersize_list = ["32", "64", "128", "256", "512", "1024", "2048"]
        buffersize_label = wx.StaticText(self, label="Buffersize")
        self._gbs.Add(buffersize_label, pos=(4, 0))
        self._buffersize_choice = wx.Choice(self, choices=buffersize_list)
        self._buffersize_choice.SetSelection(buffersize_list.index(str(config['server']['buffersize'])))
        self._gbs.Add(self._buffersize_choice, pos=(5, 0), flag=wx.EXPAND)

        duplex_label = wx.StaticText(self, label="Duplex (Out / In+Out)")
        self._gbs.Add(duplex_label, pos=(6, 0))
        self._duplex_choice = wx.Choice(self, choices=["0", "1"])
        self._duplex_choice.SetSelection(config['server']['duplex'])
        self._gbs.Add(self._duplex_choice, pos=(7, 0), flag=wx.EXPAND)

        # input devices
        input_device_label = wx.StaticText(self, label="Input Device")
        self._gbs.Add(input_device_label, pos=(8, 0))
        input_devices_list, index_list = pyo.pa_get_input_devices()
        final_list = ["{}: {}".format(i, d) for i, d in zip(index_list, input_devices_list)]
        self._input_device_choice = wx.Choice(self, choices=final_list)
        self._gbs.Add(self._input_device_choice, pos=(9, 0))

        inindex = index_list.index(pyo.pa_get_default_input())
        if config['device']['inindex']:
            try:
                inindex = index_list.index(config['device']['inindex'])
            except:
                pass

        self._input_device_choice.SetSelection(inindex)

        # output devices
        output_device_label = wx.StaticText(self, label="Output Device")
        self._gbs.Add(output_device_label, pos=(10, 0))
        output_devices_list, index_list = pyo.pa_get_output_devices()

        # this loops replaces non-ascii characters with '?'
        for i, device in enumerate(output_devices_list):
            newtext = ""
            for char in device:
                if ord(char) < 128:
                    newtext += char
                else:
                    newtext += "?"
            output_devices_list[i] = newtext

        final_list = ["{}: {}".format(i, d) for i, d in zip(index_list, output_devices_list)]
        self._output_device_choice = wx.Choice(self, choices=final_list)
        self._gbs.Add(self._output_device_choice, pos=(11, 0))

        outindex = index_list.index(pyo.pa_get_default_output())
        if config['device']['outindex']:
            try:
                outindex = index_list.index(config['device']['outindex'])
            except:
                pass

        self._output_device_choice.SetSelection(outindex)

        self._gbs.Add(-1, 15, pos=(12, 0))

        # buttons
        self._ok_btn = wx.Button(self, label="Ok", id=wx.ID_OK)
        self._gbs.Add(self._ok_btn, (13, 0), flag=wx.EXPAND)
        self._cancel_btn = wx.Button(self, label="Cancel", id=wx.ID_CANCEL)
        self._gbs.Add(self._cancel_btn, (14, 0), flag=wx.EXPAND)

        box = wx.BoxSizer()
        box.Add(self._gbs, 1, wx.EXPAND | wx.ALL, 5)
        self.SetSizerAndFit(box)

        self._ok_btn.Bind(wx.EVT_LEFT_UP, self.OnOkButton)
Beispiel #17
0
def initPyo(rate=44100, stereo=True, buffer=128):
    """setup the pyo (sound) server
    """
    global pyoSndServer, Sound, audioDriver, duplex
    Sound = SoundPyo
    if not 'pyo' in locals():
        import pyo  # microphone.switchOn() calls initPyo even if audioLib is something else
    #subclass the pyo.Server so that we can insert a __del__ function that shuts it down
    class Server(pyo.Server):
        core=core #make libs class variables so they don't get deleted first
        logging=logging
        def __del__(self):
            self.stop()
            self.core.wait(0.5)#make sure enough time passes for the server to shutdown
            self.shutdown()
            self.core.wait(0.5)#make sure enough time passes for the server to shutdown
            self.logging.debug('pyo sound server shutdown')#this may never get printed

    maxInputChnls = pyo.pa_get_input_max_channels(pyo.pa_get_default_input())
    maxOutputChnls = pyo.pa_get_output_max_channels(pyo.pa_get_default_output())
    maxChnls = min(maxInputChnls, maxOutputChnls)
    if maxInputChnls < 1:
        logging.warning('%s.initPyo could not find microphone hardware; recording not available' % __name__)
        maxChnls = maxOutputChnls
    if maxOutputChnls < 1:
        logging.error('%s.initPyo could not find speaker hardware; sound not available' % __name__)
        core.quit()
    #check if we already have a server and kill it
    if globals().has_key('pyoSndServer') and hasattr(pyoSndServer,'shutdown'): #if it exists and isn't None!
        #this doesn't appear to work!
        pyoSndServer.stop()
        core.wait(0.5)#make sure enough time passes for the server to shutdown
        pyoSndServer.shutdown()
        core.wait(0.5)
        pyoSndServer.reinit(sr=rate, nchnls=maxChnls, buffersize=buffer, audio=audioDriver)
        pyoSndServer.boot()
    else:
        if platform=='win32':
            #check for output device/driver
            devNames, devIDs=pyo.pa_get_output_devices()
            audioDriver,outputID=_bestDriver(devNames, devIDs)
            if outputID:
                logging.info('Using sound driver: %s (ID=%i)' %(audioDriver, outputID))
            else:
                logging.warning('No audio outputs found (no speakers connected?')
                return -1
            #check for valid input (mic)
            devNames, devIDs = pyo.pa_get_input_devices()
            junk, inputID=_bestDriver(devNames, devIDs)
            if inputID:
                duplex = bool(maxInputChnls > 0)
            else:
                duplex=False
        else:#for other platforms set duplex to True (if microphone is available)
            audioDriver = prefs.general['audioDriver'][0]
            duplex = bool(maxInputChnls > 0)
        # create the instance of the server:
        if platform=='darwin':
            #for mac we set the backend using the server audio param
            pyoSndServer = Server(sr=rate, nchnls=maxChnls, buffersize=buffer, audio=audioDriver)
        else:
            #with others we just use portaudio and then set the OutputDevice below
            pyoSndServer = Server(sr=rate, nchnls=maxChnls, buffersize=buffer)

        pyoSndServer.setVerbosity(1)
        if platform=='win32':
            pyoSndServer.setOutputDevice(outputID)
            if inputID:
                pyoSndServer.setInputDevice(inputID)
        #do other config here as needed (setDuplex? setOutputDevice?)
        pyoSndServer.setDuplex(duplex)
        pyoSndServer.boot()
    core.wait(0.5)#wait for server to boot before starting te sound stream
    pyoSndServer.start()
    try:
        Sound()  # test creation, no play
    except pyo.PyoServerStateException:
        msg = "Failed to start pyo sound Server"
        if platform == 'darwin' and audioDriver != 'portaudio':
            msg += "; maybe try prefs.general.audioDriver 'portaudio'?"
        logging.error(msg)
        core.quit()
    logging.debug('pyo sound server started')
    logging.flush()
Beispiel #18
0
from pyo import *
import serial
import numpy
import pyo

source = serial.Serial()
source.port = "COM4"
source.open()
source.baudrate = 115200

s = Server(sr=44100, nchnls=2, buffersize=1024, duplex=0)

out_devices = pyo.pa_get_output_devices()
od_index = 0
print out_devices
for od in out_devices[0]:
    if "ASIO" in od:
        pai = int(out_devices[1][od_index])
        s.setOutputDevice(pai)
        print "Found ASIO device, using device " + str(pai)
        break
    od_index += 1

s.boot()


class keySound(PyoObject):
    def __init__(self, pitch=440, amp=0):
        self._pitch = pitch
        self._amp = amp
        self._pitchSig = Sig(pitch)