Esempio n. 1
2
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)
Esempio n. 2
0
def prob4():
	samplerate = 22050
	noise = sp.int16(sp.random.randint(-32767,32767,samplerate*10)) # Create 10 seconds of mono white noise
	wavfile.write('white_noise.wav',22050,noise)
	f = sp.fft(sp.float32(noise))
	plt.plot(sp.absolute(f))
	plt.show()
Esempio n. 3
0
def prob4(filename='saw.wav', new_rate = 11025, outfile='prob4.wav'):
    """Down-samples a given .wav file to a new rate and saves the resulting
    signal as another .wav file.
    
    Parameters
    ----------
    filename : string, optional
        The name of the .wav sound file to be down-sampled.
        Defaults to 'saw.wav'.
    new_rate : integer, optional
        The down-sampled rate. Defaults to 11025.
    outfile : string, optional
        The name of the new file. Defaults to prob4.wav.

    Returns
    -------
    None
    """
    old_rate, in_sig = wavfile.read(filename)
    fin = fftw.fft(sp.float32(in_sig))
    # Use if scipy_fftpack is unavailable
    # fin = sp.fft(sp.float32(in_sig))
    nsiz = sp.floor(in_sig.size * new_rate / old_rate)
    nsizh = sp.floor(nsiz / 2)
    fout = sp.zeros(nsiz) + 0j
    fout[0:nsizh] = fin[0:nsizh]
    fout[nsiz-nsizh+1:] = sp.conj(sp.flipud(fout[1:nsizh]))
    out = sp.real(sp.ifft(fout))
    out = sp.int16(out/sp.absolute(out).max() * 32767)
    plot_signal(filename)
    wavfile.write('prob4.wav',new_rate,out)
    print ""; plot_signal('prob4.wav')
Esempio n. 4
0
def down_sample(filename, new_rate, outputfile=None):
    """
    Create a down-sampled copy of the provided .wav file.  Unless overridden, the output
        file will be of the form "down_<orginalname>.wav"
        
    Parameters
    ----------
    filename : string
        input .wav file
    new_rate : int
        sample rate of output file
    outputfile : string
        name of output file
    """

    if outputfile is None:
        outputfile = "down_" + filename

    old_rate, in_sig = wavfile.read(filename)
    in_sig = sp.float32(in_sig)
    fin = sp.fft(in_sig)
    nsiz = sp.floor(in_sig.size * new_rate / old_rate)
    nsizh = sp.floor(nsiz / 2)
    fout = sp.zeros(nsiz)
    fout = fout + 0j
    fout[0:nsizh] = fin[0:nsizh]
    fout[nsiz - nsizh + 1 :] = sp.conj(sp.flipud(fout[1:nsizh]))
    out = sp.ifft(fout)
    out = sp.real(out)  # Take the real component of the signal
    out = sp.int16(out / sp.absolute(out).max() * 32767)
    wavfile.write(outputfile, new_rate, out)
Esempio n. 5
0
def prob5():
	rate, sig = wavfile.read('tada.wav')
	sig = sp.float32(sig)
	noise = sp.float32(sp.random.randint(-32767,32767,sig.shape))
	out = sp.ifft(sp.fft(sig)*sp.fft(noise))
	out = sp.real(out)
	out = sp.int16(out/sp.absolute(out).max() * 32767)
	wavfile.write('white-conv.wav',rate,out)
Esempio n. 6
0
def write(param,signal):
    st = tempfile.TemporaryFile()
    wf=wave.open(st,'wb')
    wf.setparams(params)
    s=sp.int16(signal*32767.0).tostring()
    wf.writeframes(s)
    st.seek(0)
    print st.read()
Esempio n. 7
0
def white_noise(outfile='prob4.wav'):
    """Generate some white noise, write it to the specified outfile,
    and plot the spectrum (DFT) of the signal.
    """
    samplerate = 44100
    noise = sp.int16(sp.random.randint(-32767, 32767, samplerate*10))
    N = Signal(samplerate, noise)
    N.write_to_file(outfile)
    N.plot(True)
        def callback(in_data, frame_count, time_info, status):
            # data = q.get()

            d = self.wf.readframes(frame_count)
            print frame_count
            buf = scipy.fromstring(d, scipy.int16)
            d2 = scipy.signal.lfilter(IIR_b, IIR_a, buf)
            data = scipy.int16(d2).tostring()
            return (data, pyaudio.paContinue)
