本文整理匯總了Python中soundfile.read方法的典型用法代碼示例。如果您正苦於以下問題:Python soundfile.read方法的具體用法?Python soundfile.read怎麽用?Python soundfile.read使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類soundfile
的用法示例。
在下文中一共展示了soundfile.read方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: load_wav
# 需要導入模塊: import soundfile [as 別名]
# 或者: from soundfile import read [as 別名]
def load_wav(wav_rxfilename, start=0, end=None):
""" This function reads audio file and return data in numpy.float32 array.
"lru_cache" holds recently loaded audio so that can be called
many times on the same audio file.
OPTIMIZE: controls lru_cache size for random access,
considering memory size
"""
if wav_rxfilename.endswith('|'):
# input piped command
p = subprocess.Popen(wav_rxfilename[:-1], shell=True,
stdout=subprocess.PIPE)
data, samplerate = sf.read(io.BytesIO(p.stdout.read()),
dtype='float32')
# cannot seek
data = data[start:end]
elif wav_rxfilename == '-':
# stdin
data, samplerate = sf.read(sys.stdin, dtype='float32')
# cannot seek
data = data[start:end]
else:
# normal wav file
data, samplerate = sf.read(wav_rxfilename, start=start, stop=end)
return data, samplerate
示例2: wavefile_to_waveform
# 需要導入模塊: import soundfile [as 別名]
# 或者: from soundfile import read [as 別名]
def wavefile_to_waveform(wav_file, features_type):
data, sr = sf.read(wav_file)
if features_type == 'vggish':
tmp_name = str(int(np.random.rand(1)*1000000)) + '.wav'
sf.write(tmp_name, data, sr, subtype='PCM_16')
sr, wav_data = wavfile.read(tmp_name)
os.remove(tmp_name)
# sr, wav_data = wavfile.read(wav_file) # as done in VGGish Audioset
assert wav_data.dtype == np.int16, 'Bad sample type: %r' % wav_data.dtype
data = wav_data / 32768.0 # Convert to [-1.0, +1.0]
# at least one second of samples, if not repead-pad
src_repeat = data
while (src_repeat.shape[0] < sr):
src_repeat = np.concatenate((src_repeat, data), axis=0)
data = src_repeat[:sr]
return data, sr
示例3: test_process
# 需要導入模塊: import soundfile [as 別名]
# 或者: from soundfile import read [as 別名]
def test_process(self):
porcupine = Porcupine(
library_path=LIBRARY_PATH,
model_file_path=MODEL_FILE_PATH,
keyword_file_path=KEYWORD_FILE_PATHS['porcupine'],
sensitivity=0.5)
audio, sample_rate = soundfile.read(
os.path.join(os.path.dirname(__file__), '../../resources/audio_samples/porcupine.wav'),
dtype='int16')
assert sample_rate == porcupine.sample_rate
num_frames = len(audio) // porcupine.frame_length
results = []
for i in range(num_frames):
frame = audio[i * porcupine.frame_length:(i + 1) * porcupine.frame_length]
results.append(porcupine.process(frame))
porcupine.delete()
self.assertEqual(sum(results), 1)
示例4: load_IR
# 需要導入模塊: import soundfile [as 別名]
# 或者: from soundfile import read [as 別名]
def load_IR(self, ir_file, ir_fmt):
ir_file = os.path.join(self.data_root, ir_file)
# print('loading ir_file: ', ir_file)
if hasattr(self, 'cache') and ir_file in self.cache:
return self.cache[ir_file]
else:
if ir_fmt == 'mat':
IR = loadmat(ir_file, squeeze_me=True, struct_as_record=False)
IR = IR['risp_imp']
elif ir_fmt == 'imp' or ir_fmt == 'txt':
IR = np.loadtxt(ir_file)
elif ir_fmt == 'npy':
IR = np.load(ir_file)
elif ir_fmt == 'wav':
IR, _ = sf.read(ir_file)
else:
raise TypeError('Unrecognized IR format: ', ir_fmt)
IR = IR[:self.max_reverb_len]
if np.max(IR)>0:
IR = IR / np.abs(np.max(IR))
p_max = np.argmax(np.abs(IR))
if hasattr(self, 'cache'):
self.cache[ir_file] = (IR, p_max)
return IR, p_max
示例5: __init__
# 需要導入模塊: import soundfile [as 別名]
# 或者: from soundfile import read [as 別名]
def __init__(self, noises_dir, snr_levels=[0, 5, 10],
cache=False,
report=False):
self.noises_dir = noises_dir
self.snr_levels = snr_levels
self.report = report
# read noises in dir
if isinstance(noises_dir, list):
self.noises = []
for ndir in noises_dir:
self.noises += glob.glob(os.path.join(ndir, '*.wav'))
else:
self.noises = glob.glob(os.path.join(noises_dir, '*.wav'))
self.nidxs = list(range(len(self.noises)))
if len(self.noises) == 0:
raise ValueError('[!] No noises found in {}'.format(noises_dir))
else:
print('[*] Found {} noise files'.format(len(self.noises)))
self.eps = 1e-22
if cache:
self.cache = {}
for noise in self.noises:
self.load_noise(noise)
示例6: __getitem__
# 需要導入模塊: import soundfile [as 別名]
# 或者: from soundfile import read [as 別名]
def __getitem__(self, index):
fname = self.files[index]
wav, sr = sf.read(fname)
assert sr == 16000
wav = torch.from_numpy(wav).float()
lbls = None
if self.labels:
if isinstance(self.labels, str):
lbl_file = osp.splitext(fname)[0] + "." + self.labels
with open(lbl_file, 'r') as lblf:
lbls = lblf.readline()
assert lbls is not None
else:
lbls = self.labels[index]
return wav, lbls
示例7: test_default
# 需要導入模塊: import soundfile [as 別名]
# 或者: from soundfile import read [as 別名]
def test_default(self):
tfm = new_transformer()
actual = tfm.stat(INPUT_FILE)
expected = {
'Length (seconds)': '10.000000',
'Minimum amplitude': '-0.264252',
'RMS amplitude': '0.053924',
'Volume adjustment': '3.521',
'Mean norm': '0.042598',
'Minimum delta': '0.000000',
'Samples read': '441000',
'Maximum amplitude': '0.284027',
'Mean amplitude': '0.000014',
'RMS delta': '0.006387',
'Midline amplitude': '0.009888',
'Maximum delta': '0.112427',
'Mean delta': '0.004495',
'Scaled by': '2147483647.0',
'Rough frequency': '831'
}
self.assertEqual(expected, actual)
示例8: test_scale
# 需要導入模塊: import soundfile [as 別名]
# 或者: from soundfile import read [as 別名]
def test_scale(self):
tfm = new_transformer()
actual = tfm.stat(INPUT_FILE, scale=2147483647.0 / 2.0)
expected = {
'Length (seconds)': '10.000000',
'Minimum amplitude': '-0.528503',
'RMS amplitude': '0.107848',
'Volume adjustment': '3.521',
'Mean norm': '0.085196',
'Minimum delta': '0.000000',
'Samples read': '441000',
'Maximum amplitude': '0.568054',
'Mean amplitude': '0.000028',
'RMS delta': '0.012773',
'Midline amplitude': '0.019775',
'Maximum delta': '0.224854',
'Mean delta': '0.008991',
'Scaled by': '1073741823.5',
'Rough frequency': '831'
}
self.assertEqual(expected, actual)
示例9: test_rms
# 需要導入模塊: import soundfile [as 別名]
# 或者: from soundfile import read [as 別名]
def test_rms(self):
tfm = new_transformer()
actual = tfm.stat(INPUT_FILE, rms=True)
expected = {
'Length (seconds)': '10.000000',
'Minimum amplitude': '-4.900466',
'RMS amplitude': '1.000000',
'Volume adjustment': '3.521',
'Mean norm': '0.789962',
'Minimum delta': '0.000000',
'Samples read': '441000',
'Maximum amplitude': '5.267194',
'Mean amplitude': '0.000256',
'RMS delta': '0.118437',
'Midline amplitude': '0.183364',
'Maximum delta': '2.084919',
'Mean delta': '0.083366',
'Rough frequency': '831',
'Scaled by rms': '0.053924'
}
self.assertEqual(expected, actual)
示例10: test_multichannel
# 需要導入模塊: import soundfile [as 別名]
# 或者: from soundfile import read [as 別名]
def test_multichannel(self):
tfm = new_transformer()
actual = tfm.stat(INPUT_FILE4)
expected = {
'Length (seconds)': '10.000000',
'Minimum amplitude': '-0.264252',
'RMS amplitude': '0.053924',
'Volume adjustment': '3.521',
'Mean norm': '0.042598',
'Minimum delta': '0.000000',
'Samples read': '441000',
'Maximum amplitude': '0.284027',
'Mean amplitude': '0.000014',
'RMS delta': '0.006387',
'Midline amplitude': '0.009888',
'Maximum delta': '0.112427',
'Mean delta': '0.004495',
'Scaled by': '2147483647.0',
'Rough frequency': '831'
}
self.assertEqual(expected, actual)
示例11: read_audio
# 需要導入模塊: import soundfile [as 別名]
# 或者: from soundfile import read [as 別名]
def read_audio(path, target_fs=None):
"""Read 1 dimension audio sequence from given path.
Args:
path: string, path of audio.
target_fs: int, resampling rate.
Returns:
audio: 1 dimension audio sequence.
fs: sampling rate of audio.
"""
(audio, fs) = soundfile.read(path)
if audio.ndim > 1:
audio = np.mean(audio, axis=1)
if target_fs is not None and fs != target_fs:
audio = librosa.resample(audio, orig_sr=fs, target_sr=target_fs)
fs = target_fs
return audio, fs
示例12: process
# 需要導入模塊: import soundfile [as 別名]
# 或者: from soundfile import read [as 別名]
def process(wavefile, outdir, pattern=''):
_, base = os.path.split(wavefile)
if pattern:
if pattern not in base:
return
# print base
raw_in = os.path.join(outdir, base.replace('.wav','.raw'))
raw_out = os.path.join(outdir, base.replace('.wav','_norm.raw'))
logfile = os.path.join(outdir, base.replace('.wav','.log'))
wav_out = os.path.join(outdir, base)
data, samplerate = sf.read(wavefile, dtype='int16')
sf.write(raw_in, data, samplerate, subtype='PCM_16')
os.system('%s -log %s -q -lev -26.0 -sf %s %s %s'%(sv56, logfile, samplerate, raw_in, raw_out))
norm_data, samplerate = sf.read(raw_out, dtype='int16', samplerate=samplerate, channels=1, subtype='PCM_16')
sf.write(wav_out, norm_data, samplerate)
os.system('rm %s %s'%(raw_in, raw_out))
示例13: read_est_file
# 需要導入模塊: import soundfile [as 別名]
# 或者: from soundfile import read [as 別名]
def read_est_file(est_file):
'''
Generic function to read est files. So far, it reads the first two columns of est files. (TODO: expand)
'''
# Get EST_Header_End line number: (TODO: more efficient)
with open(est_file) as fid:
header_size = 1 # init
for line in fid:
if line == 'EST_Header_End\n':
break
header_size += 1
m_data = np.loadtxt(est_file, skiprows=header_size, usecols=[0,1])
return m_data
#------------------------------------------------------------------------------
# check_len_smpls= signal length. If provided, it checks and fixes for some pm out of bounds (REAPER bug)
# fs: Must be provided if check_len_smpls is given
示例14: __init__
# 需要導入模塊: import soundfile [as 別名]
# 或者: from soundfile import read [as 別名]
def __init__(self, utt2rir, filetype="list"):
self.utt2rir_file = utt2rir
self.filetype = filetype
self.utt2rir = {}
if filetype == "list":
with open(utt2rir, "r") as f:
for line in f:
utt, filename = line.rstrip().split(None, 1)
signal, rate = soundfile.read(filename, dtype="int16")
self.utt2rir[utt] = (signal, rate)
elif filetype == "sound.hdf5":
self.utt2rir = SoundHDF5File(utt2rir, "r")
else:
raise NotImplementedError(filetype)
示例15: read_wav
# 需要導入模塊: import soundfile [as 別名]
# 或者: from soundfile import read [as 別名]
def read_wav(filename):
# Reads in a wav audio file, averages both if stereo, converts the signal to float64 representation
audio_signal, sample_rate = sf.read(filename)
if audio_signal.ndim > 1:
audio_signal = (audio_signal[:, 0] + audio_signal[:, 1])/2.0
if audio_signal.dtype != 'float64':
audio_signal = wav_to_float(audio_signal)
return audio_signal, sample_rate