Example #1
0
    def __init__(self, name='mic', file='', saveDir=''):
        """
        :Parameters:
                name :
                    Stem for the output file, also used in logging.
                file :
                    optional file name to use; default = 'name-onsetTimeEpoch.wav'
                saveDir :
                    Directory to use for output .wav files.
                    If a saveDir is given, it will return 'saveDir/file'. 
                    If no saveDir, then return abspath(file)
        """
        self.name = name
        self.saveDir = saveDir
        if file:
            self.wavOutFilename = file
        else:
            self.wavOutFilename = os.path.join(self.saveDir, name + ONSET_TIME_HERE +'.wav')
        if not self.saveDir:
            self.wavOutFilename = os.path.abspath(self.wavOutFilename)

        self.onset = None # becomes onset time, used in filename
        self.savedFile = False # becomes saved file name
        self.status = NOT_STARTED # for Builder component
        
        # pyo server good to go? 
        if not serverCreated():
            raise AttributeError('pyo server not created')
        if not serverBooted():
            raise AttributeError('pyo server not booted')
        
        self.loggingId = self.__class__.__name__
        if self.name:
            self.loggingId += ' ' + self.name
Example #2
0
def switchOn(sampleRate=44100):
    """Must explicitly switch on the microphone before use, can take several seconds.
    """
    # imports from pyo, creates globals including pyoServer and pyoSamplingRate

    global haveMic
    haveMic = False
    t0 = time.time()
    
    try:
        global Server, Record, Input, Clean_objects, SfPlayer, serverCreated, serverBooted
        from pyo import Server, Record, Input, Clean_objects, SfPlayer, serverCreated, serverBooted
        global getVersion, pa_get_input_devices, pa_get_output_devices
        from pyo import getVersion, pa_get_input_devices, pa_get_output_devices
        haveMic = True
    except ImportError:
        msg = 'Microphone class not available, needs pyo; see http://code.google.com/p/pyo/'
        logging.error(msg)
        raise ImportError(msg)
    
    global pyoSamplingRate
    pyoSamplingRate = sampleRate
    global pyoServer
    if serverCreated():
        pyoServer.setSamplingRate(sampleRate)
        pyoServer.boot()
    else:
        pyoServer = Server(sr=sampleRate, nchnls=2, duplex=1).boot()
    pyoServer.start()

    logging.exp('%s: switch on (%dhz) took %.3fs' % (__file__.strip('.py'), sampleRate, time.time() - t0))
    def __init__(self,
                 name='mic',
                 filename='',
                 saveDir='',
                 sampletype=0,
                 buffering=16,
                 chnl=0):
        """
        :Parameters:
            name :
                Stem for the output file, also used in logging.
            file :
                optional file name to use; default = 'name-onsetTimeEpoch.wav'
            saveDir :
                Directory to use for output .wav files.
                If a saveDir is given, it will return 'saveDir/file'.
                If no saveDir, then return abspath(file)
            sampletype : bit depth
                pyo recording option: 0=16 bits int, 1=24 bits int; 2=32 bits int
        """
        if not haveMic:
            raise MicrophoneError(
                'Need to call microphone.switchOn() before AudioCapture or AdvancedCapture'
            )
        self.name = name
        self.saveDir = saveDir
        if filename:
            self.wavOutFilename = filename
        else:
            self.wavOutFilename = os.path.join(self.saveDir, name + '.wav')
        if not self.saveDir:
            self.wavOutFilename = os.path.abspath(self.wavOutFilename)
        else:
            if not os.path.isdir(self.saveDir):
                os.makedirs(self.saveDir, 0770)

        self.onset = None  # becomes onset time, used in filename
        self.savedFile = False  # becomes saved file name
        self.status = NOT_STARTED  # for Builder component

        # pyo server good to go?
        if not serverCreated():
            raise AttributeError('pyo server not created')
        if not serverBooted():
            raise AttributeError('pyo server not booted')

        self.loggingId = self.__class__.__name__
        if self.name:
            self.loggingId += ' ' + self.name

        # the recorder object needs to persist, or else get bus errors:
        self.recorder = self._Recorder()
        self.options = {
            'sampletype': sampletype,
            'buffering': buffering,
            'chnl': chnl
        }