Esempio n. 9
0
def write(param, signal):
    st = tempfile.TemporaryFile()
    wf = wave.open(st, 'wb')
    wf.setparams(params)
    s = sp.int16(signal*32767.0).tostring()
    wf.writeframes(s)
    st.seek(0)
    if six.PY2:
        print(st.read())
    else:
        sys.stdout.buffer.write(st.read())
Esempio n. 10
0
def white_noise(outfile='prob4.wav'):
    """Generate some white noise, write it to the specified outfile,
    and plot the spectrum (DFT) of the signal.
    """
    samplerate = 22050
    # Create 10 seconds of mono white noise
    noise = sp.int16(sp.random.randint(-32767,32767,samplerate*10)) 
    wavfile.write(outfile,22050,noise)
    f = sp.fft(sp.float32(noise))
    plt.plot(sp.absolute(f))
    plt.show()
Esempio n. 11
0
def white_noise(outfile='prob4.wav'):
    """Generate some white noise, write it to the specified outfile,
    and plot the spectrum (DFT) of the signal.
    """
    samplerate = 44100
    w_noise = sp.int16(sp.random.randint(-32767,32767, samplerate*10.))
    spectrum = sp.fft(w_noise)
    wavfile.write(outfile,samplerate,w_noise)
    frequency = samplerate*(np.arange(1,len(spectrum)+1,1)*1.)/len(w_noise)
    plt.plot(frequency, spectrum)
    plt.show()
    pass
Esempio n. 12
0
def problem1():
    #clean up noisy signal "The only thing to fear is fear itself"
    rate,data = wavfile.read("Noisysignal2.wav")
    fsig = sp.fft(data,axis=0)
    for j in xrange(14999,50000):
        fsig[j] = 0
        fsig[-j] = 0
    newsig = sp.ifft(fsig)
    newsig = sp.real(newsig)
    newsig = sp.int16(newsig/sp.absolute(newsig).max() * 32767)
    wavfile.write("output.wav", rate, newsig)
    return newsig
Esempio n. 13
0
def prob3():
	rate1,sig1 = wavfile.read('chopinw.wav')
	n = sig1.shape[0]
	rate2,sig2 = wavfile.read('balloon.wav')
	m = sig2.shape[0]
	sig1 = sp.append(sig1,sp.zeros((m,2)))
	sig2 = sp.append(sig2,sp.zeros((n,2)))
	f1 = sp.fft(sig1)
	f2 = sp.fft(sig2)
	out = sp.ifft((f1*f2))
	out = sp.real(out)
	scaled = sp.int16(out/sp.absolute(out).max() * 32767)
	wavfile.write('test.wav',rate1,scaled)
def plot_cleaned_signal():
    plt.close('all')
    rate,data = wavfile.read('Noisysignal1.wav')
    fsig = sp.fft(data,axis = 0)
    for j in xrange(10000,20000):
        fsig[j]=0
        fsig[-j]=0

    newsig=sp.ifft(fsig)
    newsig = sp.real(newsig)
    newsig = sp.int16(newsig/sp.absolute(newsig).max() * 32767)    
    plt.figure()
    plt.plot(newsig)
    plt.savefig('Cleanedsignal.pdf')
Esempio n. 15
0
def convertToBinaryPredictor(x):
    arr = []
    a = 0
    for i in SP.arange(x.size):
        arr.append(bin(x[i,0])[2:])
        l = max(a, bin(x[i,0])[2:].__len__())
    X = SP.zeros((x.size,l))

    for i in SP.arange(x.size):
        head0=l-arr[i].__len__()
        for j in SP.arange(head0):
            X[i,j] = 0
        for j in SP.arange(arr[i].__len__()):
            X[i,head0+j] = SP.int16(arr[i][j])
    return X
Esempio n. 16
0
def clean_signal(outfile='prob1.wav'):
    """Clean the 'Noisysignal2.wav' file. Plot the resulting sound
    wave and write the resulting sound to the specified outfile.
    """
    rate, data = wavfile.read('Noisysignal2.wav')
    jfk = lab9.Signal(rate, data)
    jfk.plot(True)
    fsig = sp.fft(data, axis = 0)
    for j in xrange(14500,50000):
        fsig[j]=0
        fsig[-j]=0
    newsig = sp.ifft(fsig)
    newsig = sp.real(newsig)
    newsig = sp.int16(newsig/sp.absolute(newsig).max()*32767)
    clear = lab9.Signal(rate,newsig)
    clear.write_file(outfile)
    clear.plot(True)
    pass
