platypush/plugins/sound/__init__.py
def record(self, outfile=None, duration=None, device=None, sample_rate=None,
               format=None, blocksize=None, latency=0, channels=1, subtype='PCM_24'):
        """
        Records audio to a sound file (support formats: wav, raw)

        :param outfile: Sound file (default: the method will create a temporary file with the recording)
        :type outfile: str

        :param duration: Recording duration in seconds (default: record until stop event)
        :type duration: float

        :param device: Input device (default: default configured device or system default audio input if not configured)
        :type device: int or str

        :param sample_rate: Recording sample rate (default: device default rate)
        :type sample_rate: int

        :param format: Audio format (default: WAV)
        :type format: str

        :param blocksize: Audio block size (default: configured `input_blocksize` or 2048)
        :type blocksize: int

        :param latency: Device latency in seconds (default: 0)
        :type latency: float

        :param channels: Number of channels (default: 1)
        :type channels: int

        :param subtype: Recording subtype - see `Soundfile docs - Subtypes <https://pysoundfile.readthedocs.io/en/0.9.0/#soundfile.available_subtypes>`_ for a list of the available subtypes (default: PCM_24)
        :type subtype: str
        """

        def recording_thread(outfile, duration, device, sample_rate, format,
                             blocksize, latency, channels, subtype):
            import sounddevice as sd

            self.recording_paused_changed.clear()

            if outfile:
                outfile = os.path.abspath(os.path.expanduser(outfile))
                if os.path.isfile(outfile):
                    self.logger.info('Removing existing audio file {}'.format(outfile))
                    os.unlink(outfile)
            else:
                outfile = tempfile.NamedTemporaryFile(
                    prefix='recording_', suffix='.wav', delete=False,
                    dir=tempfile.gettempdir()).name

            if device is None:
                device = self.input_device
            if device is None:
                device = self._get_default_device('input')

            if sample_rate is None:
                dev_info = sd.query_devices(device, 'input')
                sample_rate = int(dev_info['default_samplerate'])

            if blocksize is None:
                blocksize = self.input_blocksize

            q = queue.Queue()

            def audio_callback(indata, frames, duration, status):
                while self._get_recording_state() == RecordingState.PAUSED:
                    self.recording_paused_changed.wait()

                if status:
                    self.logger.warning('Recording callback status: {}'.format(
                        str(status)))

                q.put({
                    'timestamp': time.time(),
                    'frames': frames,
                    'time': duration,
                    'data': indata.copy()
                })

            try:
                import soundfile as sf
                import numpy

                with sf.SoundFile(outfile, mode='w', samplerate=sample_rate,
                                  format=format, channels=channels, subtype=subtype) as f:
                    with sd.InputStream(samplerate=sample_rate, device=device,
                                        channels=channels, callback=audio_callback,
                                        latency=latency, blocksize=blocksize):
                        self.start_recording()
                        get_bus().post(SoundRecordingStartedEvent(filename=outfile))
                        self.logger.info('Started recording from device [{}] to [{}]'.
                                         format(device, outfile))

                        recording_started_time = time.time()

                        while self._get_recording_state() != RecordingState.STOPPED \
                                and (duration is None or
                                     time.time() - recording_started_time < duration):
                            while self._get_recording_state() == RecordingState.PAUSED:
                                self.recording_paused_changed.wait()

                            get_args = {
                                'block': True,
                                'timeout': max(0, duration - (time.time() - recording_started_time)),
                            } if duration is not None else {}

                            data = q.get(**get_args)
                            if data and time.time() - data.get('timestamp') <= 1.0:
                                # Only write the block if the latency is still acceptable
                                f.write(data['data'])

                    f.flush()

            except queue.Empty:
                self.logger.warning('Recording timeout: audio callback failed?')
            finally:
                self.stop_recording()
                get_bus().post(SoundRecordingStoppedEvent(filename=outfile))

        Thread(target=recording_thread,
               args=(
                   outfile, duration, device, sample_rate, format, blocksize, latency, channels, subtype)
               ).start()

        Records audio to a sound file (support formats: wav, raw)

        :param outfile: Sound file (default: the method will create a temporary file with the recording)
        :type outfile: str

        :param duration: Recording duration in seconds (default: record until stop event)
        :type duration: float

        :param device: Input device (default: default configured device or system default audio input if not configured)
        :type device: int or str

        :param sample_rate: Recording sample rate (default: device default rate)
        :type sample_rate: int

        :param format: Audio format (default: WAV)
        :type format: str

        :param blocksize: Audio block size (default: configured `input_blocksize` or 2048)
        :type blocksize: int

        :param latency: Device latency in seconds (default: 0)
        :type latency: float

        :param channels: Number of channels (default: 1)
        :type channels: int

        :param subtype: Recording subtype - see `Soundfile docs - Subtypes <https://pysoundfile.readthedocs.io/en/0.9.0/#soundfile.available_subtypes>`_ for a list of the available subtypes (default: PCM_24)
        :type subtype: str
        
Records audio to a sound file (support formats: wav, raw)
Records audio to a sound file ( support formats : wav raw )
def record(self, outfile=None, duration=None, device=None, sample_rate=None,
               format=None, blocksize=None, latency=0, channels=1, subtype='PCM_24'):
        def recording_thread(outfile, duration, device, sample_rate, format,
                             blocksize, latency, channels, subtype):
            import sounddevice as sd
            self.recording_paused_changed.clear()
            if outfile:
                outfile = os.path.abspath(os.path.expanduser(outfile))
                if os.path.isfile(outfile):
                    self.logger.info('Removing existing audio file {}'.format(outfile))
                    os.unlink(outfile)
            else:
                outfile = tempfile.NamedTemporaryFile(
                    prefix='recording_', suffix='.wav', delete=False,
                    dir=tempfile.gettempdir()).name
            if device is None:
                device = self.input_device
            if device is None:
                device = self._get_default_device('input')
            if sample_rate is None:
                dev_info = sd.query_devices(device, 'input')
                sample_rate = int(dev_info['default_samplerate'])
            if blocksize is None:
                blocksize = self.input_blocksize
            q = queue.Queue()
            def audio_callback(indata, frames, duration, status):
                while self._get_recording_state() == RecordingState.PAUSED:
                    self.recording_paused_changed.wait()
                if status:
                    self.logger.warning('Recording callback status: {}'.format(
                        str(status)))
                q.put({
                    'timestamp': time.time(),
                    'frames': frames,
                    'time': duration,
                    'data': indata.copy()
                })
            try:
                import soundfile as sf
                import numpy
                with sf.SoundFile(outfile, mode='w', samplerate=sample_rate,
                                  format=format, channels=channels, subtype=subtype) as f:
                    with sd.InputStream(samplerate=sample_rate, device=device,
                                        channels=channels, callback=audio_callback,
                                        latency=latency, blocksize=blocksize):
                        self.start_recording()
                        get_bus().post(SoundRecordingStartedEvent(filename=outfile))
                        self.logger.info('Started recording from device [{}] to [{}]'.
                                         format(device, outfile))
                        recording_started_time = time.time()
                        while self._get_recording_state() != RecordingState.STOPPED \
                                and (duration is None or
                                     time.time() - recording_started_time < duration):
                            while self._get_recording_state() == RecordingState.PAUSED:
                                self.recording_paused_changed.wait()
                            get_args = {
                                'block': True,
                                'timeout': max(0, duration - (time.time() - recording_started_time)),
                            } if duration is not None else {}
                            data = q.get(**get_args)
                            if data and time.time() - data.get('timestamp') <= 1.0:
                                f.write(data['data'])
                    f.flush()
            except queue.Empty:
                self.logger.warning('Recording timeout: audio callback failed?')
            finally:
                self.stop_recording()
                get_bus().post(SoundRecordingStoppedEvent(filename=outfile))
        Thread(target=recording_thread,
               args=(
                   outfile, duration, device, sample_rate, format, blocksize, latency, channels, subtype)
               ).start()
def record ( self , outfile = None , duration = None , device = None , sample_rate = None , format = None , blocksize = None , latency = 0 , channels = 1 , subtype = 'PCM_24' ) : def recording_thread ( outfile , duration , device , sample_rate , format , blocksize , latency , channels , subtype ) : import sounddevice as sd self . recording_paused_changed . clear ( ) if outfile : outfile = os . path . abspath ( os . path . expanduser ( outfile ) ) if os . path . isfile ( outfile ) : self . logger . info ( 'Removing existing audio file {}' . format ( outfile ) ) os . unlink ( outfile ) else : outfile = tempfile . NamedTemporaryFile ( prefix = 'recording_' , suffix = '.wav' , delete = False , dir = tempfile . gettempdir ( ) ) . name if device is None : device = self . input_device if device is None : device = self . _get_default_device ( 'input' ) if sample_rate is None : dev_info = sd . query_devices ( device , 'input' ) sample_rate = int ( dev_info [ 'default_samplerate' ] ) if blocksize is None : blocksize = self . input_blocksize q = queue . Queue ( ) def audio_callback ( indata , frames , duration , status ) : while self . _get_recording_state ( ) == RecordingState . PAUSED : self . recording_paused_changed . wait ( ) if status : self . logger . warning ( 'Recording callback status: {}' . format ( str ( status ) ) ) q . put ( { 'timestamp' : time . time ( ) , 'frames' : frames , 'time' : duration , 'data' : indata . copy ( ) } ) try : import soundfile as sf import numpy with sf . SoundFile ( outfile , mode = 'w' , samplerate = sample_rate , format = format , channels = channels , subtype = subtype ) as f : with sd . InputStream ( samplerate = sample_rate , device = device , channels = channels , callback = audio_callback , latency = latency , blocksize = blocksize ) : self . start_recording ( ) get_bus ( ) . post ( SoundRecordingStartedEvent ( filename = outfile ) ) self . logger . info ( 'Started recording from device [{}] to [{}]' . format ( device , outfile ) ) recording_started_time = time . time ( ) while self . _get_recording_state ( ) != RecordingState . STOPPED and ( duration is None or time . time ( ) - recording_started_time < duration ) : while self . _get_recording_state ( ) == RecordingState . PAUSED : self . recording_paused_changed . wait ( ) get_args = { 'block' : True , 'timeout' : max ( 0 , duration - ( time . time ( ) - recording_started_time ) ) , } if duration is not None else { } data = q . get ( ** get_args ) if data and time . time ( ) - data . get ( 'timestamp' ) <= 1.0 : f . write ( data [ 'data' ] ) f . flush ( ) except queue . Empty : self . logger . warning ( 'Recording timeout: audio callback failed?' ) finally : self . stop_recording ( ) get_bus ( ) . post ( SoundRecordingStoppedEvent ( filename = outfile ) ) Thread ( target = recording_thread , args = ( outfile , duration , device , sample_rate , format , blocksize , latency , channels , subtype ) ) . start ( )
Records audio to a sound file (support formats: wav, raw)
Records audio to a sound file ( support formats : wav raw )
"""
        Records audio to a sound file (support formats: wav, raw)

        :param outfile: Sound file (default: the method will create a temporary file with the recording)
        :type outfile: str

        :param duration: Recording duration in seconds (default: record until stop event)
        :type duration: float

        :param device: Input device (default: default configured device or system default audio input if not configured)
        :type device: int or str

        :param sample_rate: Recording sample rate (default: device default rate)
        :type sample_rate: int

        :param format: Audio format (default: WAV)
        :type format: str

        :param blocksize: Audio block size (default: configured `input_blocksize` or 2048)
        :type blocksize: int

        :param latency: Device latency in seconds (default: 0)
        :type latency: float

        :param channels: Number of channels (default: 1)
        :type channels: int

        :param subtype: Recording subtype - see `Soundfile docs - Subtypes <https://pysoundfile.readthedocs.io/en/0.9.0/#soundfile.available_subtypes>`_ for a list of the available subtypes (default: PCM_24)
        :type subtype: str
        """ # Only write the block if the latency is still acceptable
self
outfile
Sound file (default: the method will create a temporary file with the recording)
Sound file ( default : the method will create a temporary file with the recording )
duration
Recording duration in seconds (default: record until stop event)
Recording duration in seconds ( default : record until stop event )
device
Input device (default: default configured device or system default audio input if not configured)
Input device ( default : default configured device or system default audio input if not configured )
sample_rate
Recording sample rate (default: device default rate)
Recording sample rate ( default : device default rate )
format
Audio format (default: WAV)
Audio format ( default : WAV )
blocksize
Audio block size (default: configured `input_blocksize` or 2048)
Audio block size ( default : configured ` input_blocksize ` or 2048 )
latency
Device latency in seconds (default: 0)
Device latency in seconds ( default : 0 )
channels
Number of channels (default: 1)
Number of channels ( default : 1 )
subtype
Recording subtype - see `Soundfile docs - Subtypes `_ for a list of the available subtypes (default: PCM_24)
Recording subtype - see ` Soundfile docs - Subtypes ` _ for a list of the available subtypes ( default : PCM_24 )