Check if a wav contains data
492981
def empty_wav(wav_path: Union[Path, str]) -> bool:
    """"""
    with wave.open(str(wav_path), 'rb') as wav_f:
        return wav_f.getnframes() == 0
1204926
def audioread(filename):
    
    try:
        if '.wav' in filename.lower():
            fs, signal = wv.read(filename)
        elif '.call' in filename.lower():
            with open(filename, 'rb') as f:
                signal = np.fromfile(f, dtype=np.int16)
            fs = 333333
        else:
            raise IOError("Unsupported audio format for file: {}".format(filename))
    except:
        print u"Problem reading wav file"
        raise
    signal = signal.astype(float)
    return fs, signal
989208
def _wavGetInfo(f:Union[IO, str]) -> Tuple[SndInfo, Dict[str, Any]]:
    
    if isinstance(f, (str, bytes)):
        f = open(f, 'rb')
        needsclosing = True
    else:
        needsclosing = False
    fsize, bigendian = _wavReadRiff(f)
    fmt = ">i" if bigendian else "<i"
    while (f.tell() < fsize):
        chunk_id = f.read(4)
        if chunk_id == b'fmt ':
            chunksize, sampfmt, chans, sr, byterate, align, bits = _wavReadFmt(f, bigendian)
        elif chunk_id == b'data':
            datasize = _struct.unpack(fmt, f.read(4))[0]
            nframes = int(datasize / (chans * (bits / 8)))
            break
        else:
            _warnings.warn("chunk not understood: %s" % chunk_id)
            data = f.read(4)
            size = _struct.unpack(fmt, data)[0]
            f.seek(size, 1)
    encoding = _encoding(sampfmt, bits)
    if needsclosing:
        f.close()
    info = SndInfo(sr, nframes, chans, encoding, "wav")
    return info, {'fsize': fsize, 'bigendian': bigendian, 'datasize': datasize}
892850
def is_contains(self, data):
        
        if not data:
            return False
        data = self._compress_by_md5(data)
        result = True
        # cut the first two place,route to different block by block_num
        name = self.key + str(int(data[0:2], 16) % self.block_num)
        for h in self.hash_function:
            local_hash = h.hash(data)
            result = result & self.server.getbit(name, local_hash)
        return result
1054072
def main(input_filename, songname, format, counter):
    

    # 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)

    # extract peaks and compute constellation hashes & offsets
    peaks = resound.get_peaks(np.array(wav_data))
    fingerprints = list(resound.hashes(peaks))  # hash, offset pairs

    if not fingerprints:
        raise RuntimeError("No fingerprints detected in source file - check your parameters passed to Resound.")

    # Combine duplicate keys
    for fp, abs_offset in fingerprints:
        counter[fp].append((abs_offset, songname))

    print "    Identified {} keypoints in '{}'.".format(len(counter), songname)

    return counter
179789
function contains(arr, v) {
    var nIndex,
      nLen = arr.length;
    for (nIndex = 0; nIndex < nLen; nIndex++) {
      if (arr[nIndex][1] === v) {
        return true;
      }
    }
    return false;
  }
1362536
def detect_intent_stream(project_id, session_id, audio_file_path,
                         language_code):
    """"""
    import dialogflow_v2 as dialogflow
    session_client = dialogflow.SessionsClient()

    # Note: hard coding audio_encoding and sample_rate_hertz for simplicity.
    audio_encoding = dialogflow.enums.AudioEncoding.AUDIO_ENCODING_LINEAR_16
    sample_rate_hertz = 16000

    session_path = session_client.session_path(project_id, session_id)
    print('Session path: {}\n'.format(session_path))

    def request_generator(audio_config, audio_file_path):
        query_input = dialogflow.types.QueryInput(audio_config=audio_config)

        # The first request contains the configuration.
        yield dialogflow.types.StreamingDetectIntentRequest(
            session=session_path, query_input=query_input)

        # Here we are reading small chunks of audio data from a local
        # audio file.  In practice these chunks should come from
        # an audio input device.
        with open(audio_file_path, 'rb') as audio_file:
            while True:
                chunk = audio_file.read(4096)
                if not chunk:
                    break
                # The later requests contains audio data.
                yield dialogflow.types.StreamingDetectIntentRequest(
                    input_audio=chunk)

    audio_config = dialogflow.types.InputAudioConfig(
        audio_encoding=audio_encoding, language_code=language_code,
        sample_rate_hertz=sample_rate_hertz)

    requests = request_generator(audio_config, audio_file_path)
    responses = session_client.streaming_detect_intent(requests)

    print('=' * 20)
    for response in responses:
        print('Intermediate transcript: "{}".'.format(
                response.recognition_result.transcript))

    # Note: The result from the last response is the final transcript along
    # with the detected content.
    query_result = response.query_result

    print('=' * 20)
    print('Query text: {}'.format(query_result.query_text))
    print('Detected intent: {} (confidence: {})\n'.format(
        query_result.intent.display_name,
        query_result.intent_detection_confidence))
    print('Fulfillment text: {}\n'.format(
        query_result.fulfillment_text))
