Python wave.openfp() Examples

The following are 7 code examples of wave.openfp(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module wave , or try the search function .
Example #1
Source File: sndhdr.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_wav(h, f):
    import wave
    # 'RIFF' <len> 'WAVE' 'fmt ' <len>
    if not h.startswith(b'RIFF') or h[8:12] != b'WAVE' or h[12:16] != b'fmt ':
        return None
    f.seek(0)
    try:
        w = wave.openfp(f, 'r')
    except (EOFError, wave.Error):
        return None
    return ('wav', w.getframerate(), w.getnchannels(),
                   w.getnframes(), 8*w.getsampwidth()) 
Example #2
Source File: sndhdr.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_wav(h, f):
    import wave
    # 'RIFF' <len> 'WAVE' 'fmt ' <len>
    if not h.startswith(b'RIFF') or h[8:12] != b'WAVE' or h[12:16] != b'fmt ':
        return None
    f.seek(0)
    try:
        w = wave.openfp(f, 'r')
    except (EOFError, wave.Error):
        return None
    return ('wav', w.getframerate(), w.getnchannels(),
                   w.getnframes(), 8*w.getsampwidth()) 
Example #3
Source File: _common.py    From pytorch-asr with GNU General Public License v3.0 5 votes vote down vote up
def rebuild(self, mode):
        import wave
        logger.info(f"rebuilding \"{mode}\" ...")
        wav_manifest, txt_manifest = dict(), dict()
        for wav_file in self.target_path.joinpath(mode).rglob("*.wav"):
            uttid = wav_file.stem
            with wave.openfp(str(wav_file), "rb") as wav:
                samples = wav.getnframes()
            wav_manifest[uttid] = (str(wav_file), samples)
            txt_file = str(wav_file).replace('wav', 'txt')
            if Path(txt_file).exists():
                txt_manifest[uttid] = (str(txt_file), '-')
        self.make_manifest(mode, wav_manifest, txt_manifest) 
Example #4
Source File: _common.py    From pytorch-asr with GNU General Public License v3.0 5 votes vote down vote up
def process_text_only(self, mode):
        import wave
        logger.info(f"processing text only from \"{mode}\" ...")
        wav_manifest = dict()
        for wav_file in self.target_path.joinpath(mode).rglob("*.wav"):
            uttid = wav_file.stem
            with wave.openfp(str(wav_file), "rb") as wav:
                samples = wav.getnframes()
            wav_manifest[uttid] = (str(wav_file), samples)
        txt_manifest = self.get_transcripts(mode)
        self.make_manifest(mode, wav_manifest, txt_manifest) 
Example #5
Source File: sndhdr.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_wav(h, f):
    import wave
    # 'RIFF' <len> 'WAVE' 'fmt ' <len>
    if not h.startswith(b'RIFF') or h[8:12] != b'WAVE' or h[12:16] != b'fmt ':
        return None
    f.seek(0)
    try:
        w = wave.openfp(f, 'r')
    except (EOFError, wave.Error):
        return None
    return ('wav', w.getframerate(), w.getnchannels(),
                   w.getnframes(), 8*w.getsampwidth()) 
Example #6
Source File: audioread.py    From pb_chime5 with MIT License 5 votes vote down vote up
def read_from_byte_string(byte_string, dtype=np.dtype('<i2')):
    """ Parses a bytes string, i.e. a raw read of a wav file

    :param byte_string: input bytes string
    :param dtype: dtype used to decode the audio data
    :return: np.ndarray with audio data with channels x samples
    """
    wav_file = wave.openfp(BytesIO(byte_string))
    channels = wav_file.getnchannels()
    interleaved_audio_data = np.frombuffer(
        wav_file.readframes(wav_file.getnframes()), dtype=dtype)
    audio_data = np.array(
        [interleaved_audio_data[ch::channels] for ch in range(channels)])
    audio_data = audio_data.astype(np.float32) / np.max(audio_data)
    return audio_data 
Example #7
Source File: _common.py    From pytorch-asr with GNU General Public License v3.0 4 votes vote down vote up
def split_wav(self, mode):
        import io
        import wave
        segments_file = self.recipe_path.joinpath("data", mode, "segments")
        logger.info(f"processing {str(segments_file)} file ...")
        segments = dict()
        with smart_open(segments_file, "r") as f:
            for line in tqdm(f, total=get_num_lines(segments_file), ncols=params.NCOLS):
                split = line.strip().split()
                uttid, wavid, start, end = split[0], split[1], float(split[2]), float(split[3])
                if wavid in segments:
                    segments[wavid].append((uttid, start, end))
                else:
                    segments[wavid] = [(uttid, start, end)]

        wav_scp = self.recipe_path.joinpath("data", mode, "wav.scp")
        logger.info(f"processing {str(wav_scp)} file ...")
        manifest = dict()
        with smart_open(wav_scp, "r") as rf:
            for line in tqdm(rf, total=get_num_lines(wav_scp), ncols=params.NCOLS):
                wavid, cmd = line.strip().split(" ", 1)
                if not wavid in segments:
                    continue
                cmd = cmd.strip().rstrip(' |').split()
                if cmd[0] == 'sph2pipe':
                    cmd[0] = str(SPH2PIPE_PATH)
                p = sp.run(cmd, stdout=sp.PIPE, stderr=sp.PIPE)
                fp = io.BytesIO(p.stdout)
                with wave.openfp(fp, "rb") as wav:
                    fr = wav.getframerate()
                    nf = wav.getnframes()
                    for uttid, start, end in segments[wavid]:
                        fs, fe = int(fr * start - SAMPLE_MARGIN), int(fr * end + SAMPLE_MARGIN)
                        if fs < 0 or fe > nf:
                            continue
                        wav.rewind()
                        wav.setpos(fs)
                        signal = wav.readframes(fe - fs)
                        p = uttid.find('-')
                        if p != -1:
                            tar_path = self.target_path.joinpath(mode, uttid[:p])
                        else:
                            tar_path = self.target_path.joinpath(mode)
                        tar_path.mkdir(mode=0o755, parents=True, exist_ok=True)
                        wav_file = tar_path.joinpath(uttid + ".wav")
                        with wave.open(str(wav_file), "wb") as wf:
                            wf.setparams(wav.getparams())
                            wf.writeframes(signal)
                        manifest[uttid] = (str(wav_file), fe - fs)
        return manifest