def test_bad_wavread(self): """ Check wavread on bad file""" # Create a tmp audio file with non wav format, write some random data into it, # and check it can not be opened by wavread rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav') try: nbuff = 22050 noise = 0.1 * N.random.randn(nbuff) # Open the copy file for writing format = audio_format('aiff', 'pcm16') b = Sndfile(cfilename, 'w', format, 1, nbuff) b.write_frames(noise) b.close() b = Sndfile(cfilename, 'r') rcnoise = b.read_frames(nbuff) b.close() try: rnoise = wavread(cfilename)[0] raise Exception("wavread on non wav file succeded, expected to fail") except ValueError, e: pass #print str(e) + ", as expected" finally: close_tmp_file(rfd, cfilename)
def test_bad_wavread(self): """ Check wavread on bad file""" # Create a tmp audio file with non wav format, write some random data into it, # and check it can not be opened by wavread rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav') try: nbuff = 22050 noise = 0.1 * N.random.randn(nbuff) # Open the copy file for writing format = audio_format('aiff', 'pcm16') b = Sndfile(cfilename, 'w', format, 1, nbuff) b.write_frames(noise) b.close() b = Sndfile(cfilename, 'r') rcnoise = b.read_frames(nbuff) b.close() try: rnoise = wavread(cfilename)[0] raise Exception("wavread on non wav file succeded, expected to fail") except ValueError as e: pass #print str(e) + ", as expected" finally: close_tmp_file(rfd, cfilename)
def readFromAudioFile(filename, mono=False): ''' Calls audiolab to generate Sound object from wav and aiff files. If mono is true, returns the left channel only. ''' if ".wav" in filename: data, fs, encoding = wavread(filename) elif ".aiff" in filename: data, fs, encoding = aiffread(filename) else: raise ValueError("File extension not .wav or .aiff") if (len(data.shape)==2 and mono): return Sound(data[:,0],fs,filename) else: return Sound(data,fs,filename)
def test(): wavfile = "../golf_D.wav" data, fs = wavread(wavfile) ### STFT fftLen = 1024 win = hanning(fftLen) step = fftLen / 8 spectrogram = abs(stft(data, win, step)[:, :fftLen / 2 + 1]).T ### 表示 fig = pl.figure() fig.patch.set_alpha(0.) imshow_sox(spectrogram) pl.tight_layout() pl.show()
def test(): wavfile = "../golf_D.wav" data, fs = wavread(wavfile) ### STFT fftLen = 1024 win = hanning(fftLen) step = fftLen / 8 spectrogram = abs(stft(data, win, step)[:, : fftLen / 2 + 1]).T ### 表示 fig = pl.figure() fig.patch.set_alpha(0.) imshow_sox(spectrogram) pl.tight_layout() pl.show()
import matplotlib.pylab as plt import numpy as np import loudness as ln from audiolab import wavread #Audio loader fs = 32000 frameSize = 32 fileToLoad = "../../wavs/pureTones/pureTone_1000Hz_40dBSPL_32000Hz.wav" audio = ln.AudioFileCutter(fileToLoad, frameSize) audio.initialize() audioBank = audio.getOutput() nFrames = audio.getNFrames() out = np.zeros((audioBank.getNEars(), nFrames, frameSize)) for frame in range(nFrames): audio.process() for ear in range(audioBank.getNEars()): out[ear, frame] = audioBank.getSignal(ear,0) x, fs, enc = wavread(fileToLoad) y = out.flatten()[0:x.size] if np.allclose(y, x): print "Test comparing result of AudioFileCutter with audiolab's wavread: successful" else: print "Test comparing result of AudioFileCutter with audiolab's wavread: unsuccessful"
# -*- coding: utf-8 -*- """ Created on Sat Jan 18 13:00:45 2020 @author: Gulshan Rana """ import audiolab, scipy a, fs, enc = audiolab.wavread('audio1.wav') b, fs, enc = audiolab.wavread('beep.wav') c = scipy.vstack((a,b)) audiolab.wavwrite(c, 'ab.wav', fs, enc) d, fs, enc = audiolab.wavread('ab.wav') e, fs, enc = audiolab.wavread('ab.wav') f = scipy.vstack((d,e)) audiolab.wavwrite(f, 'finaud1.wav', fs, enc)
import pydbm.dictionary import numpy as np import numpy.lib.recfunctions as rfn import matplotlib.pyplot as plt import audiolab x, fs, p = audiolab.wavread('/Users/grahamboyes/Desktop/VibesMedium_7100-80.wav') D = pydbm.dictionary.Dictionary(fs) S = pydbm.dictionary.SpecDictionary(fs) dtype = 'hann' dur = 4096 hop = 128 tmin = 0 tmax = len(x)-dur winargs = {} D.addSTFT(dtype, dur, 128, tmin, tmax, **winargs) D.index() #dtype, midicents, scales, onsets, **kwargs) #S.addSTFT(dtype, dur, 128, tmin, tmax, **winargs) S.addNote(dtype, 7100, [dur, 1024], [np.arange(0, tmax, hop), np.arange(0, len(x)-1024, hop/2)], **winargs) S.index() #signal, cmax, srr_thresh, tolmidicents, maxPeaks, dBthresh, overspec model, res, sBook = S.mp(x.copy(), 1000, 35., 10000, 5, -80.0, 1) audiolab.wavwrite(model, '/Users/grahamboyes/Desktop/VibesMedium_7100-80_mod.wav', fs)
n = len(y) # lungime semnal k = arange(n) T = n / Fs frq = k / T # two sides frequency range frq = frq[range(n / 2)] # one side frequency range print "creating fft" Y = fft(y) / n # fft computing and normalization Y = Y[range(n / 2)] print "creating plot" plot(frq, abs(Y), 'r') # plotting the spectrum xlabel('Freq (Hz)') ylabel('|Y(freq)|') print "returning plot" Fs = 44100 # sampling r x, fs, bits = audiolab.wavread('30_yards_bark_cut_3.wav') y = x[:, 1] lungime = len(y) timp = len(y) / 44100. t = np.linspace(0, timp, len(y)) print "creating linspace" subplot(2, 1, 1) plot(t, y) xlabel('Time') ylabel('Amplitude') subplot(2, 1, 2) plotSpectrum(y, Fs) show()
import pydbm.data import pydbm.dictionary import pydbm.book import audiolab import numpy as np x, fs, p = audiolab.wavread('/Users/grahamboyes/Documents/Work/project_m/harm_fof.wav') list_of_corpora = ['/Users/grahamboyes/Documents/Work/project_m/16khz/ordinario/SoftMallet/forte', '/Users/grahamboyes/Documents/Work/project_m/16khz/ordinario/SoftMallet/piano'] S = pydbm.data.SoundDatabase(list_of_corpora) D = pydbm.dictionary.SoundgrainDictionary(16000, S) D.addCorpus(np.array([512, 1024, 2048, 4096]), 0) D.addCorpus(np.array([512, 1024, 2048, 4096]), 1) x_ = np.zeros(len(x) + max(D.atoms['duration'])) x_[0:len(x)] = x mod, res, B = D.mp(x_.copy(), 30, 10) audiolab.wavwrite(mod, '/Users/grahamboyes/Desktop/prawnprollip.wav', fs) sout = '/Users/grahamboyes/Desktop/testDIF.sdif' B.writeSDIF(sout) out = B.synthesize() audiolab.wavwrite(out, '/Users/grahamboyes/Desktop/prawnprollipsynth.wav', fs)
from tempfile import mkstemp from os.path import join, dirname from os import remove from audiolab import wavread, wavwrite (tmp, fs, enc) = wavread('test.wav') if tmp.ndim < 2: nc = 1 else: nc = tmp.shape[1] print "The file has %d frames, %d channel(s)" % (tmp.shape[0], nc) print "FS is %f, encoding is %s" % (fs, enc) fd, cfilename = mkstemp('pysndfiletest.wav') try: wavwrite(tmp, cfilename, fs = 16000, enc = 'pcm24') finally: remove(cfilename)
import os import numpy as np import pydbm.dictionary import pydbm.meta import pydbm.data import pydbm.atom import pydbm.utils import matplotlib.pyplot as plt import audiolab import scipy.fftpack as fftpack import scipy.signal as sig x, fs, p = audiolab.wavread('/Users/grahamboyes/Documents/Work/sound_corpora/MUMS_converted/DVD 3/STRINGS/CELLOS/CELLO/CelA#2_4.08sec.wav') T = pydbm.utils.MiscUtils() H = pydbm.atom.HannGen() w = 2048 k = 2048 hop = 256 cc = 100 pin = 0 pend = len(x) - w imp = np.zeros(w * 4) imp[0] = 1.
n = len(y) # lungime semnal k = arange(n) T = n/Fs frq = k/T # two sides frequency range frq = frq[range(n/2)] # one side frequency range print "creating fft" Y = fft(y)/n # fft computing and normalization Y = Y[range(n/2)] print "creating plot" plot(frq,abs(Y),'r') # plotting the spectrum xlabel('Freq (Hz)') ylabel('|Y(freq)|') print "returning plot" Fs = 44100; # sampling r x, fs, bits=audiolab.wavread('30_yards_bark_cut_3.wav') y = x[:,1] lungime=len(y) timp=len(y)/44100. t=np.linspace(0,timp,len(y)) print "creating linspace" subplot(2,1,1) plot(t,y) xlabel('Time') ylabel('Amplitude') subplot(2,1,2) plotSpectrum(y,Fs) show()
bits.append(0) return bits def get_message(fsk): message = "" for i in range(0, len(fsk), 10): current_byte = (fsk[i:i + 10])[1:9] # Get the middle 8 bits pow = [2**j for j in range(8)] # Get powers of 2 for total bits ascii = np.dot(current_byte, pow) # Get the ascii value message += chr(ascii) # Convert ascii to char return message print(get_message(get_FSK(mark_freq, space_freq))) # Print the hidden message elif choice == 3: message_to_hide = str( input("Please enter the path of the encoded message to hide: ")) file_to_hide_in = str( input("Please enter the name of the file to hide the message in: ")) a, fs, enc = audiolab.wavread(message_to_hide) b, fs, enc = audiolab.wavread(file_to_hide_in) c = scipy.vstack((a, b)) audiolab.wavwrite(c, 'hidden.wav', fs, enc) print("New file saved as 'hidden.wav'") else: print("Your input is not correct!") sys.exit()
import pydbm.data import pydbm.dictionary import numpy as np import audiolab x, fs, p = audiolab.wavread('../sounds/harm_fof.wav') sdif = '/Users/grahamboyes/Documents/Work/project_m/harm_fof_shape.sdif' list_of_corpora = ['/Users/grahamboyes/Documents/Work/sound_corpora/16k/ModernGrand/AF/ordinario_velshort/chromatic'] #Y = pydbm.data.PolygonGroup(sdif) S = pydbm.data.SoundDatabase(list_of_corpora) D = pydbm.dictionary.SoundgrainDictionary(fs, S) #for y in Y.polygons: # D.addPolygon(x.copy(), 1024, y, 2048, 256, 6) n = S.sdif2array('/Users/grahamboyes/Desktop/ballard.mrk.sdif', ['XTRD'])['XTRD'] n = (n['time'] * fs).astype(int) n = np.array([0, 1000, 2000, 4000, 8000, 16000, 17000, 18000, 20000, 24000]) D.addCorpus(n, 0) x_ = np.zeros(len(x) + max(D.atoms['duration'])) x_[0:len(x)] = x #global scalar g = max(abs(x_)) * 0.05
import audiolab import pydbm.dictionary import pydbm.data import numpy as np target = '/Users/grahamboyes/Desktop/AMEN_stereo.wav' outdir = '/Users/grahamboyes/Desktop' db = ['/Users/grahamboyes/Desktop/taggedsounds/machine'] xs, fs, p = audiolab.wavread(target) vecs = (xs[0:, 0], xs[0:, 1]) S = pydbm.data.SoundDatabase(db) #if there is a transient model somewhere n = S.sdif2array('/Users/grahamboyes/Desktop/AMEN_stereo.mrk.sdif', ['XTRD'])['XTRD'] n = (n['time'] * fs).astype(int) D = pydbm.dictionary.SoundgrainDictionary(fs, S) for i in xrange(len(db)): D.addCorpus(n, i) v = [] for ind, x in enumerate(vecs): x_ = np.zeros(len(x) + max(D.atoms['duration'])) x_[0:len(x)] = x mod, res, M = D.mp(x_.copy(), 300, 35) v.append(mod)
import os import numpy as np import pydbm.dictionary import pydbm.meta import pydbm.data import pydbm.atom import pydbm.utils import matplotlib.pyplot as plt import audiolab import scipy.fftpack as fftpack import scipy.signal as sig x, fs, p = audiolab.wavread('/Users/grahamboyes/Documents/Work/experiments_dup/experiments/test_samples/piano/MPdecomps/threePFNOF_4100_residual.wav') T = pydbm.utils.MiscUtils() H = pydbm.atom.HannGen() size = 16000 coefs = T.lpc(x[16000:17024], 17) imp = np.zeros(size) imp[0] = 1. h = np.random.randn(size) #* sig.lfilter([0.5, 0.7] , 1 ,np.random.randn(size)) #h = np.zeros(size) #for k in range(1, 40): # h += np.cos(2*np.pi*k*220./fs*np.arange(size))
from tempfile import mkstemp from os.path import join, dirname from os import remove from audiolab import wavread, wavwrite (tmp, fs, enc) = wavread('test.wav') if tmp.ndim < 2: nc = 1 else: nc = tmp.shape[1] print "The file has %d frames, %d channel(s)" % (tmp.shape[0], nc) print "FS is %f, encoding is %s" % (fs, enc) fd, cfilename = mkstemp('pysndfiletest.wav') try: wavwrite(tmp, cfilename, fs=16000, enc='pcm24') finally: remove(cfilename)
import audiolab import scipy from pylab import * x, fs, nbits = audiolab.wavread('laser_resampled.wav') audiolab.play(x, fs) N = 4*fs # four seconds of audio X = scipy.fft(x[:N]) Xdb = 20*scipy.log10(scipy.absolute(X)) f = scipy.linspace(0, fs, N, endpoint=False) pylab.plot(f, Xdb) pylab.xlim(0, 5000) # view up to 5 kHz Y = X*H y = scipy.real(scipy.ifft(Y)) """import pymedia import time import matplotlib.pyplot as plt import matplotlib.mlab as mlab import numpy as np import pylab as P f = open('manybeeps_resampled.wav', 'rb') s=f.read() spa = pymedia.audio.sound.SpectrAnalyzer(1, 575, 1024) bands= spa.asBands(5, s)
from audiolab import wavread data, fs, enc = wavread('test.wav')
filters = ['duration:[* TO 0.5]', 'samplerate:44100', 'channels:1', 'type:wav'] P = urllib.URLopener() outdir = '/Users/grahamboyes/Desktop/hackday' for page in range(low, high): P.retrieve("http://www.freesound.org/api/sounds/search/?q=%s&f=%s&p=%s&api_key=%s&format=xml"%(''.join([q + ' ' for q in query]), ''.join([f + ' ' for f in filters]), page, api_key), '%s/test.xml'%outdir) f = etree.parse('%s/test.xml'%outdir) root = f.getroot() for sound in root.findall('sounds'): for resource in sound.findall('resource'): P.retrieve(resource.find('serve').text + '?api_key=%s'%api_key, outdir + '/' + resource.find('original_filename').text) #a decomposition using the outdir x, fs, p = audiolab.wavread('/Users/grahamboyes/Documents/python/pythonDafx/SOUNDS/AMEN.wav') S = pydbm.data.SoundDatabase([outdir]) n = S.sdif2array('/Users/grahamboyes/Desktop/AMEN.mrk.sdif', ['XTRD'])['XTRD'] n = (n['time'] * fs).astype(int) D = pydbm.dictionary.SoundgrainDictionary(fs, S) D.addCorpus(n, 0) x_ = np.zeros(len(x) + max(D.atoms['duration'])) x_[0:len(x)] = x mod, res, M = D.mp(x_.copy(), 300, 35) audiolab.wavwrite(mod[0:len(x)], '%s/model.wav'%outdir, fs)