Example #4
0
    def __init__(
        self, name="mic", filename="", saveDir="", sampletype=0, buffering=16, chnl=0, stereo=True, autoLog=True
    ):
        """
        :Parameters:
            name :
                Stem for the output file, also used in logging.
            filename :
                optional file name to use; default = 'name-onsetTimeEpoch.wav'
            saveDir :
                Directory to use for output .wav files.
                If a saveDir is given, it will return 'saveDir/file'.
                If no saveDir, then return abspath(file)
            sampletype : bit depth
                pyo recording option: 0=16 bits int, 1=24 bits int; 2=32 bits int
            buffering : pyo argument
            chnl : which audio input channel to record (default=0)
            stereo : how many channels to record (default True, stereo; False = mono)
        """
        if not haveMic:
            raise MicrophoneError("Need to call microphone.switchOn() before AudioCapture or AdvancedCapture")
        self.name = name
        self.saveDir = saveDir
        if filename:
            self.wavOutFilename = filename
        else:
            self.wavOutFilename = os.path.join(self.saveDir, name + ".wav")
        if not self.saveDir:
            self.wavOutFilename = os.path.abspath(self.wavOutFilename)
        else:
            if not os.path.isdir(self.saveDir):
                os.makedirs(self.saveDir, 0770)

        self.onset = None  # becomes onset time, used in filename
        self.savedFile = False  # becomes saved file name
        self.status = NOT_STARTED  # for Builder component

        # pyo server good to go?
        if not serverCreated():
            raise AttributeError("pyo server not created")
        if not serverBooted():
            raise AttributeError("pyo server not booted")

        self.autoLog = autoLog
        self.loggingId = self.__class__.__name__
        if self.name:
            self.loggingId += " " + self.name

        # the recorder object needs to persist, or else get bus errors:
        self.recorder = self._Recorder()
        self.options = {
            "sampletype": sampletype,
            "buffering": buffering,
            "chnl": chnl,
            "chnls": 1 + int(stereo == True),
        }
Example #5
0
def switchOn(sampleRate=48000, outputDevice=None, bufferSize=None):
    """You need to switch on the microphone before use, which can take
    several seconds. The only time you can specify the sample rate (in Hz)
    is during switchOn().

    Considerations on the default sample rate 48kHz::

        DVD or video = 48,000
        CD-quality   = 44,100 / 24 bit
        human hearing: ~15,000 (adult); children & young adult higher
        human speech: 100-8,000 (useful for telephone: 100-3,300)
        Google speech API: 16,000 or 8,000 only
        Nyquist frequency: twice the highest rate, good to oversample a bit

    pyo's downsamp() function can reduce 48,000 to 16,000 in about 0.02s
    (uses integer steps sizes). So recording at 48kHz will generate
    high-quality archival data, and permit easy downsampling.

    outputDevice, bufferSize: set these parameters on the pyoSndServer
        before booting; None means use pyo's default values
    """
    # imports pyo, creates sound.pyoSndServer using sound.initPyo() if not yet
    # created
    t0 = core.getTime()
    if prefs.hardware['audioLib'][0] != 'pyo':
        logging.warning(
            "Starting Microphone but sound lib preference is set to be {}. "
            "Clashes might occur since 'pyo' is not "
            "preferred lib but is needed for Microphone".format(
                prefs.hardware['audioLib']))
    try:
        global pyo
        import pyo
        global haveMic
        haveMic = True
    except ImportError:  # pragma: no cover
        msg = ('Microphone class not available, needs pyo; '
               'see http://ajaxsoundstudio.com/software/pyo/')
        logging.error(msg)
        raise ImportError(msg)
    if pyo.serverCreated():
        backend_pyo.pyoSndServer.setSamplingRate(sampleRate)
    else:
        # backend_pyo.init() will create pyoSndServer. We want there only
        # ever to be one server
        # will automatically use duplex=1 and stereo if poss
        backend_pyo.init(rate=sampleRate)
    if outputDevice:
        backend_pyo.pyoSndServer.setOutputDevice(outputDevice)
    if bufferSize:
        backend_pyo.pyoSndServer.setBufferSize(bufferSize)
    logging.exp('%s: switch on (%dhz) took %.3fs' %
                (__file__.strip('.py'), sampleRate, core.getTime() - t0))