Esempio n. 17
0
def prob1():
	rate,data = wavfile.read('Noisysignal2.wav')
	fsig = sp.fft(data,axis = 0)
	f = sp.absolute(fsig)
	plt.plot(f[0:f.shape[0]/2])
	for j in xrange(14020,50001):
		fsig[j]=0
		fsig[-j]=0

	newsig=sp.ifft(fsig)
	f = sp.absolute(fsig)
	plt.figure()
	plt.plot(f[0:f.shape[0]/2])
	plt.show()
	plt.close()
	newsig = sp.ifft(fsig).astype(float)
	scaled = sp.int16(newsig/sp.absolute(newsig).max() * 32767)
	wavfile.write('cleansig2.wav',rate,scaled)
        def threader():
            for i in range(100):
                # 時間計測
                start_b = time.time()

                #  オーディオデータの呼び出し
                d = self.wf.readframes(BUFFER_SIZE)  # str
                # strをintに変換
                buf = scipy.fromstring(d, scipy.int16)
                # フィルタリング
                data = scipy.signal.lfilter(IIR_b, IIR_a, buf)
                # strに変換
                self.buffer = scipy.int16(data).tostring()

                q.put(self.buffer)

                # パフォーマンス
                elapsed_time = time.time() - start_b
                print("buffer_time:{0}".format(elapsed_time))
Esempio n. 19
0
def convolve(source='chopin.wav', pulse='balloon.wav', outfile='prob3.wav'):
    """Convolve the specified source file with the specified pulse file, then
    write the resulting sound wave to the specified outfile.
    """

    input_rate, input_signal = wavfile.read(source)
    ballon_rate, ballon_signal = wavfile.read(pulse)
    input_signal_zeros = np.hstack((input_signal[:,1], np.zeros(5*44100)))
    full_signal_len = len(input_signal_zeros)
    num_of_zeros_for_ballon = full_signal_len - len(ballon_signal)
    ballon_middle = len(ballon_signal) / 2
    balloon_signal_zeros = np.hstack([ballon_signal[:ballon_middle,1], np.zeros((num_of_zeros_for_ballon)), ballon_signal[ballon_middle:, 1]])
    full_balloon = balloon_signal_zeros
    full_chopin = input_signal_zeros
    fourier_convolution = np.multiply(sp.fft(full_chopin), sp.fft(full_balloon))
    result = sp.ifft(fourier_convolution)
    result = sp.real(result)
    result = sp.int16(result / sp.absolute(result).max() * 32767)
    final = Signal(input_rate, result.real)
    final.write_to_file(outfile)
Esempio n. 20
0
 def importWave(self):
   """Wave file to ndarray"""
   wf = wave.open(self.filename, 'rb')
   waveframes = wf.readframes(wf.getnframes())
   self.framerate = wf.getframerate()
   data = sp.fromstring(waveframes, sp.int16)
   self.duration = float(wf.getnframes()) / self.framerate
   if(wf.getnchannels() == 2):
     left = sp.array([data[i] for i in range(0, data.size, 2)])
     right = sp.array([data[i] for i in range(1, data.size, 2)])
     left = sp.int32(left); right = sp.int32(right)
     data = sp.int16(left+right) / 2
   if(self.fs == None):
     self.fs = self.framerate
   else:
     #data = self.resample(data, data.size*(self.fs/self.framerate))
     data = ssig.decimate(data, int(self.framerate/self.fs))
   self.duration_list = sp.arange(0, self.duration, 1./self.fs)
   data = ssig.detrend(data)
   return data
Esempio n. 21
0
def clean_signal(outfile='prob1.wav'):
    """Clean the 'Noisysignal2.wav' file. Plot the resulting sound
    wave and write the resulting sound to the specified outfile."""

    # Load the noisy .wav file
    rate, signal = wavfile.read('./Fourier2/Noisysignal2.wav')
    bad_signal = Signal(rate, signal)

    # Plot the original sound and its FFT
    plt.figure(1).suptitle("Original Sound")
    plt.subplot(121)
    bad_signal.plot()
    plt.subplot(122)
    bad_signal.plot(True)
    plt.show()

    # Cut out all the bad frequencies from the FFT
    fsig = sp.fft(bad_signal.signal, axis=0)
    for j in xrange(14999, 50000):
        fsig[j] = 0
        fsig[-j] = 0

    # inverse FFT back and scale
    newsig = sp.ifft(fsig)
    newsig = sp.real(newsig)
    newsig = sp.int16(newsig / sp.absolute(newsig).max() * 32767)
    clean_signal = Signal(rate, newsig)

    # Plot the clean sound and its FFT
    plt.figure(2).suptitle("Clean Sound")
    plt.subplot(121)
    clean_signal.plot(False)
    plt.subplot(122)
    clean_signal.plot(True)
    plt.show()

    bad_signal.plot()
    clean_signal.plot()
    plt.show()

    clean_signal.write_to_file("clean_2.wav")
