Run through a single audio file
435582
def train_on_audio(self, fn: str):
        """"""
        save_test = random() > 0.8
        audio = load_audio(fn)
        num_chunks = len(audio) // self.args.chunk_size

        self.listener.clear()

        for i, chunk in enumerate(chunk_audio(audio, self.args.chunk_size)):
            print('\r' + str(i * 100. / num_chunks) + '%', end='', flush=True)
            self.audio_buffer = np.concatenate((self.audio_buffer[len(chunk):], chunk))
            conf = self.listener.update(chunk)
            if conf > self.args.threshold:
                self.samples_since_train += 1
                name = splitext(basename(fn))[0] + '-' + str(i) + '.wav'
                name = join(self.args.folder, 'test' if save_test else '', 'not-wake-word',
                            'generated', name)
                save_audio(name, self.audio_buffer)
                print()
                print('Saved to:', name)

            if not save_test and self.samples_since_train >= self.args.delay_samples and \
                    self.args.epochs > 0:
                self.samples_since_train = 0
                self.retrain()
765318
def audio(hsh, key = nil)
      if !hsh.nil? && hsh.length
        if key.nil?
          hsh['mp3'] ? hsh['mp3'] : hsh['m4a'] ? hsh['m4a'] : hsh['ogg'] ? hsh['ogg'] : hsh['opus'] ? hsh['opus'] : hsh.values.first
        else
          hsh[key]
        end
      end
    end
1097120
def _read_audio_data(self, file_path):
        
        try:
            self.log(u"Reading audio data...")
            # if we know the TTS outputs to PCM16 mono WAVE
            # with the correct sample rate,
            # we can read samples directly from it,
            # without an intermediate conversion through ffmpeg
            audio_file = AudioFile(
                file_path=file_path,
                file_format=self.OUTPUT_AUDIO_FORMAT,
                rconf=self.rconf,
                logger=self.logger
            )
            audio_file.read_samples_from_file()
            self.log([u"Duration of '%s': %f", file_path, audio_file.audio_length])
            self.log(u"Reading audio data... done")
            return (True, (
                audio_file.audio_length,
                audio_file.audio_sample_rate,
                audio_file.audio_format,
                audio_file.audio_samples
            ))
        except (AudioFileUnsupportedFormatError, OSError) as exc:
            self.log_exc(u"An unexpected error occurred while reading audio data", exc, True, None)
            return (False, None)
389426
def _load_audio_list(self, path):
        

        result = {}

        for entry in textfile.read_separated_lines_generator(path, separator='\t', max_columns=4):
            for i in range(len(entry)):
                if entry[i] == '\\N':
                    entry[i] = None

            if len(entry) < 4:
                entry.extend([None] * (4 - len(entry)))

            if not self.include_empty_licence and entry[2] is None:
                continue

            if self.include_licenses is not None and entry[2] not in self.include_licenses:
                continue

            result[entry[0]] = entry[1:]

        return result
110956
def run(self):
        '''
        
        '''

        self._log('About to perform NifTI to %s conversion...\n' %
                  self._str_outputFileType)

        frames     = 1
        frameStart = 0
        frameEnd   = 0

        sliceStart = 0
        sliceEnd   = 0

        if self._b_4D:
            self._log('4D volume detected.\n')
            frames = self._Vnp_4DVol.shape[3]
        if self._b_3D:
            self._log('3D volume detected.\n')

        if self._b_convertMiddleFrame:
            self._frameToConvert = int(frames/2)

        if self._frameToConvert == -1:
            frameEnd    = frames
        else:
            frameStart  = self._frameToConvert
            frameEnd    = self._frameToConvert + 1

        for f in range(frameStart, frameEnd):
            if self._b_4D:
                self._Vnp_3DVol = self._Vnp_4DVol[:,:,:,f]
            slices     = self._Vnp_3DVol.shape[2]
            if self._b_convertMiddleSlice:
                self._sliceToConvert = int(slices/2)

            if self._sliceToConvert == -1:
                sliceEnd    = -1
            else:
                sliceStart  = self._sliceToConvert
                sliceEnd    = self._sliceToConvert + 1

            misc.mkdir(self._str_outputDir)
            if self._b_reslice:
                for dim in ['x', 'y', 'z']:
                    self.dim_save(dimension = dim, makeSubDir = True, indexStart = sliceStart, indexStop = sliceEnd, rot90 = True)
            else:
                self.dim_save(dimension = 'z', makeSubDir = False, indexStart = sliceStart, indexStop = sliceEnd, rot90 = True)
