• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python wavfile.write函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中scipy.io.wavfile.write函数的典型用法代码示例。如果您正苦于以下问题:Python write函数的具体用法?Python write怎么用?Python write使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了write函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:tkchris93,项目名称:ACME,代码行数:28,代码来源:solutions.py


示例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][:])
开发者ID:taesupkim,项目名称:ift6266h16,代码行数:7,代码来源:utils.py


示例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')
开发者ID:claymcleod,项目名称:dnn-music-generation,代码行数:30,代码来源:datatools.py


示例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)
开发者ID:jakevdp,项目名称:scipy,代码行数:29,代码来源:test_wavfile.py


示例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()
开发者ID:MerinS,项目名称:SigPro,代码行数:7,代码来源:encodewatermark.py


示例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)
开发者ID:Gorgorot38,项目名称:Sonotone-RICM4,代码行数:25,代码来源:Peak.py


示例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)
开发者ID:Mogito89,项目名称:hearv,代码行数:30,代码来源:gen_freq.py


示例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
开发者ID:gitter-badger,项目名称:rapp-platform,代码行数:35,代码来源:rapp_energy_denoise.py


示例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)
开发者ID:amygdalama,项目名称:furrier-transform,代码行数:25,代码来源:furrier-transform.py


示例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)
开发者ID:RomHartmann,项目名称:useful_scripts,代码行数:7,代码来源:audio_tools.py


示例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)
开发者ID:EQ4,项目名称:world.py,代码行数:35,代码来源:test_noise.py


示例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()
开发者ID:SS-HU,项目名称:devicehive-audio-analysis,代码行数:27,代码来源:capture.py


示例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])
开发者ID:mewashin,项目名称:SPH,代码行数:7,代码来源:task1.py


示例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
开发者ID:roim,项目名称:PyTranscribe,代码行数:7,代码来源:__init__.py


示例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
开发者ID:CPJKU,项目名称:madmom,代码行数:30,代码来源:signal.py


示例16: synt_all_method3

def synt_all_method3(folder_in):
    folder_out = folder_in[:-15] + "_synt_mcep_mat"
    if not os.path.exists(folder_out):
        os.mkdir(folder_out)

    mcep_mats = sorted([item for item in os.listdir(folder_in) if "_mc_mat" in item])
    f0s = sorted([item for item in os.listdir(folder_in) if "_f0" in item])
    aper_mats = sorted([item for item in os.listdir(folder_in) if "_aper_mat" in item])
    world = World(samplingrate, float(hop_length) / samplingrate * 1000)

    for mcep_mat_file, f0_file, aper_mat_file in zip(mcep_mats, f0s, aper_mats):
        print(mcep_mat_file)
        res = synt_from_mcep_matrix_to_spec(
            world,
            np.load(os.path.join(folder_in, f0_file)),
            np.load(os.path.join(folder_in, mcep_mat_file)),
            np.load(os.path.join(folder_in, aper_mat_file)))
        print("writing synth for {0}".format(mcep_mat_file))
        # wavfile.write("norm.wav", 16000, normalize_int16(s))
        wavfile.write(
            os.path.join(
                folder_out,
                mcep_mat_file.replace("mc_mat.npy", "") + "synth.wav"),
            sample_rate,
            normalize_int16(res))
开发者ID:ctrldash,项目名称:nefarious-kidney,代码行数:25,代码来源:synth.py


示例17: main

def main(argv):
    if len(argv) == 6:
        window_size = int(argv[1])
        a_fname = argv[2]
        b_fname = argv[3]
        a_phase_b_mag_fname = argv[4]
        b_phase_a_mag_fname = argv[5]
    else:
        print(
            'Usage: %s ' % argv[0] +
            '<WINDOW_WIDTH> <FILE_1> <FILE_2> <OUTFILE_1> <OUTFILE_2>' + (
                '\n\nSwap magnitude and phase of WAV files FILE_1 and FILE_2.'
                '\n\nWINDOW_WIDTH: STFT frame length (integer # of samples)'
                '\nOUTFILE_1: phase of FILE_1, magnitude of FILE_2'
                '\nOUTFILE_2: phase of FILE_2, magnitude of FILE_1'))
        return 1

    a_rate, a = wavfile.read(a_fname)
    b_rate, b = wavfile.read(b_fname)
    assert a_rate == b_rate
    assert a.dtype == b.dtype

    print('Window width: %d samples = %.3f ms' %
          (window_size, 1e3 * window_size / a_rate))

    a_phase_b_mag, b_phase_a_mag = swap_wav_magnitude(a, b, window_size)

    wavfile.write(a_phase_b_mag_fname, a_rate, a_phase_b_mag)
    wavfile.write(b_phase_a_mag_fname, a_rate, b_phase_a_mag)

    return 0
开发者ID:alexeyantonov,项目名称:Fourier_fun,代码行数:31,代码来源:swap_wav_mag_phase_stft.py


示例18: thumbnailWrapper