Example #6
0
def switchOff():
    """Must explicitly switch off the microphone when done.
    """
    t0 = time.time()
    global pyoServer, pyoSamplingRate
    if serverBooted():
        pyoServer.stop()
        time.sleep(.25) # give it a chance to stop before shutdown()
    if serverCreated():
        pyoServer.shutdown()
    del pyoSamplingRate
    logging.exp('%s: switch off took %.3fs' % (__file__.strip('.py'), time.time() - t0))
Example #7
0
def switchOn(sampleRate=48000, outputDevice=None, bufferSize=None):
    """You need to switch on the microphone before use, which can take several seconds.
    The only time you can specify the sample rate (in Hz) is during switchOn().
    You can switchOff() and switchOn() with a different rate, and can `resample()`
    a given an `AudioCapture()` object (if one has been recorded).
    
    Considerations on the default sample rate 48kHz::
    
        DVD or video = 48,000
        CD-quality   = 44,100 / 24 bit
        human hearing: ~15,000 (adult); children & young adult higher
        human speech: 100-8,000 (useful for telephone: 100-3,300)
        google speech API: 16,000 or 8,000 only
        Nyquist frequency: twice the highest rate, good to oversample a bit
        
    pyo's downsamp() function can reduce 48,000 to 16,000 in about 0.02s (uses integer steps sizes)
    So recording at 48kHz will generate high-quality archival data, and permit easy downsampling.
    
    outputDevice, bufferSize: set these parameters on the pyoServer before booting;
        None means use pyo's default values
    """
    # imports from pyo, creates globals pyoServer
    t0 = core.getTime()
    try:
        global Server, Record, Input, Clean_objects, SfPlayer, serverCreated, serverBooted
        from pyo import Server, Record, Input, Clean_objects, SfPlayer, serverCreated, serverBooted
        global getVersion, pa_get_input_devices, pa_get_output_devices, downsamp, upsamp
        from pyo import getVersion, pa_get_input_devices, pa_get_output_devices, downsamp, upsamp
        global haveMic
        haveMic = True
    except ImportError:
        msg = 'Microphone class not available, needs pyo; see http://code.google.com/p/pyo/'
        logging.error(msg)
        raise ImportError(msg)
    global pyoServer
    if serverCreated():
        pyoServer.setSamplingRate(sampleRate)

    else:
        pyoServer = Server(sr=sampleRate, nchnls=2, duplex=1)
    if outputDevice:
        pyoServer.setOutputDevice(outputDevice)
    if bufferSize:
        pyoServer.setBufferSize(bufferSize)
    pyoServer.boot()
    core.pyoServers.append(pyoServer)
    pyoServer.start()
    logging.exp('%s: switch on (%dhz) took %.3fs' %
                (__file__.strip('.py'), sampleRate, core.getTime() - t0))