997070
protected function wavToMp3($data)
    {
        if (!file_exists(self::$lame_binary_path) || !is_executable(self::$lame_binary_path)) {
            throw new Exception('Lame binary "' . $this->lame_binary_path . '" does not exist or is not executable');
        }

        // size of wav data input
        $size = strlen($data);

        // file descriptors for reading and writing to the Lame process
        $descriptors = array(
                0 => array('pipe', 'r'), // stdin
                1 => array('pipe', 'w'), // stdout
                2 => array('pipe', 'a'), // stderr
        );

        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            // workaround for Windows conversion
            // writing to STDIN seems to hang indefinitely after writing approximately 0xC400 bytes
            $wavinput = tempnam(sys_get_temp_dir(), 'wav');
            if (!$wavinput) {
                throw new Exception('Failed to create temporary file for WAV to MP3 conversion');
            }
            file_put_contents($wavinput, $data);
            $size = 0;
        } else {
            $wavinput = '-'; // stdin
        }

        // Mono, variable bit rate, 32 kHz sampling rate, read WAV from stdin, write MP3 to stdout
        $cmd  = sprintf("%s -m m -v -b 32 %s -", self::$lame_binary_path, $wavinput);
        $proc = proc_open($cmd, $descriptors, $pipes);

        if (!is_resource($proc)) {
            throw new Exception('Failed to open process for MP3 encoding');
        }

        stream_set_blocking($pipes[0], 0); // set stdin to be non-blocking

        for ($written = 0; $written < $size; $written += $len) {
            // write to stdin until all WAV data is written
            $len = fwrite($pipes[0], substr($data, $written, 0x20000));

            if ($len === 0) {
                // fwrite wrote no data, make sure process is still alive, otherwise wait for it to process
                $status = proc_get_status($proc);
                if ($status['running'] === false) break;
                usleep(25000);
            } else if ($written < $size) {
                // couldn't write all data, small pause and try again
                usleep(10000);
            } else if ($len === false) {
                // fwrite failed, should not happen
                break;
            }
        }

        fclose($pipes[0]);

        $data = stream_get_contents($pipes[1]);
        $err  = trim(stream_get_contents($pipes[2]));

        fclose($pipes[1]);
        fclose($pipes[2]);

        $return = proc_close($proc);

        if ($wavinput != '-') unlink($wavinput); // delete temp file on Windows

        if ($return !== 0) {
            throw new Exception("Failed to convert WAV to MP3.  Shell returned ({$return}): {$err}");
        } else if ($written < $size) {
            throw new Exception('Failed to convert WAV to MP3.  Failed to write all data to encoder');
        }

        return $data;
    }
1369939
function (result) {
            if (result.stat('audioInputLevel')) {
              currentStats.audioSentPackets = Number(result.stat('packetsSent'));
              currentStats.audioSentPacketsLost = Number(result.stat('packetsLost'));
              currentStats.audioSentBytes =  Number(result.stat('bytesSent'));
              currentStats.audioCodec = result.stat('googCodecName');
              currentStats.audioRtt = Number(result.stat('googRtt'));
            } else if (result.stat('audioOutputLevel')) {
              currentStats.audioRecvPackets = Number(result.stat('packetsReceived'));
              currentStats.audioRecvPacketsLost = Number(result.stat('packetsLost'));
              currentStats.audioRecvBytes =  Number(result.stat('bytesReceived'));
              currentStats.audioCodec = result.stat('googCodecName');
            }
          }
1133218
def detect(str)
      raise ArgumentError, 'str must be a String' unless str.is_a?(String)

      j_instance.sentDetect(str).to_ary
    end
1319002
def check(self, datas, *filers):
        '''
            
        '''
        # special case : no filter : want to read all the feed
        if self.match == "" and self.does_not_match == '':
            yield datas
        # let's filtering :
        else:
            condition1 = False
            condition2 = False
            # arg contain the property from which we want to check the 'data'
            for prop in filers:
                # check if my datas contains my property
                if prop in datas:
                    # filter to find only this data
                    if self.match != '' and condition1 is False:
                        condition1 = self.filter_that(self.match,
                                                      datas[prop])
                    # filter to exclude this data,
                    # when found, continue to the next entry
                    if self.does_not_match != '' and condition2 is False:
                        condition2 = self.filter_that(self.does_not_match,
                                                      datas[prop])
                        if condition2:
                            continue
        if condition1 and condition2 is False:
            yield datas
449290
def check(self, data):
        """"""
        if isinstance(data, Iterable):
            data = "".join(str(x) for x in data)
        try:
            data = str(data)
        except UnicodeDecodeError:
            return False
        return bool(data and self.__regexp.match(data))
1361887
def _collect_data(directory, input_ext, target_ext):
  """"""
  # Directory from string to tuple pair of strings
  # key: the filepath to a datafile including the datafile's basename. Example,
  #   if the datafile was "/path/to/datafile.wav" then the key would be
  #   "/path/to/datafile"
  # value: a pair of strings (input_filepath, target_filepath)
  data_files = {}
  for root, _, filenames in os.walk(directory):
    input_files = [filename for filename in filenames if input_ext in filename]
    for input_filename in input_files:
      basename = input_filename.strip(input_ext)
      input_file = os.path.join(root, input_filename)
      target_file = os.path.join(root, basename + target_ext)
      key = os.path.join(root, basename)
      assert os.path.exists(target_file)
      assert key not in data_files
      data_files[key] = (input_file, target_file)
  return data_files
1187232
def is_matching(cls, file_path):
        
        if file_path.endswith(".ndata") and os.path.exists(file_path):
            try:
                with open(file_path, "r+b") as fp:
                    local_files, dir_files, eocd = parse_zip(fp)
                    contains_data = b"data.npy" in dir_files
                    contains_metadata = b"metadata.json" in dir_files
                    file_count = contains_data + contains_metadata  # use fact that True is 1, False is 0
                    # TODO: make sure ndata isn't compressed, or handle it
                    if len(dir_files) != file_count or file_count == 0:
                        return False
                    return True
            except Exception as e:
                logging.error("Exception parsing ndata file: %s", file_path)
                logging.error(str(e))
        return False
887590
public boolean hasData() {
        int apos = token.length - 1;
        int rpos = pos - 1;
        for (; rpos > -1 && apos > -1; rpos--, apos--) {
            if (buffer2[rpos] != -1) {
                return true;
            }
        }
        for (rpos = buffer2.length - 1; apos > -1; rpos--, apos--) {
            if (buffer2[rpos] != -1) {
                return true;
            }
        }
        return false;
    }
375841
def _filtering_step(self, basename):
        
        name = ''.join(basename.split('.')[:-1])
        # May cause problems if wav is not less than 9 channels.
        if basename.split('.')[-1] == "wav":
            if self.get_verbosity():
                print("Found wave! Copying to {}/filtered/{}".format(
                    self.src_dir, basename))
            subprocess.Popen(["cp", "{}/{}.wav".format(self.src_dir, name),
                              "{}/filtered/{}.wav".format(self.src_dir, name)],
                             universal_newlines=True).communicate()
431258
def _get_station_file(path_name, station, channel, debug=0):
    
    wavfiles = glob.glob(path_name + os.sep + '*')

    out_files = [_check_data(wavfile, station, channel, debug=debug)
                 for wavfile in wavfiles]
    out_files = list(set(out_files))
    return out_files