428478
function audioExt (name) {
  var ext = path.extname(name)
  return ['.wav', '.ogg', '.mp3'].indexOf(ext) > -1 ? ext : null
}
961562
def play(song, artist=None, album=None):
	""""""

	if not settings.platformCompatible():
		return False

	if song and not artist and not album:
		(output, error) = subprocess.Popen(["osascript", "-e", DEFAULT_ITUNES_PLAY % (song, song, song)], stdout=subprocess.PIPE).communicate()
		if output:
			speech.speak("Playing " + output)
		else:
			speech.speak("Unable to find " + song + " in your library.")

	elif song and artist and not album:
		(output, error) = subprocess.Popen(["osascript", "-e", ITUNES_SONG_AND_ARTIST % (song, artist, song, artist)], stdout=subprocess.PIPE).communicate()
		if output:
			speech.speak("Playing " + output)
		else:
			speech.speak("Unable to find " + song + " in your library.")

	elif album and artist and not song:
		(output, error) = subprocess.Popen(["osascript", "-e", ITUNES_ALBUM_AND_ARTIST % (artist, album)], stdout=subprocess.PIPE).communicate()
		if output:
			speech.speak("Playing " + output)
		else:
			speech.speak("Unable to find " + song + " in your library.")

	elif album and not artist and not song:
		(output, error) = subprocess.Popen(["osascript", "-e", ITUNES_ALBUM % (album)], stdout=subprocess.PIPE).communicate()
		if output:
			speech.speak("Playing " + output)
		else:
			speech.speak("Unable to find " + song + " in your library.")

	elif artist and not album and not song:
		(output, error) = subprocess.Popen(["osascript", "-e", ITUNES_ARTIST % (artist)], stdout=subprocess.PIPE).communicate()
		if output:
			speech.speak("Playing " + output)
		else:
			speech.speak("Unable to find " + song + " in your library.")
1346078
def play(self):
		
		### First do some status checks

		# Make sure a file is loaded
		if self.status == UNINITIALIZED or self.clip is None:
			raise RuntimeError("Player uninitialized or no file loaded")

		# Check if playback has already finished (rewind needs to be called first)
		if self.status == EOS:
			logger.debug("End of stream has already been reached")
			return

		# Check if playback hasn't already been started (and thus if play()
		# has not been called before from another thread for instance)
		if self.status in [PLAYING,PAUSED]:
			logger.warning("Video already started")
			return

		### If all is in order start the general playing loop
		if self.status == READY:
			self.status = PLAYING

		self.last_frame_no = 0

		if not hasattr(self,"renderloop") or not self.renderloop.isAlive():
			if self.audioformat:
				# Chop the total stream into separate audio chunks that are the
				# lenght of a video frame (this way the index of each chunk 
				# corresponds to the video frame it belongs to.)
				self.__calculate_audio_frames()
				# Start audio handling thread. This thread places audioframes
				# into a sound buffer, untill this buffer is full.
				self.audioframe_handler = threading.Thread(
					target=self.__audiorender_thread)
				self.audioframe_handler.start()

			# Start main rendering loop.
			self.renderloop = threading.Thread(target=self.__render)
			self.renderloop.start()
		else:
			logger.warning("Rendering thread already running!")
1013336
def run(self):
		
		if not hasattr(self, 'queue'):
			raise RuntimeError("Audio queue is not intialized.")
		self.keep_listening = True
		self.stream.start()
		
		while self.keep_listening:
			try:
				chunk = self.queue.get(timeout=queue_timeout)
				underflowed = self.stream.write(chunk)
				if underflowed:
					logger.debug("Buffer underrun")
			except Empty:
				pass

		self.stream.stop()
		self.stream.close()