Example #8
0
def switchOn(sampleRate=48000, outputDevice=None, bufferSize=None):
    """You need to switch on the microphone before use, which can take several seconds.
    The only time you can specify the sample rate (in Hz) is during switchOn().
    You can switchOff() and switchOn() with a different rate, and can `resample()`
    a given an `AudioCapture()` object (if one has been recorded).
    
    Considerations on the default sample rate 48kHz::
    
        DVD or video = 48,000
        CD-quality   = 44,100 / 24 bit
        human hearing: ~15,000 (adult); children & young adult higher
        human speech: 100-8,000 (useful for telephone: 100-3,300)
        google speech API: 16,000 or 8,000 only
        Nyquist frequency: twice the highest rate, good to oversample a bit
        
    pyo's downsamp() function can reduce 48,000 to 16,000 in about 0.02s (uses integer steps sizes)
    So recording at 48kHz will generate high-quality archival data, and permit easy downsampling.
    
    outputDevice, bufferSize: set these parameters on the pyoServer before booting;
        None means use pyo's default values
    """
    # imports from pyo, creates globals pyoServer
    t0 = core.getTime()
    try:
        global Server, Record, Input, Clean_objects, SfPlayer, serverCreated, serverBooted
        from pyo import Server, Record, Input, Clean_objects, SfPlayer, serverCreated, serverBooted
        global getVersion, pa_get_input_devices, pa_get_output_devices, downsamp, upsamp
        from pyo import getVersion, pa_get_input_devices, pa_get_output_devices, downsamp, upsamp
        global haveMic
        haveMic = True
    except ImportError:
        msg = 'Microphone class not available, needs pyo; see http://code.google.com/p/pyo/'
        logging.error(msg)
        raise ImportError(msg)
    global pyoServer
    if serverCreated():
        pyoServer.setSamplingRate(sampleRate)
        
    else:
        pyoServer = Server(sr=sampleRate, nchnls=2, duplex=1)
    if outputDevice:
        pyoServer.setOutputDevice(outputDevice)
    if bufferSize:
        pyoServer.setBufferSize(bufferSize)
    pyoServer.boot()
    core.pyoServers.append(pyoServer)
    pyoServer.start()
    logging.exp('%s: switch on (%dhz) took %.3fs' % (__file__.strip('.py'), sampleRate, core.getTime() - t0))
Example #9
0
def switchOff():
    """Its good to explicitly switch off the microphone when done (in order to avoid
    a segmentation fault). core.quit() also tries to switchOff if needed, but best to
    do so explicitly.
    """
    t0 = core.getTime()
    global haveMic
    haveMic = False
    global pyoServer
    if serverBooted():
        pyoServer.stop()
        core.wait(.25) # give it a chance to stop before shutdown(), avoid seg fault
    if serverCreated():
        pyoServer.shutdown()
        del core.pyoServers[core.pyoServers.index(pyoServer)]
    logging.exp('%s: switch off took %.3fs' % (__file__.strip('.py'), core.getTime() - t0))
Example #10
0
def switchOn(sampleRate=48000, outputDevice=None, bufferSize=None):
    """You need to switch on the microphone before use, which can take
    several seconds. The only time you can specify the sample rate (in Hz)
    is during switchOn().

    Considerations on the default sample rate 48kHz::

        DVD or video = 48,000
        CD-quality   = 44,100 / 24 bit
        human hearing: ~15,000 (adult); children & young adult higher
        human speech: 100-8,000 (useful for telephone: 100-3,300)
        Google speech API: 16,000 or 8,000 only
        Nyquist frequency: twice the highest rate, good to oversample a bit

    pyo's downsamp() function can reduce 48,000 to 16,000 in about 0.02s
    (uses integer steps sizes). So recording at 48kHz will generate
    high-quality archival data, and permit easy downsampling.

    outputDevice, bufferSize: set these parameters on the pyoSndServer
        before booting; None means use pyo's default values
    """
    # imports pyo, creates sound.pyoSndServer using sound.initPyo() if not yet
    # created
    t0 = core.getTime()
    try:
        global pyo
        import pyo
        global haveMic
        haveMic = True
    except ImportError:  # pragma: no cover
        msg = ('Microphone class not available, needs pyo; '
               'see http://code.google.com/p/pyo/')
        logging.error(msg)
        raise ImportError(msg)
    if pyo.serverCreated():
        sound.backend.pyoSndServer.setSamplingRate(sampleRate)
    else:
        # sound.init() will create pyoSndServer. We want there only
        # ever to be one server
        # will automatically use duplex=1 and stereo if poss
        sound.init(rate=sampleRate)
    if outputDevice:
        sound.backend.pyoSndServer.setOutputDevice(outputDevice)
    if bufferSize:
        sound.backend.pyoSndServer.setBufferSize(bufferSize)
    logging.exp('%s: switch on (%dhz) took %.3fs' %
                (__file__.strip('.py'), sampleRate, core.getTime() - t0))
