本文整理汇总了Python中scipy.io.wavfile.write方法的典型用法代码示例。如果您正苦于以下问题:Python wavfile.write方法的具体用法?Python wavfile.write怎么用?Python wavfile.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.io.wavfile
的用法示例。
在下文中一共展示了wavfile.write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: write_file
# 需要导入模块: from scipy.io import wavfile [as 别名]
# 或者: from scipy.io.wavfile import write [as 别名]
def write_file(output_file_path, input_file_name, name_attribute, sig, fs):
"""
Read wave file as mono.
Args:
- output_file_path (str) : path to save resulting wave file to.
- input_file_name (str) : name of processed wave file,
- name_attribute (str) : attribute to add to output file name.
- sig (array) : signal/audio array.
- fs (int) : sampling rate.
Returns:
tuple of sampling rate and audio data.
"""
# set-up the output file name
fname = os.path.basename(input_file_name).split(".wav")[0] + name_attribute
fpath = os.path.join(output_file_path, fname)
write(filename=fpath, rate=fs, data=sig)
print("Writing data to " + fpath + ".")
示例2: synthesize
# 需要导入模块: from scipy.io import wavfile [as 别名]
# 或者: from scipy.io.wavfile import write [as 别名]
def synthesize(frames,filename,stride,sr=16000,deemph=0,ymax=0.98,normalize=False):
# Generate stream
y=torch.zeros((len(frames)-1)*stride+len(frames[0]))
for i,x in enumerate(frames):
y[i*stride:i*stride+len(x)]+=x
# To numpy & deemph
y=y.numpy().astype(np.float32)
if deemph>0:
y=deemphasis(y,alpha=deemph)
# Normalize
if normalize:
y-=np.mean(y)
mx=np.max(np.abs(y))
if mx>0:
y*=ymax/mx
else:
y=np.clip(y,-ymax,ymax)
# To 16 bit & save
wavfile.write(filename,sr,np.array(y*32767,dtype=np.int16))
return y
########################################################################################################################
示例3: split_to_mix
# 需要导入模块: from scipy.io import wavfile [as 别名]
# 或者: from scipy.io.wavfile import write [as 别名]
def split_to_mix(audio_path_list,database_repo=DATABASE_REPO_PATH,partition=2):
# return split_list : (part1,part2,...)
# each part : (idx,path)
length = len(audio_path_list)
part_len = length // partition
head = 0
part_idx = 0
split_list = []
while((head+part_len)<length):
part = audio_path_list[head:(head+part_len)]
split_list.append(part)
with open('%s/single_TF_part%d.txt'%(database_repo,part_idx),'a') as f:
for idx, _ in part:
name = 'single-%05d' % idx
f.write('%s.npy' % name)
f.write('\n')
head += part_len
part_idx += 1
return split_list
# mix single TF data
示例4: wavWrite
# 需要导入模块: from scipy.io import wavfile [as 别名]
# 或者: from scipy.io.wavfile import write [as 别名]
def wavWrite(y, fs, nbits, audioFile):
""" Write samples to WAV file
Args:
samples: (ndarray / 2D ndarray) (floating point) sample vector
mono: DIM: nSamples
stereo: DIM: nSamples x nChannels
fs: (int) Sample rate in Hz
nBits: (int) Number of bits
fnWAV: (string) WAV file name to write
"""
if nbits == 8:
intsamples = (y+1.0) * AudioIO.normFact['int' + str(nbits)]
fX = np.int8(intsamples)
elif nbits == 16:
intsamples = y * AudioIO.normFact['int' + str(nbits)]
fX = np.int16(intsamples)
elif nbits > 16:
fX = y
write(audioFile, fs, fX)
示例5: sound
# 需要导入模块: from scipy.io import wavfile [as 别名]
# 或者: from scipy.io.wavfile import write [as 别名]
def sound(x,fs):
""" Plays a wave file using the pyglet library. But first, it has to be written.
Termination of the playback is being performed by any keyboard input and Enter.
Args:
x: (array) Floating point samples
fs: (int) The sampling rate
"""
import pyglet as pg
global player
# Call the writing function
AudioIO.wavWrite(x, fs, 16, 'testPlayback.wav')
# Initialize playback engine
player = pg.media.Player()
# Initialize the object with the audio file
playback = pg.media.load('testPlayback.wav')
# Set it to player
player.queue(playback)
# Sound call
player.play()
# Killed by "keyboard"
kill = raw_input()
if kill or kill == '':
AudioIO.stop()
# Remove the dummy wave write
os.remove('testPlayback.wav')
示例6: _wavdata_rs
# 需要导入模块: from scipy.io import wavfile [as 别名]
# 或者: from scipy.io.wavfile import write [as 别名]
def _wavdata_rs(self):
if self.fs_rs is not None:
# Number of points in resample
ns_rs = np.int_(np.ceil(self.ns * self.fs_rs / self.fs))
# Do resample
# XXX: Tried using a Hamming window as a low pass filter, but it
# didn't seem to make a big difference, so it's not used
# here.
data_rs = resample(self.wavdata, ns_rs)
wavpath_rs = self.wavpath.split('.')[0] + '-resample-' + str(self.fs_rs) + 'Hz.wav'
# Write resampled data to wav file
# Convert data from 32-bit floating point to 16-bit PCM
data_rs_int = np.int16(data_rs * 32768)
wavfile.write(wavpath_rs, self.fs_rs, data_rs_int)
# XXX: Was worried that Python might continue executing code
# before the file write is finished, but it seems like it's
# not an issue.
return wavpath_rs, data_rs, data_rs_int, ns_rs
else:
return None, None, None, None
示例7: run_phase_reconstruction_example
# 需要导入模块: from scipy.io import wavfile [as 别名]
# 或者: from scipy.io.wavfile import write [as 别名]
def run_phase_reconstruction_example():
fs, d = fetch_sample_speech_tapestry()
# actually gives however many components you say! So double what .m file
# says
fftsize = 512
step = 64
X_s = np.abs(stft(d, fftsize=fftsize, step=step, real=False,
compute_onesided=False))
X_t = iterate_invert_spectrogram(X_s, fftsize, step, verbose=True)
"""
import matplotlib.pyplot as plt
plt.specgram(d, cmap="gray")
plt.savefig("1.png")
plt.close()
plt.imshow(X_s, cmap="gray")
plt.savefig("2.png")
plt.close()
"""
wavfile.write("phase_original.wav", fs, soundsc(d))
wavfile.write("phase_reconstruction.wav", fs, soundsc(X_t))
示例8: run_fft_dct_example
# 需要导入模块: from scipy.io import wavfile [as 别名]
# 或者: from scipy.io.wavfile import write [as 别名]
def run_fft_dct_example():
random_state = np.random.RandomState(1999)
fs, d = fetch_sample_speech_fruit()
n_fft = 64
X = d[0]
X_stft = stft(X, n_fft)
X_rr = complex_to_real_view(X_stft)
X_dct = fftpack.dct(X_rr, axis=-1, norm='ortho')
X_dct_sub = X_dct[1:] - X_dct[:-1]
std = X_dct_sub.std(axis=0, keepdims=True)
X_dct_sub += .01 * std * random_state.randn(
X_dct_sub.shape[0], X_dct_sub.shape[1])
X_dct_unsub = np.cumsum(X_dct_sub, axis=0)
X_idct = fftpack.idct(X_dct_unsub, axis=-1, norm='ortho')
X_irr = real_to_complex_view(X_idct)
X_r = istft(X_irr, n_fft)[:len(X)]
SNR = 20 * np.log10(np.linalg.norm(X - X_r) / np.linalg.norm(X))
print(SNR)
wavfile.write("fftdct_orig.wav", fs, soundsc(X))
wavfile.write("fftdct_rec.wav", fs, soundsc(X_r))
示例9: run_ltsd_example
# 需要导入模块: from scipy.io import wavfile [as 别名]
# 或者: from scipy.io.wavfile import write [as 别名]
def run_ltsd_example():
fs, d = fetch_sample_speech_tapestry()
winsize = 1024
d = d.astype("float32") / 2 ** 15
d -= d.mean()
pad = 3 * fs
noise_pwr = np.percentile(d, 1) ** 2
noise_pwr = max(1E-9, noise_pwr)
d = np.concatenate((np.zeros((pad,)) + noise_pwr * np.random.randn(pad), d))
_, vad_segments = ltsd_vad(d, fs, winsize=winsize)
v_up = np.where(vad_segments == True)[0]
s = v_up[0]
st = v_up[-1] + int(.5 * fs)
d = d[s:st]
bname = "tapestry.wav".split(".")[0]
wavfile.write("%s_out.wav" % bname, fs, soundsc(d))
示例10: to_wav
# 需要导入模块: from scipy.io import wavfile [as 别名]
# 或者: from scipy.io.wavfile import write [as 别名]
def to_wav(filename,rate,x):
"""
Write a wave file.
A wrapper function for scipy.io.wavfile.write
that also includes int16 scaling and conversion.
Assume input x is [-1,1] values.
Parameters
----------
filename : file name string
rate : sampling frequency in Hz
Returns
-------
Nothing : writes only the *.wav file
Examples
--------
>>> to_wav('test_file.wav', 8000, x)
"""
x16 = np.int16(x*32767)
wavfile.write(filename, rate, x16)
示例11: getMusicSegmentsFromFile
# 需要导入模块: from scipy.io import wavfile [as 别名]
# 或者: from scipy.io.wavfile import write [as 别名]
def getMusicSegmentsFromFile(inputFile):
modelType = "svm"
modelName = "data/svmMovies8classes"
dirOutput = inputFile[0:-4] + "_musicSegments"
if os.path.exists(dirOutput) and dirOutput!=".":
shutil.rmtree(dirOutput)
os.makedirs(dirOutput)
[Fs, x] = audioBasicIO.readAudioFile(inputFile)
if modelType=='svm':
[Classifier, MEAN, STD, classNames, mtWin, mtStep, stWin, stStep, compute_beat] = aT.load_model(modelName)
elif modelType=='knn':
[Classifier, MEAN, STD, classNames, mtWin, mtStep, stWin, stStep, compute_beat] = aT.load_model_knn(modelName)
flagsInd, classNames, acc, CM = aS.mtFileClassification(inputFile, modelName, modelType, plotResults = False, gtFile = "")
segs, classes = aS.flags2segs(flagsInd, mtStep)
for i, s in enumerate(segs):
if (classNames[int(classes[i])] == "Music") and (s[1] - s[0] >= minDuration):
strOut = "{0:s}{1:.3f}-{2:.3f}.wav".format(dirOutput+os.sep, s[0], s[1])
wavfile.write( strOut, Fs, x[int(Fs*s[0]):int(Fs*s[1])])
示例12: annotation2files
# 需要导入模块: from scipy.io import wavfile [as 别名]
# 或者: from scipy.io.wavfile import write [as 别名]
def annotation2files(wavFile, csvFile):
'''
Break an audio stream to segments of interest,
defined by a csv file
- wavFile: path to input wavfile
- csvFile: path to csvFile of segment limits
Input CSV file must be of the format <T1>\t<T2>\t<Label>
'''
[Fs, x] = audioBasicIO.read_audio_file(wavFile)
with open(csvFile, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter='\t', quotechar='|')
for j, row in enumerate(reader):
T1 = float(row[0].replace(",","."))
T2 = float(row[1].replace(",","."))
label = "%s_%s_%.2f_%.2f.wav" % (wavFile, row[2], T1, T2)
label = label.replace(" ", "_")
xtemp = x[int(round(T1*Fs)):int(round(T2*Fs))]
print(T1, T2, label, xtemp.shape)
wavfile.write(label, Fs, xtemp)
示例13: BeamformIt
# 需要导入模块: from scipy.io import wavfile [as 别名]
# 或者: from scipy.io.wavfile import write [as 别名]
def BeamformIt(mixture, fs=8000, basedir='/Data/software/BeamformIt/', verbose=False):
mixture /= np.max(np.abs(mixture))
if not os.path.exists('/tmp/audios/'):
os.mkdir('/tmp/audios/')
wavfile.write('/tmp/audios/rec.wav', fs, mixture.T)
p = subprocess.Popen("cd {}; bash do_beamforming.sh /tmp/audios/ temps".format(basedir),
stdout=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
p_status = p.wait()
ref_ch = int(str(output).split("Selected channel ")[1].split(' as the reference channel')[0])
if verbose:
print("Output: {}".format(output))
print("Error: {}".format(err))
print("Status: {}".format(p_status))
s, _ = sf.read('{}/output/temps/temps.wav'.format(basedir))
return s, ref_ch
示例14: generate_and_save_samples
# 需要导入模块: from scipy.io import wavfile [as 别名]
# 或者: from scipy.io.wavfile import write [as 别名]
def generate_and_save_samples(sample_fn, length, count, dir, rate, levels):
def save_samples(data):
data = (data * np.reshape(np.arange(levels) / (levels-1), [levels, 1, 1])).sum(
axis=1, keepdims=True)
value = np.iinfo(np.int16).max
audio = (utils.inverse_mulaw(data * 2 - 1) * value).astype(np.int16)
for idx, sample in enumerate(audio):
filename = os.path.join(dir, 'sample_{}.wav'.format(idx))
wavfile.write(filename, rate, np.squeeze(sample))
samples = chainer.Variable(
chainer.cuda.cupy.zeros([count, levels, 1, length], dtype='float32'))
one_hot_ref = chainer.cuda.cupy.eye(levels).astype('float32')
with tqdm.tqdm(total=length) as bar:
for i in range(length):
probs = F.softmax(sample_fn(samples))[:, :, 0, 0, i]
samples.data[:, :, 0, i] = one_hot_ref[utils.sample_from(probs.data.get())]
bar.update()
samples.to_cpu()
save_samples(samples.data)
示例15: save_wav
# 需要导入模块: from scipy.io import wavfile [as 别名]
# 或者: from scipy.io.wavfile import write [as 别名]
def save_wav(audio, output_wav_file):
wav.write(output_wav_file, 16000, np.array(np.clip(np.round(audio), -2**15, 2**15-1), dtype=np.int16))
print('output dB', db(audio))