Generates chunks of audio that represent the wakeword stream
340
def generate_wakeword_pieces(self, volume):
        """"""
        while True:
            target = 1 if random() > 0.5 else 0
            it = self.pos_files_it if target else self.neg_files_it
            sample_file = next(it)
            yield self.layer_with(self.normalize_volume_to(load_audio(sample_file), volume), target)
            yield self.layer_with(np.zeros(int(pr.sample_rate * (0.5 + 2.0 * random()))), 0)
887483
function(arraybuffer, self) {
    // Fire a load error if something broke.
    var error = function() {
      self._emit('loaderror', null, 'Decoding audio data failed.');
    };

    // Load the sound on success.
    var success = function(buffer) {
      if (buffer && self._sounds.length > 0) {
        cache[self._src] = buffer;
        loadSound(self, buffer);
      } else {
        error();
      }
    };

    // Decode the buffer into an audio source.
    if (typeof Promise !== 'undefined' && Howler.ctx.decodeAudioData.length === 1) {
      Howler.ctx.decodeAudioData(arraybuffer).then(success).catch(error);
    } else {
      Howler.ctx.decodeAudioData(arraybuffer, success, error);
    }
  }
335457
def parse_streams(self):
        
        logger.debug("Parsing streams of {}".format(self.input_file))

        cmd = [
            self.ffmpeg_normalize.ffmpeg_exe, '-i', self.input_file,
            '-c', 'copy', '-t', '0', '-map', '0',
            '-f', 'null', NUL
        ]

        cmd_runner = CommandRunner(cmd)
        cmd_runner.run_command()
        output = cmd_runner.get_output()

        logger.debug("Stream parsing command output:")
        logger.debug(output)

        output_lines = [line.strip() for line in output.split('\n')]

        for line in output_lines:

            if not line.startswith('Stream'):
                continue

            stream_id_match = re.search(r'#0:([\d]+)', line)
            if stream_id_match:
                stream_id = int(stream_id_match.group(1))
                if stream_id in self._stream_ids():
                    continue
            else:
                continue

            if 'Audio' in line:
                logger.debug("Found audio stream at index {}".format(stream_id))
                sample_rate_match = re.search(r'(\d+) Hz', line)
                sample_rate = int(sample_rate_match.group(1)) if sample_rate_match else None
                bit_depth_match = re.search(r's(\d+)p?,', line)
                bit_depth = int(bit_depth_match.group(1)) if bit_depth_match else None
                self.streams['audio'][stream_id] = AudioStream(self, stream_id, sample_rate, bit_depth)

            elif 'Video' in line:
                logger.debug("Found video stream at index {}".format(stream_id))
                self.streams['video'][stream_id] = VideoStream(self, stream_id)

            elif 'Subtitle' in line:
                logger.debug("Found subtitle stream at index {}".format(stream_id))
                self.streams['subtitle'][stream_id] = SubtitleStream(self, stream_id)

        if not self.streams['audio']:
            raise FFmpegNormalizeError(
                "Input file {} does not contain any audio streams"
                .format(self.input_file))

        if os.path.splitext(self.output_file)[1].lower() in ['.wav', '.mp3', '.aac']:
            logger.warning(
                "Output file only supports one stream. "
                "Keeping only first audio stream."
            )
            first_stream = list(self.streams['audio'].values())[0]
            self.streams['audio'] = {first_stream.stream_id: first_stream}
            self.streams['video'] = {}
            self.streams['subtitle'] = {}
887148
def play(self, filename, translate=False):  # pragma: no cover
        '''
        
        '''
        # FIXME: Use platform-independent and async audio-output here
        # PyAudio looks most promising, too bad about:
        #  --allow-external PyAudio --allow-unverified PyAudio
        if translate:
            with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:
                fname = f.name
            with audioread.audio_open(filename) as f:
                with contextlib.closing(wave.open(fname, 'w')) as of:
                    of.setnchannels(f.channels)
                    of.setframerate(f.samplerate)
                    of.setsampwidth(2)
                    for buf in f:
                        of.writeframes(buf)
            filename = fname

        if winsound:
            winsound.PlaySound(str(filename), winsound.SND_FILENAME)
        else:
            cmd = ['aplay', str(filename)]
            self._logger.debug('Executing %s', ' '.join([pipes.quote(arg) for arg in cmd]))
            subprocess.call(cmd)

        if translate:
            os.remove(fname)