def thumbnailWrapper(inputFile, thumbnailWrapperSize):
    st_window = 0.5
    st_step = 0.5
    if not os.path.isfile(inputFile):
        raise Exception("Input audio file not found!")

    [fs, x] = audioBasicIO.readAudioFile(inputFile)
    if fs == -1:    # could not read file
        return

    [A1, A2, B1, B2, Smatrix] = aS.musicThumbnailing(x, fs, st_window, st_step,
                                                     thumbnailWrapperSize)

    # write thumbnailWrappers to WAV files:
    if inputFile.endswith(".wav"):
        thumbnailWrapperFileName1 = inputFile.replace(".wav", "_thumb1.wav")
        thumbnailWrapperFileName2 = inputFile.replace(".wav", "_thumb2.wav")
    if inputFile.endswith(".mp3"):
        thumbnailWrapperFileName1 = inputFile.replace(".mp3", "_thumb1.mp3")
        thumbnailWrapperFileName2 = inputFile.replace(".mp3", "_thumb2.mp3")
    wavfile.write(thumbnailWrapperFileName1, fs, x[int(fs * A1):int(fs * A2)])
    wavfile.write(thumbnailWrapperFileName2, fs, x[int(fs * B1):int(fs * B2)])
    print("1st thumbnailWrapper (stored in file {0:s}): {1:4.1f}sec" \
          " -- {2:4.1f}sec".format(thumbnailWrapperFileName1, A1, A2))
    print("2nd thumbnailWrapper (stored in file {0:s}): {1:4.1f}sec" \
          " -- {2:4.1f}sec".format(thumbnailWrapperFileName2, B1, B2))

    # Plot self-similarity matrix:
    fig = plt.figure()
    ax = fig.add_subplot(111, aspect="auto")
    plt.imshow(Smatrix)
    # Plot best-similarity diagonal:
    Xcenter = (A1 / st_step + A2 / st_step) / 2.0
    Ycenter = (B1 / st_step + B2 / st_step) / 2.0

    e1 = matplotlib.patches.Ellipse((Ycenter, Xcenter),
                                    thumbnailWrapperSize * 1.4, 3, angle=45,
                                    linewidth=3, fill=False)
    ax.add_patch(e1)

    plt.plot([B1/ st_step, Smatrix.shape[0]], [A1/ st_step, A1/ st_step], color="k",
             linestyle="--", linewidth=2)
    plt.plot([B2/ st_step, Smatrix.shape[0]], [A2/ st_step, A2/ st_step], color="k",
             linestyle="--", linewidth=2)
    plt.plot([B1/ st_step, B1/ st_step], [A1/ st_step, Smatrix.shape[0]], color="k",
             linestyle="--", linewidth=2)
    plt.plot([B2/ st_step, B2/ st_step], [A2/ st_step, Smatrix.shape[0]], color="k",
             linestyle="--", linewidth=2)

    plt.xlim([0, Smatrix.shape[0]])
    plt.ylim([Smatrix.shape[1], 0])

    ax.yaxis.set_label_position("right")
    ax.yaxis.tick_right()

    plt.xlabel("frame no")
    plt.ylabel("frame no")
    plt.title("Self-similarity matrix")

    plt.show()
开发者ID:tyiannak,项目名称:pyAudioAnalysis,代码行数:60,代码来源:audioAnalysis.py


示例19: test

def test():
    rate, data = wavfile.read('/Users/hehehehehe/Desktop/workspace/final/data/musicvideo/musicvideo.wav')
    filtereddata = numpy.fft.rfft(data, axis=0)
    print (data)
    filteredwrite = numpy.fft.irfft(filtereddata, axis=0)
    print (filteredwrite)
    wavfile.write('TestFiltered.wav', rate, filteredwrite)
开发者ID:areshero,项目名称:hahahha,代码行数:7,代码来源:audio.py


示例20: wavwriteStereo

def wavwriteStereo(yLeft, yRight, fs, filename, inputSound):
    """
    Write a stereo sound file from 2 arrays with the channels sounds and the sampling rate
    yLeft: floating point array of one dimension,
    yRight: floating point array of one dimension,
    fs: sampling rate
    filename: name of file to create
    inputSound: original sound, used for auto-attenuation of the output sound
    """
    if yLeft.size != yRight.size: raise ValueError('wavwriteStereo: Left and Right sound samples input arrays have different sizes')
    yMaxMagnitude = max(abs(max(yLeft)),abs(max(yRight)),abs(min(yLeft)),abs(min(yRight)))
    inputMaxMagnitude = max(abs(max(inputSound)),abs(min(inputSound)))
    attenuationRatio = inputMaxMagnitude / yMaxMagnitude
#    print 'yMaxMagnitude ==',yMaxMagnitude
#    print 'inputMaxMagnitude ==',inputMaxMagnitude
#    print 'attenuationRatio ==',attenuationRatio
    xLeft = copy.deepcopy(yLeft)                     # copy array
    xLeft *= attenuationRatio                        # scale output sound to the input sound range
    xLeft *= INT16_FAC                               # scaling floating point -1 to 1 range signal to int16 range
    xLeft = np.int16(xLeft)                          # converting to int16 type
    xRight = copy.deepcopy(yRight)                   # copy array
    xRight *= attenuationRatio                       # scale output sound to the input sound range
    xRight *= INT16_FAC                              # scaling floating point -1 to 1 range signal to int16 range
    xRight = np.int16(xRight)                        # converting to int16 type
    xStereo = np.transpose(np.array([xLeft,xRight]))
    write(filename, fs, xStereo)
开发者ID:hello-sergei,项目名称:sms-tools,代码行数:26,代码来源:utilFunctions.py



注:本文中的scipy.io.wavfile.write函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python six.callable函数代码示例发布时间:2022-05-27
下一篇:
Python wavfile.read函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap