本文整理汇总了Python中scipy.io.wavfile.write函数的典型用法代码示例。如果您正苦于以下问题:Python write函数的具体用法?Python write怎么用?Python write使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了write函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: problem4
def problem4():
# read in tada.wav
rate, tada = wavfile.read('tada.wav')
# upon inspection, we find that tada.wav is a stereo audio file.
# we create stereo white noise that lasts 10 seconds
L_white = sp.int16(sp.random.randint(-32767,32767,rate*10))
R_white = sp.int16(sp.random.randint(-32767,32767,rate*10))
white = sp.zeros((len(L_white),2))
white[:,0] = L_white
white[:,1] = R_white
# pad tada signal with zeros
padded_tada = sp.zeros_like(white)
padded_tada[:len(tada)] = tada
ptada = padded_tada
# fourier transforms
ftada = sp.fft(ptada,axis=0)
fwhite = sp.fft(white,axis=0)
# inverse transform of convolution
out = sp.ifft((ftada*fwhite),axis=0)
# prepping output and writing file
out = sp.real(out)
scaled = sp.int16(out / sp.absolute(out).max() * 32767)
wavfile.write('my_tada_conv.wav',rate,scaled)
示例2: save_wavfile
def save_wavfile(signal, file_prefix, rate=16000):
num_samples = signal.shape[0]
time_length = signal.shape[1]
for s in xrange(num_samples):
file_path = file_prefix+'_{}.wav'.format(s)
wav.write(file_path, rate, signal[s][:])
示例3: convert_gen_to_out
def convert_gen_to_out(data_dir):
gen_dir = os.path.join(data_dir, 'gen')
out_dir = os.path.join(data_dir, 'out')
datatools.ensure_dir_exists(gen_dir)
datatools.ensure_dir_exists(out_dir)
gen_glob_file_path = os.path.join(gen_dir, '*.npy')
write_flush('-- Converting gen to out...')
for npy_data_file in glob.glob(gen_glob_file_path):
blocks = []
filename = npy_data_file.split('/')[-1]
wav_filename = os.path.join(out_dir, filename.replace('.npy','.wav'))
data_as_fft = np.load(npy_data_file)
for fft_block in data_as_fft:
real_imag_split = fft_block.shape[0] // 2
real = fft_block[0:real_imag_split]
imag = fft_block[real_imag_split:]
time_domain = np.fft.ifft(real + 1.0j * imag)
blocks.append(time_domain)
song_blocks = np.concatenate(blocks)
song_blocks = song_blocks * 32767.0
song_blocks = song_blocks.astype('int16')
wavfile.write(wav_filename, 44100, song_blocks)
write_flush('finished. \n')
示例4: _check_roundtrip
def _check_roundtrip(realfile, rate, dtype, channels):
if realfile:
fd, tmpfile = tempfile.mkstemp(suffix='.wav')
os.close(fd)
else:
tmpfile = BytesIO()
try:
data = np.random.rand(100, channels)
if channels == 1:
data = data[:,0]
if dtype.kind == 'f':
# The range of the float type should be in [-1, 1]
data = data.astype(dtype)
else:
data = (data*128).astype(dtype)
wavfile.write(tmpfile, rate, data)
for mmap in [False, True]:
rate2, data2 = wavfile.read(tmpfile, mmap=mmap)
assert_equal(rate, rate2)
assert_(data2.dtype.byteorder in ('<', '=', '|'), msg=data2.dtype)
assert_array_equal(data, data2)
del data2
finally:
if realfile:
os.unlink(tmpfile)
示例5: datawrite
def datawrite(filename,rate,data):
try:
write(filename, rate, data)
except IOError:
print("IOError:Wrong file or file path")
#TODO we will trace back and add codes for the exit code
sys.exit()
示例6: main
def main():
fs, data = wavfile.read('Music.wav') # load the data
audio = data.T[0] # un flux de la stereo
Xf = zTransform(audio, 44100)
b, a = peaking(100,10,44100,15)
b1, a1 = peaking(1000,15,44100,15)
## w,h = freqz(b, a, worN = 44100)
## plt.figure()
## plt.plot(w, 20 * np.log10(np.abs(h)))
## plt.show()
## Y1 = lfilter(b,a,Xf)
## Y = lfilter(b1,a1,Y1)
Y = lfilter(b,a, Xf)
finalAudio = zTransformInverse(Y, 44100).real.astype(np.int16)
wavfile.write("Test.wav",fs,finalAudio)
示例7: main
def main():
parser = argparse.ArgumentParser()
parser.add_argument('output')
args = parser.parse_args()
data = []
data.extend(gen_single(0, 2))
scale = np.array([-9, -7, -5, -4, -2, 0, 2, 3])
freq = 880 * np.power(2, scale / 12.0)
print map(int, freq)
def gen_song():
song = [1, 5, 6, 5, 4, 3, 2, 1]
song = [freq[i - 1] for i in song]
print map(int, song)
for f in song:
data.extend(gen_single(f, 0.5) * np.log(f / 440))
def gen_chord():
chord = [1, 3, 5]
chord = [freq[i - 1] for i in chord]
print map(int, chord)
val = gen_single(chord[0], 4)
for i in chord[1:]:
val += gen_single(i, 4)
data.extend(val)
gen_song()
#gen_chord()
data /= np.max(np.abs(data))
data = np.array(data) * 32767
data = data.astype('int16')
wavfile.write(args.output, SAMPLE_RATE, data)
示例8: energyDenoise
def energyDenoise(self, audio_file, scale, denoised_audio_file, energy_denoising_debug):
if not os.path.isfile(audio_file):
return False
samp_freq, signal = wavfile.read(audio_file)
samples = signal.shape[0]
sq_signal = signal * 1.0
if energy_denoising_debug:
timearray = arange(0, samples*1.0, 1)
timearray /= samp_freq
timearray *= 1000.0
subplot(3,1,1)
plot(timearray, signal, color = 'k')
for i in range(0, len(sq_signal)):
sq_signal[i] *= sq_signal[i]
mean_sq = mean(sq_signal)
for i in range(0, len(sq_signal)):
if sq_signal[i] < scale * mean_sq:
signal[i] = 0
if energy_denoising_debug:
timearray = arange(0, samples*1.0, 1)
timearray /= samp_freq
timearray *= 1000.0
subplot(3,1,2)
plot(timearray, signal, color = 'k')
if energy_denoising_debug:
show()
wavfile.write(denoised_audio_file, samp_freq, signal)
return True
示例9: generate_from_image
def generate_from_image(filename, random_phases=False):
SAMPLES_PER_WINDOW = 326
SAMPLING_RATE = 44100
spectrogram = mpimg.imread(filename)
lum_spectrogram = luminosity(spectrogram)
# mpimg reads in an image with an upside-down y-axis (i.e. 0 at the top and
# max(y) at the bottom), so we need to flip it
lum_spectrogram = np.flipud(lum_spectrogram)
num_rows, num_cols = lum_spectrogram.shape
num_samples = num_cols * SAMPLES_PER_WINDOW
t = np.matrix(time(num_samples))
f = np.matrix(np.apply_along_axis(frequency, 0, np.arange(num_rows)/float(num_rows)))
f = f.transpose()
if random_phases:
phi = np.matrix(np.random.rand(num_rows)*2*np.pi)
phi = phi.transpose()
else:
phi = np.random.random()*2*np.pi
a = amplitude(lum_spectrogram)
oscillators = np.multiply(a, np.sin(2*np.pi*f*t+phi))
signal = oscillators.sum(axis=0)
signal = signal / np.amax(np.absolute(signal))
signal = np.squeeze(np.asarray(signal))
wavfile.write("output_signal.wav", SAMPLING_RATE, signal)
示例10: array2audio
def array2audio(sDir, iRate, aData):
"""
writes an .wav audio file to disk from an array
"""
from scipy.io.wavfile import write
write(sDir, iRate, aData)
示例11: test_noise
def test_noise(noise_coeff=0.00):
file = 'test16k.wav'
fs, x = wavfile.read(file)
fs, nbit, x_length, x = readwav(file)
period = 5.0
opt = pyDioOption(40.0, 700, 2.0, period, 4)
if noise_coeff < 1:
noise_str = str(noise_coeff).split('.')[-1]
else:
noise_str = str(noise_coeff).split('.')[0]
f0, time_axis = dio(x, fs, period, opt)
f0_by_dio = copy.deepcopy(f0)
f0 = stonemask(x, fs, period, time_axis, f0)
spectrogram = star(x, fs, period, time_axis, f0)
spectrogram = cheaptrick(x, fs, period, time_axis, f0)
residual = platinum(x, fs, period, time_axis, f0, spectrogram)
old_spectrogram = np.copy(spectrogram)
plt.matshow(old_spectrogram, cmap="gray")
plt.title("Before %s noise" % noise_str)
plt.savefig("before_%s.png" % noise_str)
random_state = np.random.RandomState(1999)
spectrogram += noise_coeff * np.abs(random_state.randn(*spectrogram.shape))
residual += noise_coeff * np.abs(random_state.randn(*residual.shape))
y = synthesis(fs, period, f0, spectrogram, residual, len(x))
ys = synthesis(fs, period, f0, old_spectrogram, residual, len(x))
wavfile.write("y_%s.wav" % noise_str, fs, soundsc(y))
wavfile.write("y_no_noise.wav", fs, soundsc(ys))
plt.clf()
plt.plot(soundsc(ys), label='orig')
plt.plot(soundsc(y), label='noisy', color='red')
plt.title("Comparison of time series with %s noise" % noise_str)
plt.legend()
plt.savefig("comparison_%s.png" % noise_str)
示例12: _process_loop
def _process_loop(self):
with WavProcessor() as proc:
self._ask_data.set()
while True:
if self._process_buf is None:
# Waiting for data to process
time.sleep(self._processor_sleep_time)
continue
self._ask_data.clear()
if self._save_path:
f_path = os.path.join(
self._save_path, 'record_{:.0f}.wav'.format(time.time())
)
wavfile.write(f_path, self._sample_rate, self._process_buf)
logger.info('"{}" saved.'.format(f_path))
logger.info('Start processing.')
predictions = proc.get_predictions(
self._sample_rate, self._process_buf)
logger.info(
'Predictions: {}'.format(format_predictions(predictions))
)
logger.info('Stop processing.')
self._process_buf = None
self._ask_data.set()
示例13: test_filter
def test_filter(n):
audio = wave.read("signal-echo.wav")
audio[1][:,0] = convolve(audio[1][:,0], filters[n], 'same')
audio[1][:,1] = audio[1][:,0]
wave.write("signal-echo-out.wav", audio[0], audio[1])
示例14: writewav
def writewav(audiopath="wave.npz", outpath="out.wav"):
""" Write a wav file given an input sample array file that can be read with readfile. """
import scipy.io.wavfile as wav
samplerate, samples = readfile(audiopath)
wav.write(outpath, samplerate, samples)
return
示例15: write_wave_file
def write_wave_file(signal, filename, sample_rate=None):
"""
Write the signal to disk as a .wav file.
Parameters
----------
signal : numpy array or Signal
The signal to be written to file.
filename : str
Name of the file.
sample_rate : int, optional
Sample rate of the signal [Hz].
Returns
-------
filename : str
Name of the file.
Notes
-----
`sample_rate` can be 'None' if `signal` is a :class:`Signal` instance. If
set, the given `sample_rate` is used instead of the signal's sample rate.
Must be given if `signal` is a ndarray.
"""
from scipy.io import wavfile
if isinstance(signal, Signal) and sample_rate is None:
sample_rate = int(signal.sample_rate)
wavfile.write(filename, rate=sample_rate, data=signal)
return filename