144965
def run(self, channels=None, samplerate=None, blocksize=None):
        """"""

        source = self.processors[0]
        items = self.processors[1:]

        # Check if any processor in items need to force the samplerate
        force_samplerate = set([item.force_samplerate for item in items
                                if item.force_samplerate])
        if force_samplerate:
            if len(force_samplerate) > 1:
                raise(ValueError,
                      "Some processors specify different samplerate")
            force_samplerate = force_samplerate.pop()

            if samplerate and samplerate != force_samplerate:
                raise(ValueError, "A processor try to force the samplerate")

            samplerate = force_samplerate

        source.setup(channels=channels, samplerate=samplerate,
                     blocksize=blocksize)
        source.SIG_STOP = False
        last = source

        # setup/reset processors and configure properties throughout the pipe
        for item in items:
            item.source_mediainfo = source.mediainfo()
            item.setup(channels=last.channels(),
                       samplerate=last.samplerate(),
                       blocksize=last.blocksize(),
                       totalframes=last.totalframes())
            self._register_streamer(item)
            last = item

        # now stream audio data along the pipe
        if self._stream_thread:
            self._running_cond.acquire()
        self._is_running = True
        if self._stream_thread:
            self._running_cond.notify()
            self._running_cond.release()

        eod = False

        if source.id() == 'live_decoder':
            # Set handler for Interruption signal
            import signal

            def signal_handler(signum, frame):
                source.stop()

            signal.signal(signal.SIGINT, signal_handler)

        while not eod:
            frames, eod = source.process()
            for item in items:
                frames, eod = item.process(frames, eod)

        if source.id() == 'live_decoder':
            # Restore default handler for Interruption signal
            signal.signal(signal.SIGINT, signal.SIG_DFL)

        # Post-processing
        for item in items:
            item.post_process()

        # Release source
        source.release()
        # Release processors
        for item in items:
            item.release()

        self._is_running = False
673618
def _generate_SAX(self):
        
        sections = {}
        self.value_min = self.time_series.min()
        self.value_max = self.time_series.max()
        # Break the whole value range into different sections.
        section_height = (self.value_max - self.value_min) / self.precision
        for section_number in range(self.precision):
            sections[section_number] = self.value_min + section_number * section_height
        # Generate SAX representation.
        self.sax = ''.join(self._generate_SAX_single(sections, value) for value in self.time_series.values)
1149305
def vectorize_raw(audio: np.ndarray) -> np.ndarray:
    """"""
    if len(audio) == 0:
        raise InvalidAudio('Cannot vectorize empty audio!')
    return vectorizers[pr.vectorizer](audio)
850096
def _load_audio_file(self):
        
        self._step_begin(u"load audio file")
        # NOTE file_format=None forces conversion to
        #      PCM16 mono WAVE with default sample rate
        audio_file = AudioFile(
            file_path=self.task.audio_file_path_absolute,
            file_format=None,
            rconf=self.rconf,
            logger=self.logger
        )
        audio_file.read_samples_from_file()
        self._step_end()
        return audio_file
95214
function(index) {
    var self = this;
    var sound;

    index = typeof index === 'number' ? index : self.index;
    var data = self.playlist[index];

    // If we already loaded this track, use the current one.
    // Otherwise, setup and load a new Howl.
    if (data.howl) {
      sound = data.howl;
    } else {
      sound = data.howl = new Howl({
        src: ['./audio/' + data.file + '.webm', './audio/' + data.file + '.mp3'],
        html5: true, // Force to HTML5 so that the audio can stream in (best for large files).
        onplay: function() {
          // Display the duration.
          duration.innerHTML = self.formatTime(Math.round(sound.duration()));

          // Start upating the progress of the track.
          requestAnimationFrame(self.step.bind(self));

          // Start the wave animation if we have already loaded
          wave.container.style.display = 'block';
          bar.style.display = 'none';
          pauseBtn.style.display = 'block';
        },
        onload: function() {
          // Start the wave animation.
          wave.container.style.display = 'block';
          bar.style.display = 'none';
          loading.style.display = 'none';
        },
        onend: function() {
          // Stop the wave animation.
          wave.container.style.display = 'none';
          bar.style.display = 'block';
          self.skip('next');
        },
        onpause: function() {
          // Stop the wave animation.
          wave.container.style.display = 'none';
          bar.style.display = 'block';
        },
        onstop: function() {
          // Stop the wave animation.
          wave.container.style.display = 'none';
          bar.style.display = 'block';
        },
        onseek: function() {
          // Start upating the progress of the track.
          requestAnimationFrame(self.step.bind(self));
        }
      });
    }

    // Begin playing the sound.
    sound.play();

    // Update the track display.
    track.innerHTML = (index + 1) + '. ' + data.title;

    // Show the pause button.
    if (sound.state() === 'loaded') {
      playBtn.style.display = 'none';
      pauseBtn.style.display = 'block';
    } else {
      loading.style.display = 'block';
      playBtn.style.display = 'none';
      pauseBtn.style.display = 'none';
    }

    // Keep track of the index we are currently playing.
    self.index = index;
  }