Esempio n. 22
0
def prob1(freq=60, length=1):
    """Generates a sine wave, saves it as a .wav file, and uses plot_signal()
        to plot the signal.

    Parameters
    ----------
    freq : integer, optional
        The fequency of the sine wave. Defaults to 60.
    length : integer, optional
        The number of seconds the sine wave lasts. Defaults to 1.

    Returns
    -------
    None
    """

    samplerate = 44100
    stepsize = freq*2*sp.pi/samplerate
    signal = sp.sin(sp.arange(0, stepsize*length*samplerate, stepsize))
    scaled_signal = sp.int16(signal/sp.absolute(signal).max() * 32767)
    wavfile.write('problem1.wav', samplerate, scaled_signal)
Esempio n. 23
0
def convolve(source='chopin.wav', pulse='balloon.wav', outfile='prob3.wav'):
    """Convolve the specified source file with the specified pulse file, then
    write the resulting sound wave to the specified outfile.
    """
    rate, data = wavfile.read(source)
    rate_sample, data_sample = wavfile.read(pulse)
    ###Convert to Mono, gosh darn it this took forever to figure out.
    data = data[:,0]
    data_sample = data_sample[:,0]
    balancezeros = np.zeros(rate)
    data = np.append(data, balancezeros)
    newzeros = np.zeros((np.abs(len(data)-len(data_sample))))
    data_sample = np.append(data_sample,newzeros)
    fourier = np.fft.fft(data)
    fourier_sample = np.fft.fft(data_sample)
    ##This element-wise multiplies the two products
    conv = fourier*fourier_sample
    sig = np.real(sp.ifft(conv))
    sig = sp.int16(sig/sp.absolute(sig).max()*32767)
    wavfile.write(outfile,rate,sig)
    pass
Esempio n. 24
0
def clean_signal(outfile='prob1.wav'):
    """Clean the 'Noisysignal2.wav' file. Plot the resulting sound
    wave and write the resulting sound to the specified outfile.
    """

    rate,data = wavfile.read('Noisysignal2.wav')
    fsig = sp.fft(data,axis = 0)
    f = sp.absolute(fsig)
    plt.plot(f[0:f.shape[0]/2])
    for j in xrange(14020,50001):
        fsig[j]=0
        fsig[-j]=0

    newsig=sp.ifft(fsig)
    f = sp.absolute(fsig)
    plt.figure()
    plt.plot(f[0:f.shape[0]/2])
    plt.show()
    plt.close()
    newsig = sp.ifft(fsig).astype(float)
    scaled = sp.int16(newsig/sp.absolute(newsig).max() * 32767)
    wavfile.write(outfile,rate,scaled)
Esempio n. 25
0
def convolve(source='chopin.wav', pulse='balloon.wav', outfile='prob3.wav'):
    """Convolve the specified source file with the specified pulse file,
    then write the resulting sound wave to the specified outfile.
    """
    '''
    rate1,sig1 = wavfile.read(source)
    n = sig1.shape[0]
    rate2,sig2 = wavfile.read(pulse)
    m = sig2.shape[0]
    sig1 = sp.append(sig1,sp.zeros((m,2)))
    sig2 = sp.append(sig2,sp.zeros((n,2)))
    f1 = sp.fft(sig1)
    f2 = sp.fft(sig2)
    out = sp.ifft((f1*f2))
    out = sp.real(out)
    scaled = sp.int16(out/sp.absolute(out).max() * 32767)
    wavfile.write(outfile, rate1, scaled)
    '''

    # Read in the files
    rate1, signal  = wavfile.read(source)
    rate2, impulse = wavfile.read(pulse)
    
    # pad signal with zeros
    sig = sp.zeros((signal.shape[0]+impulse.shape[0],2))
    sig[:len(signal)] = signal
    imp = sp.zeros_like(sig)
    imp[:len(impulse)] = impulse
    
    # fourier transforms (we HAVE to have a warning box about the axis=0 stuff)
    f1 = sp.fft(sig, axis=0)
    f2 = sp.fft(imp, axis=0)
    out = sp.ifft(f1*f2, axis=0)
    
    # prepping output and writing file
    out = sp.real(out)
    scaled = sp.int16(out/sp.absolute(out).max() * 32767)
    wavfile.write(outfile, rate1, scaled)
