示例#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)
示例#2
0
 def __init__(self, channel, fs, bits, filename, normalize=False, compress=True):
     self.filename = filename
     self.win = wave.open(filename, 'w')
     self.channel = channel
     self.win.setnchannels(int16(channel))
     self.bits = bits
     self.win.setsampwidth(int16(bits / 8))
     self.fs = fs
     self.win.setframerate(fs)
     self.normalize = normalize
     self.compress = compress
     return
示例#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')
示例#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)
示例#5
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()
示例#6
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')
示例#7
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()
示例#8
0
def write(fname, params,signal):
#    st = tempfile.TemporaryFile()
#    wf=wave.open(st,'wb')
    wf=wave.open(fname,'wb')
    wf.setparams(params)
    s=sp.int16(signal*32767.0).tostring()
    wf.writeframes(s)
    wf.close()
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)
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()
示例#11
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)
        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)
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()
示例#14
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
    noise = sp.int16(sp.random.randint(-32767, 32767, samplerate * 10))
    wf.write(outfile, samplerate, noise)
    plt.plot(abs(noise))
    plt.show()
示例#15
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)
示例#16
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())
示例#17
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()
示例#18
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())
示例#19
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()
示例#20
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
示例#21
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
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)
示例#23
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')
示例#25
0
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')
示例#26
0
def wavwrite(i_x, fs, bits, filename, normalize=False, compress=True):
    if i_x.ndim == 1:
        x = i_x.reshape(len(i_x), 1)
    elif i_x.ndim == 2:
        x = i_x
    else:
        assert False
    
    win = wave.open(filename, 'w')
    win.setnchannels(int16(x.shape[1]))
    win.setsampwidth(int16(bits / 8))
    win.setframerate(fs)
    if compress:
        positivelimit = ((2 ** (bits - 1) - 1) / float(2 ** (bits - 1)))
        x = maximum(-1.0, minimum(x, positivelimit))
#    if compress:
#        x = maximum(-1.0, minimum(x, 1.0))
    if normalize:
        x /= abs(x).max()
    x = x * (2 ** (bits - 1));
    win.writeframes(array(x, int16).tostring())
    win.close()
    return
示例#27
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
示例#28
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
示例#29
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
示例#30
0
def wavwrite_old(data, fs, bit, fname):
    """
    Write wave data to file
    
    Parameters:
      data: ndarray
        wave data
      fs: float
        samplingrate
      bit: int
        bit depth
      fname: string
        output filename
        
    Returns:
     result: int
       error code (0: OK -1: NG)
    """
     
    wp = wave.open(fname, 'w')

    wp.setsampwidth(bit/8)
    wp.setframerate(fs)
    if (len(data.shape) == 2):
        n_channels = 2
        wp.setnchannels(n_channels)
        n_smp = data.shape[1]
        interleaved = sp.zeros(n_channels*n_smp)
        for i, (ldata,rdata) in enumerate(zip(data[0], data[1])):
            interleaved[2*i] = ldata
            interleaved[2*i+1] = rdata
        
    elif (len(data.shape) == 1):
        n_channels = 1
        n_smp = data.shape[0]
        wp.setnchannels(n_channels)
        interleaved = data
    else:
        return -1

    interleaved = interleaved.astype('int')

    wData = sp.int16(interleaved).tostring()

    wp.writeframes(wData)
    
    return 0
示例#31
0
def reorder_labels(labels):

    nClusters = sp.int32(sp.amax(labels.flatten()) + 1)
    labels0_vec = sp.zeros((labels.shape[0], nClusters), 'bool')
    labelsi_vec = labels0_vec.copy()
    for i in range(nClusters):
        labels0_vec[:, i] = (labels[:, 0] == i)

    for i in range(labels.shape[1]):
        for j in range(nClusters):
            labelsi_vec[:, j] = (labels[:, i] == j)
        D = pairwise_distances(labelsi_vec.T, labels0_vec.T, metric='dice')
        D[~sp.isfinite(D)] = 1
        ind1 = linear_assignment(D)
        labels[:, i] = ind1[sp.int16(labels[:, i]), 1]

    return labels
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)
示例#33
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)
示例#34
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 = wf.read('Noisysignal2.wav')
    fsig = sp.fft(data, axis = 0)
    plt.plot(fsig)
    plt.show()
    for j in xrange(14000,50000):
        fsig[j] = 0
        fsig[-j] = 0

    newsig = sp.ifft(fsig)
    newsig = np.real(newsig)
    newsig = sp.int16(newsig/sp.absolute(newsig).max()*32767)

    wf.write(outfile, rate, newsig)
    print "F.D.R. is saying only thing we have to fear is fear itself."
示例#35
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
示例#36
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
        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))
示例#38
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
示例#39
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)
示例#40
0
def smooth_patch(surf, iterations=15, relaxation=0.1):
    smoothFilter = vtkSmoothPolyDataFilter()
    smoothFilter.SetInputData(createPolyData(surf.vertices, surf.faces))
    smoothFilter.SetNumberOfIterations(iterations)
    smoothFilter.SetRelaxationFactor(relaxation)
    smoothFilter.Update()
    surf1 = smoothFilter.GetOutput()
    pts = surf1.GetPoints()
    vert1 = vtk_to_numpy(pts.GetData())
    faces1 = surf1.GetPolys()
    f1 = faces1.GetData()
    f2 = vtk_to_numpy(f1)
    f2 = f2.reshape(sp.int16(len(f2) / 4), 4)

    class surf2(surf):
        pass

    surf2.faces = f2[:, 1:]
    surf2.vertices = vert1
    return surf2
