当前位置: 首页>>代码示例>>Python>>正文


Python logging.exp函数代码示例

本文整理汇总了Python中psychopy.logging.exp函数的典型用法代码示例。如果您正苦于以下问题:Python exp函数的具体用法?Python exp怎么用?Python exp使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了exp函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: setSound

    def setSound(self, value, secs=0.5, octave=4, hamming=True, log=True):
        """Set the sound to be played.

        Often this is not needed by the user - it is called implicitly during
        initialisation.

        :parameters:

            value: can be a number, string or an array:
                * If it's a number between 37 and 32767 then a tone will be generated at that frequency in Hz.
                * It could be a string for a note ('A','Bfl','B','C','Csh'...). Then you may want to specify which octave as well
                * Or a string could represent a filename in the current location, or mediaLocation, or a full path combo
                * Or by giving an Nx2 numpy array of floats (-1:1) you can specify the sound yourself as a waveform

            secs: duration (only relevant if the value is a note name or a frequency value)

            octave: is only relevant if the value is a note name.
                Middle octave of a piano is 4. Most computers won't
                output sounds in the bottom octave (1) and the top
                octave (8) is generally painful
        """
        self._snd = None  # Re-init sound to ensure bad values will raise RuntimeError during setting

        try:#could be '440' meaning 440
            value = float(value)
            #we've been asked for a particular Hz
        except (ValueError, TypeError):
            pass  #this is a string that can't be a number
        else:
            self._fromFreq(value, secs, hamming=hamming)

        if isinstance(value, basestring):
            if capitalize(value) in knownNoteNames:
                if not self._fromNoteName(capitalize(value), secs, octave, hamming=hamming):
                    self._snd = None
            else:
                #try finding the file
                self.fileName=None
                for filePath in ['', mediaLocation]:
                    p = path.join(filePath, value)
                    if path.isfile(p):
                        self.fileName = p
                    elif path.isfile(p + '.wav'):
                        self.fileName = p + '.wav'
                if self.fileName is None:
                    raise IOError, "setSound: could not find a sound file named " + value
                elif not self._fromFile(value):
                    self._snd = None
        elif type(value) in [list,numpy.ndarray]:
            #create a sound from the input array/list
            if not self._fromArray(value):
                self._snd = None

        #did we succeed?
        if self._snd is None:
            raise RuntimeError, "Could not make a "+value+" sound"
        else:
            if log and self.autoLog:
                logging.exp("Set %s sound=%s" %(self.name, value), obj=self)
            self.status=NOT_STARTED
开发者ID:BrainTech,项目名称:psychopy,代码行数:60,代码来源:sound.py

示例2: setLoops

 def setLoops(self, newLoops, log=True):
     """Sets the current requested extra loops (int)"""
     self.loops = int(newLoops)
     self.needsUpdate = True
     if log and self.autoLog:
         logging.exp("Sound %s set loops %s" %
                     (self.name, self.loops), obj=self)
开发者ID:jonathanoroberts,项目名称:psychopy,代码行数:7,代码来源:_base.py

示例3: setMarker

    def setMarker(self, tone=19000, secs=0.015, volume=0.03, log=True):
        """Sets the onset marker, where `tone` is either in hz or a custom sound.

        The default tone (19000 Hz) is recommended for auto-detection, as being
        easier to isolate from speech sounds (and so reliable to detect). The default duration
        and volume are appropriate for a quiet setting such as a lab testing
        room. A louder volume, longer duration, or both may give better results
        when recording loud sounds or in noisy environments, and will be
        auto-detected just fine (even more easily). If the hardware microphone
        in use is not physically near the speaker hardware, a louder volume is
        likely to be required.

        Custom sounds cannot be auto-detected, but are supported anyway for
        presentation purposes. E.g., a recording of someone saying "go" or
        "stop" could be passed as the onset marker.
        """
        if hasattr(tone, "play"):
            self.marker_hz = 0
            self.marker = tone
            if log and self.autoLog:
                logging.exp("custom sound set as marker; getMarkerOnset() will not be able to auto-detect onset")
        else:
            self.marker_hz = float(tone)
            sampleRate = sound.pyoSndServer.getSamplingRate()
            if sampleRate < 2 * self.marker_hz:
                # NyquistError
                logging.warning(
                    "Recording rate (%i Hz) too slow for %i Hz-based marker detection."
                    % (int(sampleRate), self.marker_hz)
                )
            if log and self.autoLog:
                logging.exp("frequency of recording onset marker: %.1f" % self.marker_hz)
            self.marker = sound.Sound(self.marker_hz, secs, volume=volume, name=self.name + ".marker_tone")