Esempio n. 26
0
def read_mhd(mhd_path):
    """ reads the data from an mhd file and returns a np array. The data
    type to read is specified from the tifffile module by the tiff reading
    capabilities. Based on code from the pirt library.

    see: https://bitbucket.org/almarklein/pirt"""

    # Load description from mhd file
    mhd = open(mhd_path,'r').read()

    # Get data filename and load raw data
    raw_path = re.findall('ElementDataFile = (.+)',mhd)[0]

    # if the path in the mhd is not an absolute path, make it one
    if raw_path[0] != '/':
        raw_path = os.path.join(os.path.dirname(mhd_path),os.path.basename(raw_path))

    # get dimensions
    dimensions = sp.int16(re.findall('DimSize = (.+)',mhd)[0].split())

    # get correct datatype mapping
    mhd_dtype = re.findall('ElementType = (.+)',mhd)[0]
    dtype = get_np_dtype(mhd_dtype)

    # read and reshape
    fh = open(raw_path, 'rb')
    data = sp.frombuffer(fh.read(),dtype = dtype)

    if len(dimensions) == 2:
        data_reshape = sp.reshape(data,(dimensions[1],dimensions[0]))
        data_reshape = data_reshape.T
    if len(dimensions) == 3: # FIXME
        sys.exit()
        data_reshape = sp.reshape(data,(dimensions[2],dimensions[1],dimensions[0]))

    return data_reshape
Esempio n. 27
0
def gen_sinusoid(freq, length):
    samplerate = 44100 # 44100 samples per second
    stepsize = freq * 2 * sp.pi/samplerate
    sig = sp.sin(sp.arange(0, stepsize*length*samplerate, stepsize))
    scaled = sp.int16(sig/sp.absolute(sig).max() * 32767)
    return samplerate, scaled
Esempio n. 28
0
    synth.setframerate(samplingrate)

    remain = sound.getnframes()

    while remain > 0:
        s = min(chunk, remain)
        # read frames
        data_sound = sound.readframes(s)
        data_noise = noise.readframes(s)
        # convert
        ary_sound = sp.fromstring(data_sound, sp.int16)
        ary_noise = sp.fromstring(data_noise, sp.int16)

        int32_ary_sound = sp.int32(ary_sound)
        int32_ary_noise = sp.int32(ary_noise)
        ary2 = sp.int16(int32_ary_sound + int32_ary_noise)
        data2 = ary2.tostring()
        synth.writeframes(data2)
        remain = remain - s
    sound.close()
    noise.close()
    synth.close()

    infile = 'tools/sound/noisy.wav'
    signal, params = read_signal(infile, WINSIZE)
    nf = len(signal) / (WINSIZE / 2) - 1
    sig_out = sp.zeros(len(signal), sp.float32)
    window = sp.hanning(WINSIZE)

    ms = MinimumStatistics(WINSIZE, window, params[2])
    NP_lambda = compute_avgpowerspectrum(signal[0:WINSIZE * int(params[2] / float(WINSIZE) / 3.0)],
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import scipy as sp
import scipy.signal as sig
import wave

fsamp = 44100.0
fpass = 5000.0
fstop = 6000.0
wp = fpass / (fsamp / 2 )
ws = fstop / (fsamp / 2 )
b,a = sig.iirdesign(wp, ws, 1, 30)
fs, h = sig.freqs(b,a)

filename='white_noise2.wav'
wf = wave.open(filename,'rb')
n=wf.getnframes()
s=wf.readframes(n)
x = sp.fromstring(s,sp.int16)
y = sig.lfilter(b,a,x)

o_filename='filtered.wav'
wf_o=wave.open(o_filename,'wb')
wf_o.setnchannels(1)
wf_o.setsampwidth(2)
wf_o.setframerate(44100)
wf_o.writeframes(sp.int16(y).tostring())
wf_o.close()
wf.close()
Esempio n. 30
0
    rate2,balloon = wavfile.read('balloon.wav')
    
    # pad signal with zeros
    sig = np.zeros((piano.shape[0]+balloon.shape[0],2))
    sig[:len(piano)] = piano
    imp = np.zeros_like(sig)
    imp[:len(balloon)] = balloon
    
    # fourier transforms
    f1 = fftw.fft(sig,axis=0)
    f2 = fftw.fft(imp,axis=0)
    out = sp.ifft((f1*f2),axis=0)
    
    # prepping output and writing file
    out = sp.real(out)
    scaled = sp.int16(out/sp.absolute(out).max() * 32767)
    wavfile.write('test.wav',rate1,scaled)
    
#Problem 4. Let's make the "tada" circular convolution example a problem instead.
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