Args:
        audio: Audio verified to be of `sample_rate`

    Returns:
        array<float>: Vector representation of audio
164682
def vectorize(audio: np.ndarray) -> np.ndarray:
    
    if len(audio) > pr.max_samples:
        audio = audio[-pr.max_samples:]
    features = vectorize_raw(audio)
    if len(features) < pr.n_features:
        features = np.concatenate([
            np.zeros((pr.n_features - len(features), features.shape[1])),
            features
        ])
    if len(features) > pr.n_features:
        features = features[-pr.n_features:]

    return features
1061663
public function getAudioSampleRate()
    {
        if ($this->audioSampleRate === null) {
            $match = [];
            preg_match(self::$REGEX_AUDIO_SAMPLE_RATE, $this->output, $match);
            $this->audioSampleRate = (int)(array_key_exists(1, $match) ? $match[1] : 0);
        }

        return $this->audioSampleRate;
    }
668019
def samplerate(self):
        """"""
        if hasattr(self.mgfile.info, 'sample_rate'):
            return self.mgfile.info.sample_rate
        elif self.type == 'opus':
            # Opus is always 48kHz internally.
            return 48000
        return 0
1037275
def write(self, buf):
        
        buf = align_buf(buf, self._sample_width)
        buf = normalize_audio_buffer(buf, self.volume_percentage)
        return self._sink.write(buf)
1175339
def load_randomly_augmented_audio(path, sample_rate=16000, tempo_range=(0.85, 1.15),
                                  gain_range=(-6, 8)):
    
    low_tempo, high_tempo = tempo_range
    tempo_value = np.random.uniform(low=low_tempo, high=high_tempo)
    low_gain, high_gain = gain_range
    gain_value = np.random.uniform(low=low_gain, high=high_gain)
    audio = augment_audio_with_sox(path=path, sample_rate=sample_rate,
                                   tempo=tempo_value, gain=gain_value)
    return audio
227931
def convert(self):
        
        wav_directory = self._pre_convert()
        for mp3_filename in self.mp3_directory.glob('**/*.mp3'):
            wav_filename = path.join(wav_directory, os.path.splitext(os.path.basename(mp3_filename))[0] + ".wav")
            if not path.exists(wav_filename):
                _logger.debug("Converting mp3 file %s to wav file %s" % (mp3_filename, wav_filename))
                transformer = Transformer()
                transformer.convert(samplerate=SAMPLE_RATE, n_channels=N_CHANNELS, bitdepth=BITDEPTH)
                transformer.build(str(mp3_filename), str(wav_filename))
            else:
                _logger.debug("Already converted mp3 file %s to wav file %s" % (mp3_filename, wav_filename))
        return wav_directory
419289
def chunk_audio_pieces(self, pieces, chunk_size):
        """"""
        left_over = np.array([])
        for piece in pieces:
            if left_over.size == 0:
                combined = piece
            else:
                combined = np.concatenate([left_over, piece], axis=-1)
            for chunk in chunk_audio(combined.T, chunk_size):
                yield chunk.T
            left_over = piece[-(len(piece) % chunk_size):]
798955
def sample_rate(self, value):
        
        if value == self._defaults['sampleRate'] and 'sampleRate' in self._values:
            del self._values['sampleRate']
        else:
            self._values['sampleRate'] = value
1243074
def frame_generator(frame_duration_ms, audio, sample_rate):
    
    n = int(sample_rate * (frame_duration_ms / 1000.0) * 2)
    offset = 0
    timestamp = 0.0
    duration = (float(n) / sample_rate) / 2.0
    while offset + n < len(audio):
        yield Frame(audio[offset:offset + n], timestamp, duration)
        timestamp += duration
        offset += n
227265
def sampling_rate(self):
        
        with self.container.open_if_needed(mode='r') as cnt:
            return cnt.get(self.key)[1]
763641
def get_samples(self, sample_count):
        
        if self.amplitude.value <= 0:
            return None
        # Build samples by rolling the period cache through the buffer
        rolled_array = numpy.roll(self.wave_cache,
                                  -1 * self.last_played_sample)
        # Append remaining partial period
        full_count, remainder = divmod(sample_count, self.cache_length)
        final_subarray = rolled_array[:int(remainder)]
        return_array = numpy.concatenate((numpy.tile(rolled_array, full_count),
                                          final_subarray))
        # Keep track of where we left off to prevent popping between chunks
        self.last_played_sample = int(((self.last_played_sample + remainder) %
                                       self.cache_length))
        # Multiply output by amplitude
        return return_array * (self.amplitude.value *
                               self.amplitude_multiplier)
1192463
def _preprocess_data(audio_data, verbose=True):
        '''
        
        '''
        from .vggish_input import waveform_to_examples

        last_progress_update = _time.time()
        progress_header_printed = False

        # Can't run as a ".apply(...)" due to numba.jit decorator issue:
        # https://github.com/apple/turicreate/issues/1216
        preprocessed_data, audio_data_index = [], []
        for i, audio_dict in enumerate(audio_data):
            scaled_data = audio_dict['data'] / 32768.0
            data = waveform_to_examples(scaled_data, audio_dict['sample_rate'])

            for j in data:
                preprocessed_data.append([j])
                audio_data_index.append(i)

            # If `verbose` is set, print an progress update about every 20s
            if verbose and _time.time() - last_progress_update >= 20:
                if not progress_header_printed:
                    print("Preprocessing audio data -")
                    progress_header_printed = True
                print("Preprocessed {} of {} examples".format(i, len(audio_data)))
                last_progress_update = _time.time()

        if progress_header_printed:
            print("Preprocessed {} of {} examples\n".format(len(audio_data), len(audio_data)))
        return _np.asarray(preprocessed_data), audio_data_index
258646
def main(input_filename, format):
    

    # open the file & convert to wav
    song_data = AudioSegment.from_file(input_filename, format=format)
    song_data = song_data.set_channels(1)  # convert to mono
    wav_tmp = song_data.export(format="wav")  # write to a tmp file buffer
    wav_tmp.seek(0)
    rate, wav_data = wavfile.read(wav_tmp)

    rows_per_second = (1 + (rate - WIDTH)) // FRAME_STRIDE

    # Calculate a coarser window for matching
    window_size = (rows_per_second // TIME_STRIDE, (WIDTH // 2) // FREQ_STRIDE)
    peaks = resound.get_peaks(np.array(wav_data), window_size=window_size)

    # half width (nyquist freq) & half size (window is +/- around the middle)
    f_width = WIDTH // (2 * FREQ_STRIDE) * 2
    t_gap = 1 * rows_per_second
    t_width = 2 * rows_per_second
    fingerprints = resound.hashes(peaks, f_width=f_width, t_gap=t_gap, t_width=t_width)  # hash, offset pairs

    return fingerprints
147923
public Integer[] getSupportedSampleRates() {
		IntPointer sampleRatesPointer = avCodec.supported_samplerates();

		if (getType() != MediaType.AUDIO || sampleRatesPointer == null)
			return null;

		List<Integer> sampleRates = new ArrayList<Integer>();

		int sampleRate;
		int index = 0;
		while ((sampleRate = sampleRatesPointer.get(index++)) != 0)
			sampleRates.add(sampleRate);

		// ascending order
		Collections.sort(sampleRates);

		return sampleRates.toArray(new Integer[0]);
	}
745009
private static float calculateDuration(int layer, int sampleRate) {
        int sampleCount = (layer == AudioFrame.LAYER_1) ? SAMPLE_COUNT_L1 : SAMPLE_COUNT_L2;
        return (1000.0f / sampleRate) * sampleCount;
    }
685263
def sample_rate(self, sample_rate):
        

        assert issubclass(sample_rate.__class__, int)

        return self.__push('sample_rate', sample_rate)
179921
def sample_normalize(self, k_samples=1000, overwrite=False):
        
        log = logUtil.getlogger()
        log.info("Calculating mean and std from samples")
        # if k_samples is negative then it goes through total dataset
        if k_samples < 0:
            audio_paths = self.audio_paths

        # using sample
        else:
            k_samples = min(k_samples, len(self.train_audio_paths))
            samples = self.rng.sample(self.train_audio_paths, k_samples)
            audio_paths = samples
        manager = Manager()
        return_dict = manager.dict()
        jobs = []
        for threadIndex in range(cpu_count()):
            proc = Process(target=self.preprocess_sample_normalize, args=(threadIndex, audio_paths, overwrite, return_dict))
            jobs.append(proc)
            proc.start()
        for proc in jobs:
            proc.join()

        feat = np.sum(np.vstack([item['feat'] for item in return_dict.values()]), axis=0)
        count = sum([item['count'] for item in return_dict.values()])
        feat_squared = np.sum(np.vstack([item['feat_squared'] for item in return_dict.values()]), axis=0)

        self.feats_mean = feat / float(count)
        self.feats_std = np.sqrt(feat_squared / float(count) - np.square(self.feats_mean))
        np.savetxt(
            generate_file_path(self.save_dir, self.model_name, 'feats_mean'), self.feats_mean)
        np.savetxt(
            generate_file_path(self.save_dir, self.model_name, 'feats_std'), self.feats_std)
        log.info("End calculating mean and std from samples")