开发者ID:rpbaxter,项目名称:psychopy,代码行数:33,代码来源:microphone.py

示例4: play

    def play(self, loops=None, autoStop=True, log=True):
        """Starts playing the sound on an available channel.

        loops : int
            (same as above)

        For playing a sound file, you cannot specify the start and stop times when
        playing the sound, only when creating the sound initially.

        Playing a sound runs in a separate thread i.e. your code won't wait for the
        sound to finish before continuing. To pause while playing, you need to use a
        `psychopy.core.wait(mySound.getDuration())`.
        If you call `play()` while something is already playing the sounds will
        be played over each other.
        """
        if loops is not None and self.loops != loops:
            self.setLoops(loops)
        if self.needsUpdate:
            self._updateSnd()  # ~0.00015s, regardless of the size of self._sndTable
        self._snd.out()
        self.status=STARTED
        if autoStop or self.loops != 0:
            # pyo looping is boolean: loop forever or not at all
            # so track requested loops using time; limitations: not sample-accurate
            if self.loops >= 0:
                duration = self.getDuration() * (self.loops + 1)
            else:
                duration = FOREVER
            self.terminator = threading.Timer(duration, self._onEOS)
            self.terminator.start()
        if log and self.autoLog:
            logging.exp("Sound %s started" %(self.name), obj=self)
        return self
开发者ID:9173860,项目名称:psychopy,代码行数:33,代码来源:sound.py

示例5: playback

    def playback(self, block=True, loops=0, stop=False, log=True):
        """Plays the saved .wav file, as just recorded or resampled. Execution
        blocks by default, but can return immediately with `block=False`.

        `loops` : number of extra repetitions; 0 = play once

        `stop` : True = immediately stop ongoing playback (if there is one), and return
        """
        if not self.savedFile or not os.path.isfile(self.savedFile):
            msg = "%s: Playback requested but no saved file" % self.loggingId
            logging.error(msg)
            raise ValueError(msg)

        if stop:
            if hasattr(self, "current_recording") and self.current_recording.status == PLAYING:
                self.current_recording.stop()
            return

        # play this file:
        name = self.name + ".current_recording"
        self.current_recording = sound.Sound(self.savedFile, name=name, loops=loops)
        self.current_recording.play()
        if block:
            core.wait(self.duration * (loops + 1))  # set during record()

        if log and self.autoLog:
            if loops:
                logging.exp(
                    "%s: Playback: play %.3fs x %d (est) %s"
                    % (self.loggingId, self.duration, loops + 1, self.savedFile)
                )
            else:
                logging.exp("%s: Playback: play %.3fs (est) %s" % (self.loggingId, self.duration, self.savedFile))
开发者ID:rpbaxter,项目名称:psychopy,代码行数:33,代码来源:microphone.py

示例6: stop

 def stop(self, log=True):
     """Stops the sound immediately
     """
     self._snd.stop()
     self.status = STOPPED
     if log and self.autoLog:
         logging.exp("Sound %s stopped" % (self.name), obj=self)
开发者ID:jonathanoroberts,项目名称:psychopy,代码行数:7,代码来源:backend_pygame.py

示例7: setVolume

 def setVolume(self, newVol, log=True):
     """Sets the current volume of the sound (0.0 to 1.0, inclusive)"""
     self.volume = min(1.0, max(0.0, newVol))
     self.needsUpdate = True
     if log and self.autoLog:
         logging.exp("Sound %s set volume %.3f" % (self.name, self.volume), obj=self)
     return self.getVolume()
开发者ID:smathot,项目名称:psychopy,代码行数:7,代码来源:sound.py

示例8: switchOn

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))
开发者ID:jsalva,项目名称:psychopy,代码行数:31,代码来源:microphone.py

示例9: reset

 def reset(self, log=True):
     """Restores to fresh state, ready to record again
     """
     if log and self.autoLog:
         msg = '%s: resetting at %.3f'
         logging.exp(msg % (self.loggingId, core.getTime()))
     self.__init__(name=self.name, saveDir=self.saveDir)
开发者ID:jonathanoroberts,项目名称:psychopy,代码行数:7,代码来源:microphone.py