831187
function (bufferSize, numberOfIterations) {

    var bufSize = bufferSize || 16000,
        iterations = numberOfIterations || 100;

    for (var i = 0; i < iterations; i++) {
        var data = [];

        for (var k = 0; k < bufSize; k++) {
            data.push((parseFloat(Math.random() * 1.0) - 0.5));
        }

        // Dispatch an event
        var event = new CustomEvent('audioinput');
        event.data = data;
        window.dispatchEvent(event);
    }
}
1111507
def load_streams(chunks):
    
    chunks = peekable(chunks)
    while chunks:
        if six.PY3:
            dc = zlib.decompressobj(wbits=zlib.MAX_WBITS | 16)
        else:
            dc = zlib.decompressobj(zlib.MAX_WBITS | 16)
        yield load_stream(dc, chunks)
        if dc.unused_data:
            chunks = peekable(itertools.chain((dc.unused_data,), chunks))
357243
function makeMediaPeerProxy (api) {
    api.setStream = function(stream, completion) {
      api._.setStream(stream);

      if (completion) {
        if (stream.hasVideo()) {
          // FIX ME renderingStarted currently doesn't first
          // api.once('renderingStarted', completion);
          var verifyStream = function() {
            if (!api._) {
              completion(new $.Error('The plugin went away before the stream could be bound.'));
              return;
            }

            if (api._.videoWidth > 0) {
              // This fires a little too soon.
              setTimeout(completion, 200);
            }
            else {
              setTimeout(verifyStream, 500);
            }
          };

          setTimeout(verifyStream, 500);
        }
        else {
          // TODO Investigate whether there is a good way to detect
          // when the audio is ready. Does it even matter?

          // This fires a little too soon.
          setTimeout(completion, 200);
        }
      }

      return api;
    };

    return api;
  }
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
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
566828
def _wrap_stream_read(self, stream):
        
        import pyaudio
        if getattr(stream.read, '__func__', None) is pyaudio.Stream.read:
            stream.read = lambda x: pyaudio.Stream.read(stream, x // 2, False)
594673
def dataset_to_stream(dataset, input_name, num_chunks=0, append_targets=False):
  """"""
  for example in tfds.as_numpy(dataset):
    inp, out = example[0][input_name], example[1]
    if len(out.shape) > 1 and out.shape[-1] == 1:
      out = np.squeeze(out, axis=-1)
    if num_chunks > 0:
      inp = np.split(inp, num_chunks, axis=1)
      out = np.split(out, num_chunks, axis=1)
    if append_targets:
      inp = (inp, out)
    yield inp, out
1355724
function (data) {
    try {
        // Create an audio buffer to hold the data
        var audioBuffer = audioContext.createBuffer(captureCfg.channels, (data.length / captureCfg.channels),
            captureCfg.sampleRate);

        // Initialize the audio buffer with the data
        if (captureCfg.channels > 1) {
            // For multiple channels (stereo) we assume that the data is interleaved
            for (var i = 0; i < captureCfg.channels; i++) {
                var chdata = [],
                    index = 0;

                while (index < data.length) {
                    chdata.push(data[index + i]);
                    index += parseInt(captureCfg.channels);
                }

                audioBuffer.getChannelData(i).set(chdata);
            }
        }
        else {
            // For just one channels (mono)
            audioBuffer.getChannelData(0).set(data);
        }

        // Create a buffer source based on the audio buffer
        var source = audioContext.createBufferSource();
        source.buffer = audioBuffer;

        // Connect the buffer source to the gain node
        source.connect(micGainNode);

        // Play the audio immediately
        source.start(0);

        // Increase the debug counter for played data
        totalPlayedData += data.length;

        // Return the duration of the sound so that we can play the next sound when ended.
        return audioBuffer.duration;
    }
    catch(e) {
        alert("playAudio exception: " + e);
        return 100;
    }
}