class AudioReader(object): ''' Class that reads Wav format files Input as a different scp file address Output a matrix of wav files in all scp files. ''' def __init__(self, scp_path, sample_rate=8000): super(AudioReader, self).__init__() self.sample_rate = sample_rate self.index_dict = handle_scp(scp_path) self.keys = list(self.index_dict.keys()) def _load(self, key): src, sr = read_wav(self.index_dict[key], return_rate=True) if self.sample_rate is not None and sr != self.sample_rate: raise RuntimeError('SampleRate mismatch: {:d} vs {:d}'.format( sr, self.sample_rate)) return src def __len__(self): return len(self.keys) def __iter__(self): for key in self.keys: yield key, self._load(key) def __getitem__(self, index): if type(index) not in [int, str]: raise IndexError('Unsupported index type: {}'.format(type(index))) if type(index) == int: num_uttrs = len(self.keys) if num_uttrs < index and index < 0: raise KeyError('Interger index out of range, {:d} vs {:d}'.format( index, num_uttrs)) index = self.keys[index] if index not in self.index_dict: raise KeyError("Missing utterance {}!".format(index)) return self._load(index)
时间: 2024-02-14 07:21:51 浏览: 83
一个读写WAV文件的例子
3星 · 编辑精心推荐
这段代码定义了一个 AudioReader 类,用于读取多个 wav 格式的音频文件。构造函数的参数为一个 scp 文件的路径和采样率,默认为 8000。类中定义了 `_load` 函数来读取每个 wav 文件,并进行采样率匹配。另外,类还实现了 `__len__`、`__iter__` 和 `__getitem__` 等函数,以支持对音频文件的遍历和索引访问。
阅读全文