示例10: record

    def record(self, sec, file='', block=True):
        """Capture sound input for duration <sec>, save to a file.

        Return the path/name to the new file. Uses onset time (epoch) as
        a meaningful identifier for filename and log.
        """
        while self.recorder.running:
            pass
        self.duration = float(sec)
        self.onset = core.getTime() # note: report onset time in log, and use in filename
        logging.data('%s: Record: onset %.3f, capture %.3fs' %
                     (self.loggingId, self.onset, self.duration) )
        if not file:
            onsettime = '-%.3f' % self.onset
            self.savedFile = onsettime.join(os.path.splitext(self.wavOutFilename))
        else:
            self.savedFile = os.path.abspath(file).strip('.wav') + '.wav'

        t0 = core.getTime()
        self.recorder.run(self.savedFile, self.duration, self.sampletype)
        self.rate = sound.pyoSndServer.getSamplingRate()

        if block:
            core.wait(self.duration - .0008) # .0008 fudge factor for better reporting
                # actual timing is done by Clean_objects
            logging.exp('%s: Record: stop. %.3f, capture %.3fs (est)' %
                     (self.loggingId, core.getTime(), core.getTime() - t0) )
        else:
            logging.exp('%s: Record: return immediately, no blocking' %
                     (self.loggingId) )

        return self.savedFile
开发者ID:RainyJupiter,项目名称:psychopy,代码行数:32,代码来源:microphone.py

示例11: record

    def record(self, sec, block=True):
        """Capture sound input for duration <sec>, save to a file.
        
        Return the path/name to the new file. Uses onset time (epoch) as
        a meaningful identifier for filename and log.
        """
        RECORD_SECONDS = float(sec)
        self.onset = time.time() # note: report onset time in log, and use in filename
        logging.data('%s: Record: onset %.3f, capture %.3fs' %
                     (self.loggingId, self.onset, RECORD_SECONDS) )
        
        self.savedFile = self.wavOutFilename.replace(ONSET_TIME_HERE, '-%.3f' % self.onset)
        inputter = Input(chnl=0, mul=1) # chnl=[0,1] for stereo input
        t0 = time.time()
        # launch the recording, saving to file:
        recorder = Record(inputter,
                        self.savedFile,
                        chnls=2,
                        fileformat=0, # .wav format
                        sampletype=0,
                        buffering=4) # 4 is default
        # launch recording, block as needed, and clean up:
        clean = Clean_objects(RECORD_SECONDS, recorder) # set up to stop recording
        clean.start() # the timer starts now, ends automatically whether block or not
        if block:
            time.sleep(RECORD_SECONDS - 0.0008) # Clean_objects() set-up takes ~0.0008s, for me
            logging.exp('%s: Record: stop. %.3f, capture %.3fs (est)' %
                     (self.loggingId, time.time(), time.time() - t0) )
        else:
            logging.exp('%s: Record: return immediately, no blocking' %
                     (self.loggingId) )
        
        self.duration = RECORD_SECONDS # used in playback()

        return self.savedFile # filename, or None
开发者ID:jsalva,项目名称:psychopy,代码行数:35,代码来源:microphone.py

示例12: _record

    def _record(self, sec, filename='', block=True):
        while self.recorder.running:
            pass
        self.duration = float(sec)
        self.onset = core.getTime()  # for duration estimation, high precision
        self.fileOnset = core.getAbsTime()  # for log and filename, 1 sec precision
        logging.data('%s: Record: onset %d, capture %.3fs' %
                     (self.loggingId, self.fileOnset, self.duration) )
        if not file:
            onsettime = '-%d' % self.fileOnset
            self.savedFile = onsettime.join(os.path.splitext(self.wavOutFilename))
        else:
            self.savedFile = os.path.abspath(filename).strip('.wav') + '.wav'

        t0 = core.getTime()
        self.recorder.run(self.savedFile, self.duration, **self.options)

        self.rate = sound.pyoSndServer.getSamplingRate()
        if block:
            core.wait(self.duration, 0)
            logging.exp('%s: Record: stop. %.3f, capture %.3fs (est)' %
                     (self.loggingId, core.getTime(), core.getTime() - t0) )
            while self.recorder.running:
                core.wait(.001, 0)
        else:
            logging.exp('%s: Record: return immediately, no blocking' %
                     (self.loggingId) )

        return self.savedFile
开发者ID:DiogoamCoutinho,项目名称:stimulus.py,代码行数:29,代码来源:microphone.py