826140
def main():
    

    # make sure we have enough parameters
    if len(sys.argv) < 6:
        print("You must pass five arguments: QUIT_AFTER BACKWARDS TEXT_FILE_PATH AUDIO_FILE_PATH DATA_FILE_PATH")
        return 1

    # read parameters
    c_quit_after = float(sys.argv[1])   # NOTE: cew needs float, not TimeValue
    c_backwards = int(sys.argv[2])
    text_file_path = sys.argv[3]
    audio_file_path = sys.argv[4]
    data_file_path = sys.argv[5]

    # read (voice_code, text) from file
    s_text = []
    with io.open(text_file_path, "r", encoding="utf-8") as text:
        for line in text.readlines():
            # NOTE: not using strip() to avoid removing trailing blank characters
            line = line.replace(u"\n", u"").replace(u"\r", u"")
            idx = line.find(" ")
            if idx > 0:
                f_voice_code = line[:idx]
                f_text = line[(idx + 1):]
                s_text.append((f_voice_code, f_text))

    # convert to bytes/unicode as required by subprocess
    c_text = []
    if gf.PY2:
        for f_voice_code, f_text in s_text:
            c_text.append((gf.safe_bytes(f_voice_code), gf.safe_bytes(f_text)))
    else:
        for f_voice_code, f_text in s_text:
            c_text.append((gf.safe_unicode(f_voice_code), gf.safe_unicode(f_text)))

    try:
        import aeneas.cew.cew
        sr, sf, intervals = aeneas.cew.cew.synthesize_multiple(
            audio_file_path,
            c_quit_after,
            c_backwards,
            c_text
        )
        with io.open(data_file_path, "w", encoding="utf-8") as data:
            data.write(u"%d\n" % (sr))
            data.write(u"%d\n" % (sf))
            data.write(u"\n".join([u"%.3f %.3f" % (i[0], i[1]) for i in intervals]))
    except Exception as exc:
        print(u"Unexpected error: %s" % str(exc))
27709
def readAudioFile(path):
    '''
    
    '''
    extension = os.path.splitext(path)[1]

    try:
        #if extension.lower() == '.wav':
            #[Fs, x] = wavfile.read(path)
        if extension.lower() == '.aif' or extension.lower() == '.aiff':
            s = aifc.open(path, 'r')
            nframes = s.getnframes()
            strsig = s.readframes(nframes)
            x = numpy.fromstring(strsig, numpy.short).byteswap()
            Fs = s.getframerate()
        elif extension.lower() == '.mp3' or extension.lower() == '.wav' or extension.lower() == '.au' or extension.lower() == '.ogg':            
            try:
                audiofile = AudioSegment.from_file(path)
            #except pydub.exceptions.CouldntDecodeError:
            except:
                print("Error: file not found or other I/O error. "
                      "(DECODING FAILED)")
                return (-1,-1)                

            if audiofile.sample_width==2:                
                data = numpy.fromstring(audiofile._data, numpy.int16)
            elif audiofile.sample_width==4:
                data = numpy.fromstring(audiofile._data, numpy.int32)
            else:
                return (-1, -1)
            Fs = audiofile.frame_rate
            x = []
            for chn in list(range(audiofile.channels)):
                x.append(data[chn::audiofile.channels])
            x = numpy.array(x).T
        else:
            print("Error in readAudioFile(): Unknown file type!")
            return (-1,-1)
    except IOError: 
        print("Error: file not found or other I/O error.")
        return (-1,-1)

    if x.ndim==2:
        if x.shape[1]==1:
            x = x.flatten()

    return (Fs, x)
47171
def _serve_individual_audio(self, request):
    """"""
    tag = request.args.get('tag')
    run = request.args.get('run')
    index = int(request.args.get('index'))
    sample = int(request.args.get('sample', 0))
    events = self._filter_by_sample(self._multiplexer.Tensors(run, tag), sample)
    data = tensor_util.make_ndarray(events[index].tensor_proto)[sample, 0]
    mime_type = self._get_mime_type(run, tag)
    return http_util.Respond(request, data, mime_type)
440399
def main():
    """"""
    options = docopt(__doc__, version=__version__)
    if options['segment']:
        segment(
            options['<file>'],
            options['--output'],
            options['--target-duration'],
            options['--mpegts'],
        )
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;
  }
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;
    }
}
1272343
def play_next(self, stream_url=None, offset=0, opaque_token=None):
        """"""

        directive = self._play_directive('REPLACE_ENQUEUED')
        directive['audioItem'] = self._audio_item(stream_url=stream_url, offset=offset, opaque_token=opaque_token)
        self._response['directives'].append(directive)
        return self
552709
def _populate_audio_file(self):
        
        self.log(u"Populate audio file...")
        if self.audio_file_path_absolute is not None:
            self.log([u"audio_file_path_absolute is '%s'", self.audio_file_path_absolute])
            self.audio_file = AudioFile(
                file_path=self.audio_file_path_absolute,
                logger=self.logger
            )
            self.audio_file.read_properties()
        else:
            self.log(u"audio_file_path_absolute is None")
        self.log(u"Populate audio file... done")