示例#41
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")
示例#42
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_piano, data_piano = wf.read(source)
    rate_impulse, data_impulse = wf.read(pulse)
    data_impulse = data_impulse[:,0]
    data_piano = data_piano[:,0]
    new_data_piano = np.hstack((data_piano, np.zeros(len(data_piano))))
    wf.write('teststack', rate_piano, new_data_piano)

    dst = np.hstack((np.zeros(len(new_data_piano)-len(data_impulse))))

    half1 = data_impulse[:len(data_impulse)/2:1]
    half2 = data_impulse[len(data_impulse)/2::1]
    new_impulse = np.hstack((np.hstack((half1, dst)), half2))
    convolution = sp.ifft(sp.fft(new_data_piano)*sp.fft(new_impulse))
    convolution = np.real(convolution)
    convolution = sp.int16(convolution/sp.absolute(convolution).max()*32767)

    wf.write(outfile, rate_piano, convolution)
示例#43
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
示例#44
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
示例#45
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)
示例#46
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)
示例#47
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)
示例#48
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)
示例#49
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)
示例#50
0
文件: IOtools.py 项目: Dahaniel/ILTIS
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
示例#51
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)
示例#52
0
文件: IOtools.py 项目: grg2rsr/ILTIS
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
示例#53
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
    count1 += 1

print("Avg. Silhoutte Score is:%f" % sp.mean(silhouette_avg))

labs_all0_vec = sp.zeros((labs_all.shape[0], nClusters + 1), 'bool')
labs_alli_vec = labs_all0_vec.copy()
for i in range(nClusters + 1):
    labs_all0_vec[:, i] = (labs_all[:, 0] == i)

for i in range(1, 40):
    for j in range(nClusters + 1):
        labs_alli_vec[:, j] = (labs_all[:, i] == j)

    D = pairwise_distances(labs_alli_vec.T, labs_all0_vec.T, metric='dice')
    ind1 = linear_assignment(D)
    labs_all[:, i] = ind1[sp.int16(labs_all[:, i]), 1]

s = r
s.vColor = sp.zeros(s.vertices.shape)
label_vert, lab_count = sp.stats.mode(labs_all.T)
colr = get_cmap(nClusters + 1)
lab_count = sp.float32(lab_count.squeeze())
s.vColor = s.vColor + 1

for i in range(len(s.vertices)):
    #        print i, (lab_count[i]/sp.amax(lab_count)), colr(label_vert[0,i])[:3], (lab_count[i]/sp.amax(lab_count)), 0.55*sp.array(colr(label_vert[0,i])[:3])
    if label_vert[0, i] > 0:
        freq = ((lab_count[i] / sp.amax(lab_count)) -
                1.0 / nClusters) * (sp.float32(nClusters) / (nClusters - 1.0))
        s.vColor[i, ] = (1 -
                         freq) + freq * sp.array(colr(label_vert[0, i])[:3])
#!/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()
示例#56
0
def view_patch(r,
               attrib=[],
               opacity=1,
               fig=0,
               show=1,
               colorbar=1,
               clim=[0],
               outfile=0,
               azimuth=0,
               elevation=-90,
               colormap='jet',
               close=1):

    if show == 0:
        mlab.options.offscreen = True
#    else:

    if fig == 0:
        fig = mlab.figure(bgcolor=(1, 1, 1),
                          fgcolor=(0.5, 0.5, 0.5))  #(bgcolor=(1,1,1))
    else:
        mlab.figure(fig)
    if len(attrib) > 0:
        if len(clim) > 1:
            vmin = clim[0]
            vmax = clim[1]
        else:
            vmax = sp.amax(attrib)
            vmin = sp.amin(attrib)
        mlab.triangular_mesh(r.vertices[:, 0],
                             r.vertices[:, 1],
                             r.vertices[:, 2],
                             r.faces,
                             representation='surface',
                             opacity=opacity,
                             scalars=attrib,
                             colormap=colormap,
                             vmin=vmin,
                             vmax=vmax)
    elif len(r.vColor) > 0:
        sc = sp.arange(r.vertices.shape[0])
        mt = mlab.triangular_mesh(r.vertices[:, 0],
                                  r.vertices[:, 1],
                                  r.vertices[:, 2],
                                  r.faces,
                                  representation='surface',
                                  scalars=sc)
        colors = 255 * sp.ones((r.vertices.shape[0], 4))
        colors[:, :3] = sp.int16(255.0 * r.vColor)
        mt.module_manager.scalar_lut_manager.lut.table = colors

    mlab.gcf().scene.parallel_projection = True
    mlab.view(azimuth=azimuth, elevation=elevation)

    if colorbar > 0:
        mlab.colorbar(orientation='horizontal')

    if show > 0:
        mlab.draw()
        mlab.show(stop=True)


#    else:
#    mlab.options.offscreen=True

    if outfile != 0:
        mlab.savefig(outfile)

    if close == 1:
        mlab.close()

    if show != 0:
        return fig
示例#57
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)],
示例#58
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