示例13: __init__

    def __init__(self, win, size, pos=(0,0), ori=0, nVert=120, shape='circle', units=None,
            name='', autoLog=True):
        #what local vars are defined (these are the init params) for use by __repr__
        self._initParams = dir()
        self._initParams.remove('self')
        #set self params
        self.autoLog=False #set this False first and change after attribs are set
        self.win=win
        self.name = name
        self.ori = ori
        #unit conversions
        if units!=None and len(units):
            self.units = units
        else:
            self.units = win.units

        # ugly hack for setting vertices using combination of shape and nVerts
        if type(nVert) == int:
            self.nVert = nVert
        regularPolygon = True
        self.shape = shape
        unrecognized = False
        if shape is None:
            pass #just use the nVert we were given
        elif type(shape) in [str, unicode]:
            if shape.lower() == 'circle':
                pass #just use the nVert we were given
            elif shape.lower() == 'square':
                regularPolygon = False # if we use polygon then we have to hack the orientation
                vertices = [[0.5,-0.5],[-0.5,-0.5],[-0.5,0.5],[0.5,0.5]]
            elif shape.lower() == 'triangle':
                regularPolygon = False # if we use polygon then we have to hack the orientation
                vertices = [[0.5,-0.5],[0,0.5],[-0.5,-0.5]]
            else:
                unrecognized = True
        elif type(shape) in [tuple, list, numpy.ndarray]:
            regularPolygon = False
            vertices = shape
        else:
            unrecognized = True
        if unrecognized:
            logging.warn("Unrecognized shape for aperture. Expected 'circle', 'square', 'triangle', vertices or None but got %s" %(repr(shape)))
        if regularPolygon:
            self._shape = polygon.Polygon(win=self.win, edges=self.nVert,
                                          fillColor=1, lineColor=None,
                                          interpolate=False,
                                          pos=pos,
                                          size=size)
        else:
            self._shape = ShapeStim(win=self.win, vertices=vertices,
                                          fillColor=1, lineColor=None,
                                          interpolate=False,
                                          pos=pos,
                                          size=size)

        self._needVertexUpdate = True
        self._reset()#implicitly runs an self.enable()
        self.autoLog= autoLog
        if autoLog:
            logging.exp("Created %s = %s" %(self.name, str(self)))
开发者ID:larigaldie-n,项目名称:psychopy,代码行数:60,代码来源:aperture.py

示例14: __init__

    def __init__(self, win, size, pos=(0,0), ori=0, nVert=120, shape='circle', units=None,
            name='', autoLog=True):
        #what local vars are defined (these are the init params) for use by __repr__
        self._initParams = dir()
        self._initParams.remove('self')
        #set self params
        self.autoLog=False #set this False first and change after attribs are set
        self.win=win
        self.name = name

        #unit conversions
        if units!=None and len(units):
            self.units = units
        else:
            self.units = win.units

        if shape.lower() == 'square':
            ori += 45
            nVert = 4
        elif shape.lower() == 'triangle':
            nVert = 3
        self.ori = ori
        self.nVert = 120
        if type(nVert) == int:
            self.nVert = nVert
        self.quad=GL.gluNewQuadric() #needed for gluDisk
        self.setSize(size, needReset=False)
        self.setPos(pos, needReset=False)
        self._reset()#implicitly runs an self.enable()
        self.autoLog= autoLog
        if autoLog:
            logging.exp("Created %s = %s" %(self.name, str(self)))
开发者ID:PieterMoors,项目名称:psychopy,代码行数:32,代码来源:aperture.py

示例15: _switchToVersion

def _switchToVersion(requestedVersion):
    """Checkout (or clone then checkout) the requested version, set sys.path
    so that the new version will be found when import is called. Upon exit,
    the checked out version remains checked out, but the sys.path reverts.

    NB When installed with pip/easy_install PsychoPy will live in
    a site-packages directory, which should *not* be removed as it may
    contain other relevant and needed packages.
    """
    if not os.path.exists(prefs.paths['userPrefsDir']):
        os.mkdir(prefs.paths['userPrefsDir'])
    try:
        if os.path.exists(VERSIONSDIR):
            _checkout(requestedVersion)
        else:
            _clone(requestedVersion)
    except CalledProcessError as e:
        if 'did not match any file(s) known to git' in e.output:
            msg = _translate("'{}' is not a valid PsychoPy version.")
            logging.error(msg.format(requestedVersion))
            raise RuntimeError(msg)
        else:
            raise

    # make sure the checked-out version comes first on the python path:
    sys.path = [VERSIONSDIR] + sys.path
    logging.exp('Prepended `{}` to sys.path'.format(VERSIONSDIR))
开发者ID:DennisEckmeier,项目名称:psychopy,代码行数:27,代码来源:versionchooser.py


注:本文中的psychopy.logging.exp函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。