Example #11
0
    def __init__(self, name='mic', filename='', saveDir='', sampletype=0,
                 buffering=16, chnl=0):
        """
        :Parameters:
            name :
                Stem for the output file, also used in logging.
            file :
                optional file name to use; default = 'name-onsetTimeEpoch.wav'
            saveDir :
                Directory to use for output .wav files.
                If a saveDir is given, it will return 'saveDir/file'.
                If no saveDir, then return abspath(file)
            sampletype : bit depth
                pyo recording option: 0=16 bits int, 1=24 bits int; 2=32 bits int
        """
        if not haveMic:
            raise MicrophoneError('Need to call microphone.switchOn() before AudioCapture or AdvancedCapture')
        self.name = name
        self.saveDir = saveDir
        if filename:
            self.wavOutFilename = filename
        else:
            self.wavOutFilename = os.path.join(self.saveDir, name + '.wav')
        if not self.saveDir:
            self.wavOutFilename = os.path.abspath(self.wavOutFilename)
        else:
            if not os.path.isdir(self.saveDir):
                os.makedirs(self.saveDir, 0770)

        self.onset = None # becomes onset time, used in filename
        self.savedFile = False # becomes saved file name
        self.status = NOT_STARTED # for Builder component

        # pyo server good to go?
        if not serverCreated():
            raise AttributeError('pyo server not created')
        if not serverBooted():
            raise AttributeError('pyo server not booted')

        self.loggingId = self.__class__.__name__
        if self.name:
            self.loggingId += ' ' + self.name

        # the recorder object needs to persist, or else get bus errors:
        self.recorder = self._Recorder()
        self.options = {'sampletype': sampletype, 'buffering': buffering, 'chnl': chnl}
Example #12
0
def switchOff():
    """Its good to explicitly switch off the microphone when done (in order to avoid
    a segmentation fault). core.quit() also tries to switchOff if needed, but best to
    do so explicitly.
    """
    t0 = core.getTime()
    global haveMic
    haveMic = False
    global pyoServer
    if serverBooted():
        pyoServer.stop()
        core.wait(
            .25)  # give it a chance to stop before shutdown(), avoid seg fault
    if serverCreated():
        pyoServer.shutdown()
        del core.pyoServers[core.pyoServers.index(pyoServer)]
    logging.exp('%s: switch off took %.3fs' %
                (__file__.strip('.py'), core.getTime() - t0))
Example #13
0
def switchOn(sampleRate=48000, outputDevice=None, bufferSize=None):
    """You need to switch on the microphone before use, which can take several seconds.
    The only time you can specify the sample rate (in Hz) is during switchOn().

    Considerations on the default sample rate 48kHz::

        DVD or video = 48,000
        CD-quality   = 44,100 / 24 bit
        human hearing: ~15,000 (adult); children & young adult higher
        human speech: 100-8,000 (useful for telephone: 100-3,300)
        google speech API: 16,000 or 8,000 only
        Nyquist frequency: twice the highest rate, good to oversample a bit

    pyo's downsamp() function can reduce 48,000 to 16,000 in about 0.02s (uses integer steps sizes)
    So recording at 48kHz will generate high-quality archival data, and permit easy downsampling.

    outputDevice, bufferSize: set these parameters on the pyoSndServer before booting;
        None means use pyo's default values
    """
    # imports pyo, creates sound.pyoSndServer using sound.initPyo() if not yet created
    t0 = core.getTime()
    try:
        global pyo
        import pyo
        global haveMic
        haveMic = True
    except ImportError:  # pragma: no cover
        msg = 'Microphone class not available, needs pyo; see http://code.google.com/p/pyo/'
        logging.error(msg)
        raise ImportError(msg)
    if pyo.serverCreated():
        sound.pyoSndServer.setSamplingRate(sampleRate)
    else:
        #sound.initPyo() will create pyoSndServer. We want there only ever to be one server
        sound.initPyo(rate=sampleRate
                      )  #will automatically use duplex=1 and stereo if poss
    if outputDevice:
        sound.pyoSndServer.setOutputDevice(outputDevice)
    if bufferSize:
        sound.pyoSndServer.setBufferSize(bufferSize)
    logging.exp('%s: switch on (%dhz) took %.3fs' %
                (__file__.strip('.py'), sampleRate, core.getTime() - t0))