Exemplo n.º 1
0
 def test_read_no_ssnd_chunk(self):
     b = b'FORM' + struct.pack('>L', 4) + b'AIFC'
     b += b'COMM' + struct.pack('>LhlhhLL', 38, 0, 0, 0, 0, 0, 0)
     b += b'NONE' + struct.pack('B', 14) + b'not compressed' + b'\x00'
     with self.assertRaisesRegex(aifc.Error, 'COMM chunk and/or SSND chunk'
                                             ' missing'):
         aifc.open(io.BytesIO(b))
Exemplo n.º 2
0
 def test_read_wrong_number_of_channels(self):
     for nchannels in 0, -1:
         b = b'FORM' + struct.pack('>L', 4) + b'AIFC'
         b += b'COMM' + struct.pack('>LhlhhLL', 38, nchannels, 0, 8,
                                    0x4000 | 12, 11025<<18, 0)
         b += b'NONE' + struct.pack('B', 14) + b'not compressed' + b'\x00'
         b += b'SSND' + struct.pack('>L', 8) + b'\x00' * 8
         with self.assertRaisesRegex(aifc.Error, 'bad # of channels'):
             aifc.open(io.BytesIO(b))
Exemplo n.º 3
0
 def test_read_wrong_sample_width(self):
     for sampwidth in 0, -1:
         b = b'FORM' + struct.pack('>L', 4) + b'AIFC'
         b += b'COMM' + struct.pack('>LhlhhLL', 38, 1, 0, sampwidth,
                                    0x4000 | 12, 11025<<18, 0)
         b += b'NONE' + struct.pack('B', 14) + b'not compressed' + b'\x00'
         b += b'SSND' + struct.pack('>L', 8) + b'\x00' * 8
         with self.assertRaisesRegex(aifc.Error, 'bad sample width'):
             aifc.open(io.BytesIO(b))
Exemplo n.º 4
0
 def test_write_header_raises(self):
     fout = aifc.open(io.BytesIO(), 'wb')
     self.assertRaises(aifc.Error, fout.close)
     fout = aifc.open(io.BytesIO(), 'wb')
     fout.setnchannels(1)
     self.assertRaises(aifc.Error, fout.close)
     fout = aifc.open(io.BytesIO(), 'wb')
     fout.setnchannels(1)
     fout.setsampwidth(1)
     self.assertRaises(aifc.Error, fout.close)
Exemplo n.º 5
0
 def test_write_aiff_by_extension(self):
     sampwidth = 2
     fout = self.fout = aifc.open(TESTFN + '.aiff', 'wb')
     fout.setparams((1, sampwidth, 1, 1, b'ULAW', b''))
     frames = b'\x00' * fout.getnchannels() * sampwidth
     fout.writeframes(frames)
     fout.close()
     f = self.f = aifc.open(TESTFN + '.aiff', 'rb')
     self.assertEqual(f.getcomptype(), b'NONE')
     f.close()
Exemplo n.º 6
0
 def test_context_manager(self):
     with open(self.sndfilepath, 'rb') as testfile:
         with aifc.open(testfile) as f:
             pass
         self.assertEqual(testfile.closed, True)
     with open(TESTFN, 'wb') as testfile:
         with self.assertRaises(aifc.Error):
             with aifc.open(testfile, 'wb') as fout:
                 pass
         self.assertEqual(testfile.closed, True)
         fout.close() # do nothing
Exemplo n.º 7
0
def generate_samples(sample_folder, file_path, num_samples):

    output('Genearating samples for: {}'.format(file_path))

    f = aifc.open(file_path, "r")

    num_channels = f.getnchannels()
    sample_width = f.getsampwidth()
    frame_rate = f.getframerate()

    # Frame size = nchannels*samplesize bytes
    frame_size = num_channels * sample_width

    # One second of audio = nchannels*samplesize*framerate bytes
    bytes_per_second = frame_size * frame_rate

    data = f.readframes(f.getnframes())
    seconds = len(data) / bytes_per_second

    # 1/4 second
    min_sample_length = bytes_per_second / 4

    # 2 second
    max_sample_length = bytes_per_second * 2

    sample_number = 0

    while sample_number < num_samples:

        sample_name = uuid.uuid4()
        output('Generating sample: {} {}/{}'.format(sample_name, sample_number, num_samples), color='blue')

        sample_file = aifc.open('{}/{}.aif'.format(sample_folder, sample_name), 'w')
        sample_file.aiff()

        sample_file.setnchannels(num_channels)
        sample_file.setsampwidth(sample_width)
        sample_file.setframerate(frame_rate)
        sample_file.setcomptype('NONE', 'no compression')

        sample_file.setparams(sample_file.getparams())

        sample_length = random.randint(min_sample_length, max_sample_length)
        second_offset = random.randint(0, seconds - (max_sample_length / bytes_per_second))

        start_byte_index = second_offset * bytes_per_second
        end_byte_index = start_byte_index + sample_length

        sample_file.writeframesraw(data[start_byte_index:end_byte_index])

        sample_file.close()
        sample_number += 1

    f.close()
 def test_write(self):
     f = self.f = aifc.open(self.sndfilepath)
     fout = self.fout = aifc.open(TESTFN, 'wb')
     fout.aifc()
     fout.setparams(f.getparams())
     for frame in range(f.getnframes()):
         fout.writeframes(f.readframes(1))
     fout.close()
     fout = self.fout = aifc.open(TESTFN, 'rb')
     f.rewind()
     self.assertEqual(f.getparams(), fout.getparams())
     self.assertEqual(f.readframes(5), fout.readframes(5))
Exemplo n.º 9
0
 def test_read_markers(self):
     fout = self.fout = aifc.open(TESTFN, 'wb')
     fout.aiff()
     fout.setparams((1, 1, 1, 1, b'NONE', b''))
     fout.setmark(1, 0, b'odd')
     fout.setmark(2, 0, b'even')
     fout.writeframes(b'\x00')
     fout.close()
     f = self.f = aifc.open(TESTFN, 'rb')
     self.assertEqual(f.getmarkers(), [(1, 0, b'odd'), (2, 0, b'even')])
     self.assertEqual(f.getmark(1), (1, 0, b'odd'))
     self.assertEqual(f.getmark(2), (2, 0, b'even'))
     self.assertRaises(aifc.Error, f.getmark, 3)
Exemplo n.º 10
0
 def __enter__(self):
     assert self.stream is None, "This audio source is already inside a context manager"
     try:
         # attempt to read the file as WAV
         self.audio_reader = wave.open(self.filename_or_fileobject, "rb")
         self.little_endian = True
         # RIFF WAV is a little-endian format (most ``audioop`` operations assume frames are stored in little-endian form)
     except wave.Error:
         try:
             # attempt to read the file as AIFF
             self.audio_reader = aifc.open(self.filename_or_fileobject, "rb")
             self.little_endian = False # AIFF is a big-endian format
         except aifc.Error:
             # attempt to read the file as FLAC
             if hasattr(self.filename_or_fileobject, "read"):
                 flac_data = self.filename_or_fileobject.read()
             else:
                 with open(self.filename_or_fileobject, "rb") as f: flac_data = f.read()
         
             # run the FLAC converter with the FLAC data to get the AIFF data
             flac_converter = get_flac_converter()
             process = subprocess.Popen([
                 flac_converter,
                 "--stdout", "--totally-silent", # put the resulting AIFF file in stdout, and make sure it's not mixed with any program output
                 "--decode", "--force-aiff-format", # decode the FLAC file into an AIFF file
                 "-", # the input FLAC file contents will be given in stdin
             ], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
             aiff_data, stderr = process.communicate(flac_data)
             aiff_file = io.BytesIO(aiff_data)
             try:
                 self.audio_reader = aifc.open(aiff_file, "rb")
             except aifc.Error:
                 assert False, "Audio file could not be read as WAV, AIFF, or FLAC; check if file is corrupted"
             self.little_endian = False # AIFF is a big-endian format
     assert 1 <= self.audio_reader.getnchannels() <= 2, "Audio must be mono or stereo"
     self.SAMPLE_WIDTH = self.audio_reader.getsampwidth()
                                                                         
     # 24-bit audio needs some special handling for old Python versions (workaround for https://bugs.python.org/issue12866)
     samples_24_bit_pretending_to_be_32_bit = False
     if self.SAMPLE_WIDTH == 3: # 24-bit audio
         try: audioop.bias(b"", self.SAMPLE_WIDTH, 0) # test whether this sample width is supported (for example, ``audioop`` in Python 3.3 and below don't support sample width 3, while Python 3.4+ do)
         except audioop.error: # this version of audioop doesn't support 24-bit audio (probably Python 3.3 or less)
             samples_24_bit_pretending_to_be_32_bit = True # while the ``AudioFile`` instance will outwardly appear to be 32-bit, it will actually internally be 24-bit
             self.SAMPLE_WIDTH = 4 # the ``AudioFile`` instance should present itself as a 32-bit stream now, since we'll be converting into 32-bit on the fly when reading
                                                                                                 
     self.SAMPLE_RATE = self.audio_reader.getframerate()
     self.CHUNK = 4096
     self.FRAME_COUNT = self.audio_reader.getnframes()
     self.DURATION = self.FRAME_COUNT / float(self.SAMPLE_RATE)
     self.stream = AudioFile.AudioFileStream(self.audio_reader, self.little_endian, samples_24_bit_pretending_to_be_32_bit)
     return self
Exemplo n.º 11
0
def main():
    #raw    = aifc.open("/Users/katiemalone/Desktop/data_podcast/fisherfaces/fisherfaces.aif", "r")
    #edited = aifc.open("/Users/katiemalone/Desktop/data_podcast/fisherfaces/fisherfaces_edited.aif", "r")
    raw    = aifc.open("fisherfaces.aif", "r")
    edited = aifc.open("fisherfaces_edited.aif", "r")

    print raw.getparams()

    s_markers, b_markers = preprocess.signalBackgroundMarkers( raw ) 
    window_length = preprocess.findMaxWindow(s_markers)

    s_frames = preprocess.normedFrames( raw, window_length, start_points=s_markers)
#    drawFrames( s_frames )


    b_frames = preprocess.normedFrames( edited, window_length, n_samples=200 )
#    drawFrames( b_frames )

    features = []
    labels = []
    for ii in range(0, len(s_frames)):
        features.append(s_frames[ii])
        labels.append(1)
    for jj in range(0, len(b_frames)):
        features.append(b_frames[jj])
        labels.append(0)
    print "data acquisition done"

    features = np.asarray( features )
    labels = np.asarray( labels )

    features, labels = transform( features, labels )


#    f, axarr = plt.subplots(2, 2)
#    ctr = 0
    for ff, ll in zip(features, labels):
        if ll==0:
            #axarr[0, 0].scatter( ff[0], ff[1], color="red")
            plt.scatter( ff[0], ff[1], color="red")
        if ll==1:
            plt.scatter( ff[0], ff[1], color="blue")
#    for ii in range(0,n):
#        for jj in range(0,n):
#            axarr[ii, jj].plot( frames[ctr] )
#            ctr += 1
    plt.show()



    classify( features, labels )
Exemplo n.º 12
0
    def test_params_added(self):
        f = self.f = aifc.open(TESTFN, 'wb')
        f.aiff()
        f.setparams((1, 1, 1, 1, b'NONE', b''))
        f.close()

        f = self.f = aifc.open(TESTFN, 'rb')
        params = f.getparams()
        self.assertEqual(params.nchannels, f.getnchannels())
        self.assertEqual(params.sampwidth, f.getsampwidth())
        self.assertEqual(params.framerate, f.getframerate())
        self.assertEqual(params.nframes, f.getnframes())
        self.assertEqual(params.comptype, f.getcomptype())
        self.assertEqual(params.compname, f.getcompname())
Exemplo n.º 13
0
    def test_close_opened_files_on_error(self):
        non_aifc_file = findfile('pluck-pcm8.wav', subdir='audiodata')
        with check_no_resource_warning(self):
            with self.assertRaises(aifc.Error):
                # Try opening a non-AIFC file, with the expectation that
                # `aifc.open` will fail (without raising a ResourceWarning)
                self.f = aifc.open(non_aifc_file, 'rb')

            # Aifc_write.initfp() won't raise in normal case.  But some errors
            # (e.g. MemoryError, KeyboardInterrupt, etc..) can happen.
            with mock.patch.object(aifc.Aifc_write, 'initfp',
                                   side_effect=RuntimeError):
                with self.assertRaises(RuntimeError):
                    self.fout = aifc.open(TESTFN, 'wb')
Exemplo n.º 14
0
    def test_write_aiff_by_extension(self):
        sampwidth = 2
        filename = TESTFN + '.aiff'
        self.addCleanup(unlink, filename)

        fout = self.fout = aifc.open(filename, 'wb')
        fout.setparams((1, sampwidth, 1, 1, 'ULAW', ''))
        frames = '\x00' * fout.getnchannels() * sampwidth
        fout.writeframes(frames)
        fout.close()

        f = self.f = aifc.open(filename, 'rb')
        self.assertEqual(f.getcomptype(), 'NONE')
        f.close()
Exemplo n.º 15
0
def aiffread(filename):
    af = aifc.open(filename, "r")
    fs = af.getframerate()
    x = af.readframes(af.getnframes())
    x = np.frombuffer(x, dtype="int16") / 32768.0  # (-1, 1)に正規化
    af.close()
    return x, float(fs)
def specgram_large:
  nfft=256;
  nt=20;
  fs=2000;
  dt=1./fs;
  fmax=400;
  nframes = 4000

  # Read Data
  print filename
  f = aifc.open(filename, "r")
  strsig = f.readframes(nframes)
  f.close()
  x = numpy.fromstring(strsig, numpy.short).byteswap()
  n = len(x)
  
  # Initialize output
  nf=nfft/2.+1
  tt = numpy.arange(dt*(nfft-1)/2, (n-1)*dt-(nfft/2)*dt, nt * dt)
  ntt=len(tt)
  y = numpy.zeros(nf * ntt).reshape(nf, ntt);
 
  # Create Window vector
  xw = range(0, nfft)
  wind = map(lambda a: 0.5 * (1 - math.cos((a * 2 * math.pi) / (nfft - 1.0))), xw)
  for i in range(0, ntt):
    zi = numpy.arange(i*nt, nfft*(i+1) - i*(nfft-nt))
    xss = scipy.fft(x[zi] * wind, nfft)/nfft 
    yy = 2 * abs(xss[0:(nfft/2)+1])
    y[:, i] = yy

  # Return y
  return y.reshape(nf * ntt)
Exemplo n.º 17
0
 def __init__(self, path, speed=1, mark=0, interp=2, mul=1, add=0):
     pyoArgsAssert(self, "sOOiOO", path, speed, mark, interp, mul, add)
     PyoObject.__init__(self, mul, add)
     self._speed = speed
     self._mark = mark
     self._interp = interp
     path, speed, mark, interp, mul, add, lmax = convertArgsToLists(path, speed, mark, interp, mul, add)
     self._base_players = []
     self._base_objs = []
     self._snd_size, self._dur, self._snd_sr, self._snd_chnls, _format, _type = sndinfo(path[0])
     for i in range(lmax):
         try:
             sf = aifc.open(wrap(path, i))
             markerstmp = sf.getmarkers()
             sf.close()
             self._markers = [m[1] for m in markerstmp]
         except:
             self._markers = []
         self._base_players.append(
             SfMarkerLooper_base(wrap(path, i), self._markers, wrap(speed, i), wrap(mark, i), wrap(interp, i))
         )
     for i in range(lmax * self._snd_chnls):
         j = i // self._snd_chnls
         self._base_objs.append(
             SfMarkerLoop_base(wrap(self._base_players, j), i % self._snd_chnls, wrap(mul, j), wrap(add, j))
         )
Exemplo n.º 18
0
 def test_write_params_bunch(self):
     fout = aifc.open(io.BytesIO(), 'wb')
     fout.aifc()
     p = (1, 2, 3, 4, b'NONE', b'name')
     fout.setparams(p)
     self.assertEqual(fout.getparams(), p)
     fout.initfp(None)
Exemplo n.º 19
0
    def __init__(self, filename):
        self._fh = open(filename, 'rb')

        try:
            self._file = aifc.open(self._fh)
        except aifc.Error:
            # Return to the beginning of the file to try the WAV reader.
            self._fh.seek(0)
        else:
            self._needs_byteswap = True
            return

        try:
            self._file = wave.open(self._fh)
        except wave.Error:
            # Return to the beginning of the file to try the next reader
            self._fh.seek(0)
            pass
        else:
            self._needs_byteswap = False
            return

        try:
            self._file = sunau.open(self._fh)
        except sunau.Error:
            # Return to the beginning of the file to try the next reader
            self._fh.seek(0)
            pass
        else:
            self._needs_byteswap = True
            return

        raise UnsupportedError()
Exemplo n.º 20
0
def read_samples(dir):
    allSigs = np.zeros( (len(os.listdir(dir)),SAMPLE_LENGTH*SAMPLE_RATE) )
    filenames = []
    targets = []
    for cnt, filename in enumerate(os.listdir(dir)):
        if os.path.isfile(os.path.join(dir, filename)):
            filenames.append(filename)
            if dir == traindir:
                targets.append(int(re.search('(ms_TRAIN[0-9]*\_([0-9]*))',filename).group(2)))
            else:
                targets.append(0)
            sample = aifc.open(os.path.join(dir, filename), 'r')
            nframes = sample.getnframes()
            strSig = sample.readframes(nframes)
            sig = np.fromstring(strSig, np.short).byteswap()
            if nframes > 4000:
                sig = sig[nframes-4000//2:(nframes-4000//2)+4000]
            elif nframes < 4000:
                # appending is OK instead of symmetrical prepending and appending,
                # since we're going to sample patches anyway
                sig = np.append(sig,np.zeros(4000-nframes))
            allSigs[cnt,:] = sig
            sample.close()
    
    targets = np.array(targets)
    
    return filenames, targets, allSigs
Exemplo n.º 21
0
 def test_write_header_comptype_raises(self):
     for comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'):
         fout = aifc.open(io.BytesIO(), 'wb')
         fout.setsampwidth(1)
         fout.setcomptype(comptype, b'')
         self.assertRaises(aifc.Error, fout.close)
         fout.initfp(None)
Exemplo n.º 22
0
 def test_write_markers_raises(self):
     fout = aifc.open(io.BytesIO(), 'wb')
     self.assertRaises(aifc.Error, fout.setmark, 0, 0, b'')
     self.assertRaises(aifc.Error, fout.setmark, 1, -1, b'')
     self.assertRaises(aifc.Error, fout.setmark, 1, 0, None)
     self.assertRaises(aifc.Error, fout.getmark, 1)
     fout.initfp(None)
Exemplo n.º 23
0
 def test_write_params_raises(self):
     fout = aifc.open(io.BytesIO(), 'wb')
     wrong_params = (0, 0, 0, 0, b'WRNG', '')
     self.assertRaises(aifc.Error, fout.setparams, wrong_params)
     self.assertRaises(aifc.Error, fout.getparams)
     self.assertRaises(aifc.Error, fout.setnchannels, 0)
     self.assertRaises(aifc.Error, fout.getnchannels)
     self.assertRaises(aifc.Error, fout.setsampwidth, 0)
     self.assertRaises(aifc.Error, fout.getsampwidth)
     self.assertRaises(aifc.Error, fout.setframerate, 0)
     self.assertRaises(aifc.Error, fout.getframerate)
     self.assertRaises(aifc.Error, fout.setcomptype, b'WRNG', '')
     fout.aiff()
     fout.setnchannels(1)
     fout.setsampwidth(1)
     fout.setframerate(1)
     fout.setnframes(1)
     fout.writeframes(b'\x00')
     self.assertRaises(aifc.Error, fout.setparams, (1, 1, 1, 1, 1, 1))
     self.assertRaises(aifc.Error, fout.setnchannels, 1)
     self.assertRaises(aifc.Error, fout.setsampwidth, 1)
     self.assertRaises(aifc.Error, fout.setframerate, 1)
     self.assertRaises(aifc.Error, fout.setnframes, 1)
     self.assertRaises(aifc.Error, fout.setcomptype, b'NONE', '')
     self.assertRaises(aifc.Error, fout.aiff)
     self.assertRaises(aifc.Error, fout.aifc)
Exemplo n.º 24
0
def get_soundfile(filename,dplot = 1):
	"""
	reads in the acii file, optionally plots
	"""
	#open file
	wf = aifc.open(filename, 'rb')

	#read data
	data = wf.readframes(wf.getnframes())
	srate = wf.getframerate()

	#close file
	wf.close()

	#format data, time
	data_int = pylab.fromstring(data,dtype=np.int32)
	n = data_int.size
	time = np.arange(n)/float(srate)
	time = time*1000 #ms

	#plot sound file
	if dplot:
		fig = plt.figure()
		ax1 = fig.add_subplot(1,1,1)
		ax1.plot(time,data_int)
		ax1.set_xlim(min(time), max(time))
		ax1.set_xlabel("Time [ms]")
		ax1.set_ylabel("Amplitude")

	return data_int, srate
Exemplo n.º 25
0
def main():
    f = CurrentFont()
    a = aifc.open("aiff_out/aiffSlice.aiff", "wb")
    a.setnchannels(1)
    a.setsampwidth(4)
    a.setframerate(44100)
    #for i in range(80):
    #    v = sin(i/44100.0 * 440.0 * pi) * 2**7
    #    print v
    #    a.writeframes(pack("h", v))
    for n in f.selection:
        g = f[n]
        print n
        #for c in g.contours:
        #    print c.box
        #    for 
        for i in range(int(g.width)):
            pen = MarginPen(f, i, isHorizontal=False)
            g.draw(pen)
            l = pen.getAll()
            #print l,
            v = getAverage(l)
            #print v
            a.writeframes(pack("i", v))
            a.writeframes(pack("i", v))
            
    a.close()
Exemplo n.º 26
0
def compute_specgram(data_loc,train_folder,file_name):
	'''Retrieves time data from the aiff file and compute the spectogram for time_data'''  
	if not os.path.isfile(data_loc + '/' + train_folder + '/specgrams/' + file_name.split('.')[0] + '.png'):
		try:
			plt.figure(figsize=(18.,16.), dpi=50) #900x800
			f = aifc.open(os.path.join(data_loc,train_folder, file_name), 'r')
			str_frames = f.readframes(f.getnframes())
			#Fs = f.getframerate()
			Fs= 4000
			time_data = np.fromstring(str_frames, np.short).byteswap()
			f.close()
			 

			# Pxx is the segments x freqs array of instantaneous power, freqs is
			# the frequency vector, bins are the centers of the time bins in which
			# the power is computed, and im is the matplotlib.image.AxesImage
			# instance

			# spectrogram of file
			
			Pxx, freqs, bins, im = plt.specgram(time_data,Fs=Fs,noverlap=90,cmap=plt.cm.gist_heat)

			plt.axis('off')
			plt.savefig(data_loc + '/'+ train_folder + '/specgrams/'+ file_name.split('.')[0] + '.png', bbox_inches='tight')
			plt.close()
		except ValueError:
			print("Error in file: "+ file_name + "...\n")
Exemplo n.º 27
0
    def get_aiff_data(self, convert_rate = None, convert_width = None):
        """
        Returns a byte string representing the contents of an AIFF-C file containing the audio represented by the ``AudioData`` instance.

        If ``convert_width`` is specified and the audio samples are not ``convert_width`` bytes each, the resulting audio is converted to match.

        If ``convert_rate`` is specified and the audio sample rate is not ``convert_rate`` Hz, the resulting audio is resampled to match.

        Writing these bytes directly to a file results in a valid `AIFF-C file <https://en.wikipedia.org/wiki/Audio_Interchange_File_Format>`__.
        """
        raw_data = self.get_raw_data(convert_rate, convert_width)
        sample_rate = self.sample_rate if convert_rate is None else convert_rate
        sample_width = self.sample_width if convert_width is None else convert_width

        # the AIFF format is big-endian, so we need to covnert the little-endian raw data to big-endian
        if hasattr(audioop, "byteswap"): # ``audioop.byteswap`` was only added in Python 3.4
            raw_data = audioop.byteswap(raw_data, sample_width)
        else: # manually reverse the bytes of each sample, which is slower but works well enough as a fallback
            raw_data = raw_data[sample_width - 1::-1] + b"".join(raw_data[i + sample_width:i:-1] for i in range(sample_width - 1, len(raw_data), sample_width))

        # generate the AIFF-C file contents
        with io.BytesIO() as aiff_file:
            aiff_writer = aifc.open(aiff_file, "wb")
            try: # note that we can't use context manager, since that was only added in Python 3.4
                aiff_writer.setframerate(sample_rate)
                aiff_writer.setsampwidth(sample_width)
                aiff_writer.setnchannels(1)
                aiff_writer.writeframes(raw_data)
                aiff_data = aiff_file.getvalue()
            finally:  # make sure resources are cleaned up
                aiff_writer.close()
        return aiff_data
Exemplo n.º 28
0
def process_image(file_name, enlarge = True, image_height = 129, image_width = 23): 
	'''Retrieves time data from the aiff file and compute the spectogram for time_data'''
	'''enlarge: gives option to resize the image to new dimensions WxH by interpolation'''
	if file_name.endswith('.aiff'):
		f = aifc.open(file_name, 'r')
		str_frames = f.readframes(f.getnframes())
		Fs = f.getframerate()
		time_data = np.fromstring(str_frames, np.short).byteswap()
		f.close()
		Pxx, freqs, bins, im = plt.specgram(time_data,NFFT=256,Fs=Fs,noverlap=90,cmap=plt.cm.gist_heat)
		Pxx = Pxx[[freqs<250.]] # Right-whales call occur under 250Hz
		#print Pxx.shape
		from scipy.misc import imresize
		from sklearn import preprocessing
		
		if enlarge: #change image size
			Pxx_prep = imresize(np.log10(Pxx),(image_height,image_width), interp= 'lanczos').astype('float32')
			#Pxx_prep = imresize(Pxx,(image_height,image_width), interp= 'lanczos').astype('float32')
		else: #image size not changed
			Pxx_prep = np.log(Pxx).astype('float32')
		
		#Pxx_prep = preprocessing.MinMaxScaler().fit_transform(Pxx_prep) #rescale to 0-1
		Pxx_prep = preprocessing.StandardScaler(copy=True, with_mean=True, with_std=True).fit_transform(Pxx_prep) #rescale by std
		Pxx_ = (Pxx_prep*255.0).astype(int)
		# Returning raw values to perform operations. Used to obtain raw data for ipynb
		#Pxx_ = Pxx_prep
		#Pxx_ = Pxx
		return Pxx_
	else:
		print("Error in file: "+ file_name + "...\n")
		pass
Exemplo n.º 29
0
def open(file_name):
    name = os.path.abspath(file_name)
    if not os.path.exists(file_name):
        raise IOError("No such file or directory: '%s'" % file_name)
    _, file_ext = os.path.splitext(name)
    file_ext = file_ext[1:]

    proc_args = []
    audio_file = None

    if file_ext in ("mp4", "m4a", "m4b", "aac"):
        proc_args = [FAAD_BIN, "-q", "-f", "2", "-w", name]
    elif file_ext == "ogg":
        proc_args = [OGG_BIN, "-q", "-o", "-", name]
    elif file_ext in ("wav", "wave"):
        audio_file = wave.open(name, "r")
    elif file_ext in ("aiff", "aif"):
        audio_file = aifc.open(name, "r")
    elif file_ext in ("mp1", "mp2", "mp3"):
        proc_args = [LAME_BIN, "--quiet", "--decode", name, "-"]
    elif file_ext in ("flac", "oga"):
        proc_args = [FLAC_BIN, "--silent", "--stdout", "-d", name]
    elif file_ext == "wma":
        proc_args = [FFMPEG_BIN, "-i", name, "-f", "wav", "-"]

    if proc_args:
        proc = subprocess.Popen(proc_args, stdout=subprocess.PIPE)
        audio_file = PCMProxy(proc, name)

    return audio_file
Exemplo n.º 30
0
def load_aiff(filename):
    snd = aifc.open(filename)
    snd_string = snd.readframes(snd.getnframes())
    snd.close()
    # need to do .byteswap as aifc loads / converts to a bytestring in
    # MSB ordering, but numpy assumes LSB ordering.
    return np.fromstring(snd_string, dtype=np.uint16).byteswap()
Exemplo n.º 31
0
    def test_close(self):
        class Wrapfile(object):
            def __init__(self, file):
                self.file = open(file, 'rb')
                self.closed = False

            def close(self):
                self.file.close()
                self.closed = True

            def __getattr__(self, attr):
                return getattr(self.file, attr)

        testfile = Wrapfile(self.sndfilepath)
        f = self.f = aifc.open(testfile)
        self.assertEqual(testfile.closed, False)
        f.close()
        self.assertEqual(testfile.closed, True)
Exemplo n.º 32
0
def verify_aiff(aiffPath):
    if not os.path.exists(aiffPath):
        print("Error: aiff file does not exist.")
        return False

    try:
        a = aifc.open(aiffPath, "r")
    except aifc.Error:
        print(
            "Error: file was not a valid AIFF file.\nIf you are exporting with Audacity 2.4 or later,\nplease use an earlier version (2.3.x or earlier)\nas AIFF exporting is broken."
        )
        return False

    if a.getnchannels() > 1:
        print("Error: tool currently only supports mono audio.")
        return False

    return True
Exemplo n.º 33
0
 def test_write_params_singles(self):
     fout = aifc.open(io.BytesIO(), 'wb')
     fout.aifc()
     fout.setnchannels(1)
     fout.setsampwidth(2)
     fout.setframerate(3)
     fout.setnframes(4)
     fout.setcomptype('NONE', 'name')
     self.assertEqual(fout.getnchannels(), 1)
     self.assertEqual(fout.getsampwidth(), 2)
     self.assertEqual(fout.getframerate(), 3)
     self.assertEqual(fout.getnframes(), 0)
     self.assertEqual(fout.tell(), 0)
     self.assertEqual(fout.getcomptype(), 'NONE')
     self.assertEqual(fout.getcompname(), 'name')
     fout.writeframes('\x00' * 4 * fout.getsampwidth() * fout.getnchannels())
     self.assertEqual(fout.getnframes(), 4)
     self.assertEqual(fout.tell(), 4)
Exemplo n.º 34
0
 def arrayToWAV(self,
                np1array,
                OPfname,
                nrchans=1,
                SR=44100,
                nrReps=0,
                gapSecs=0,
                buffsize=4096,
                trace=False):
     """
     Writes npArray to fname.wav. Filename contains original DataFilename datetime-stamp.
     buffsize is size of wav write buffer. File writes are in buffsize increments.
     Write the arran nrReps number of times, with gapSec seconds between
     """
     OPfileID = aifc.open(OPfname + '.wav',
                          'wb')  # open the file and set up the header
     OPfileID.setnchannels(nrchans)  # the number of channels (1=mono)
     OPfileID.setsampwidth(2)  # the sample width in bytes(16bit fmt)
     OPfileID.setframerate(SR)  # the frame rate. for mono, FR =SR
     # scale data -1 to 1
     # scale (-1,1) the np.array, shift it 15 bits and overwrite it as int16s
     npSarray = BITS_15 * np1array  # NB can be a np.array. Doesn't have 2B
     npSarray = npSarray.astype('int16')  # cvt to 16 bit ints.
     # Use nparray.dtype say what type it is
     # to python list - has to be a better way!!!!! ##
     # try to pack it directly from the np1aray, as per pyAudioEg.py
     tmp = npSarray.tolist()
     dataString = "".join(struct.pack('>h', i)
                          for i in tmp)  # pack the array data into a buffer
     OPfileID.writeframes(dataString)  # write buffer to file
     # if the sound it to be repeated,insert a gapsSec silence b4 writing again
     if nrReps > 0:
         tmp = np.array(np.zeros(gapSecs * SR * nrchans, dtype='int16'))
         silentString = "".join(struct.pack('>h', i)
                                for i in tmp)  # pack zeros into a buff
         for i in range(nrReps):
             OPfileID.writeframes(silentString)  # write the silence buffer
             OPfileID.writeframes(
                 dataString)  # write the non-silent buffer again
     OPfileID.close()
     if trace:
         numsamps = int(len(np1array)) + (gapSecs * SR * nrchans)
         print("Wrote %s.wav, nrChans: %d, nrSamps: %d." %
               (OPfname, nrchans, numsamps))
Exemplo n.º 35
0
def open (name, fh=0):
    name = os.path.normpath(name)
    if not os.path.exists(name):
        raise IOError, (2, "No such file or directory: '%s'" % name)
    ext = os.path.splitext(name)[1][1:].lower()
    if ext in ("mp4", "m4a", "m4b", "aac"):
        if os.name=="nt": cline = [faad, "-q", "-w", name]
        else: cline = [faad, "-q", "-f", "2", "-w", name]
        po = Popen(cline, shell=0, stdout=PIPE, stdin=PIPE, stderr=PIPE, creationflags=noWindow)
        po.stdin.close(); po.stderr.close()
        po.filename = name
        wf = fakewave(po, fh)
    elif ext=="ogg":
        if os.name=="nt": cline = [oggdec, "--stdout", name]
        else: cline = [oggdec, "-q", "-o", "-", name]
        po = Popen(cline, shell=0, stdout=PIPE, stdin=PIPE, stderr=PIPE, creationflags=noWindow)
        po.stdin.close(); po.stderr.close()
        po.filename = name
        wf = fakewave(po, fh)
    elif ext in ("wav", "wave"):
        wf = wave.open(name, "r")
    elif ext in ("aiff", "aif"):
        wf = aifc.open(name, "r")
    elif ext in ("mp1", "mp2", "mp3"):
        cline = [lame, "--quiet", "--decode", name, "-"]
        po = Popen(cline, shell=0, stdout=PIPE, stdin=PIPE, stderr=PIPE, creationflags=noWindow)
        po.stdin.close(); po.stderr.close()
        po.filename = name
        wf = fakewave(po, fh)
    elif ext in ("flac", "oga"):
        cline = [flac, "--silent", "--stdout", "-d", name]
        po = Popen(cline, shell=0, stdout=PIPE, stdin=PIPE, stderr=PIPE, creationflags=noWindow)
        po.stdin.close(); po.stderr.close()
        po.filename = name
        wf = fakewave(po, fh)
    elif ext=="wma":
        if os.name=="nt": cline = [wmadec, "-w", name]
        else: cline = [ffmpeg, "-i", name, "-f", "wav", "-"]
        po = Popen(cline, shell=0, stdout=PIPE, stdin=PIPE, stderr=PIPE, creationflags=noWindow)
        po.stdin.close(); po.stderr.close()
        po.filename = name
        wf = fakewave(po, fh)
    else: wf = None
    return wf
Exemplo n.º 36
0
def readAudioFile(path):
    '''
    This function returns a numpy array that stores the audio samples of a specified WAV of AIFF file
    '''
    extension = os.path.splitext(path)[1]

    try:
        #if extension.lower() == '.wav':
            #[Fs, x] = wavfile.read(path)
        if extension.lower() == '.aif' or extension.lower() == '.aiff':
            s = aifc.open(path, 'r')
            nframes = s.getnframes()
            strsig = s.readframes(nframes)
            x = numpy.fromstring(strsig, numpy.short).byteswap()
            Fs = s.getframerate()
        elif extension.lower() == '.mp3' or extension.lower() == '.wav' or extension.lower() == '.au' or extension.lower() == '.ogg':            
            try:
                audiofile = AudioSegment.from_file(path)
            #except pydub.exceptions.CouldntDecodeError:
            except:
                print("Error: file not found or other I/O error. "
                      "(DECODING FAILED)")
                return (-1,-1)                

            if audiofile.sample_width==2:                
                data = numpy.fromstring(audiofile._data, numpy.int16)
            elif audiofile.sample_width==4:
                data = numpy.fromstring(audiofile._data, numpy.int32)
            else:
                return (-1, -1)
            Fs = audiofile.frame_rate
            x = []
            for chn in list(range(audiofile.channels)):
                x.append(data[chn::audiofile.channels])
            x = numpy.array(x)
        else:
            print("Error in readAudioFile(): Unknown file type!")
            return (-1,-1)
    except IOError: 
        print("Error: file not found or other I/O error.")
        return (-1,-1)

    print("frame rate = {}, channel = {}".format(Fs,audiofile.channels))
    return (x, Fs, audiofile.channels)
Exemplo n.º 37
0
def readAudioFile(path, **kwargs):
    '''
    This function returns a numpy array that stores the audio samples of a specified WAV of AIFF file
    '''
    extension = kwargs.get('extension', os.path.splitext(path)[1].lower())

    try:
        #if extension == '.wav':
        #[Fs, x] = wavfile.read(path)
        if extension in ['.aif', '.aiff']:
            s = aifc.open(path, 'r')
            nframes = s.getnframes()
            strsig = s.readframes(nframes)
            x = numpy.fromstring(strsig, numpy.short).byteswap()
            Fs = s.getframerate()
        else:
            try:
                audiofile = AudioSegment.from_file(path, **kwargs)
            #except pydub.exceptions.CouldntDecodeError:
            except:
                print("Error: file not found or other I/O error. "
                      "(DECODING FAILED)")
                return (-1, -1)

            if audiofile.sample_width == 2:
                data = numpy.fromstring(audiofile._data, numpy.int16)
            elif audiofile.sample_width == 4:
                data = numpy.fromstring(audiofile._data, numpy.int32)
            else:
                return (-1, -1)
            Fs = audiofile.frame_rate
            x = []
            for chn in list(range(audiofile.channels)):
                x.append(data[chn::audiofile.channels])
            x = numpy.array(x).T
    except IOError:
        print("Error: file not found or other I/O error.")
        return (-1, -1)

    if x.ndim == 2:
        if x.shape[1] == 1:
            x = x.flatten()

    return (Fs, x)
def process_image(file_name): 
    '''Retrieves time data from the aiff file and compute the spectogram for time_data'''
    
    if file_name.endswith('.aiff'):
        f = aifc.open(file_name, 'r')
        str_frames = f.readframes(f.getnframes())
        Fs = f.getframerate()
        time_data = np.fromstring(str_frames, np.short).byteswap()
        f.close()
        Pxx, freqs, bins, im = plt.specgram(time_data,Fs=Fs,noverlap=90,cmap=plt.cm.gist_heat)

        from scipy.misc import imresize
        from sklearn import preprocessing
		if enlarge :
			Pxx_prep = imresize(np.log10(Pxx),(128,128), interp= 'lanczos').astype('float32')
        else:
			Pxx_prep = np.log(Pxx).astype.('float32')
        Pxx_ = preprocessing.StandardScaler().fit_transform(Pxx_prep) #rescale by std
        return Pxx_
Exemplo n.º 39
0
def get_spec_par_halfoverlap(file):

    save_name = '../Spectrograms/spec_halfoverlap/'

    with aifc.open(file, 'r') as f:
        nframes = f.getnframes()
        strsig = f.readframes(nframes)
        data = numpy.fromstring(strsig, numpy.short).byteswap()
    nfft = 256  # Length of the windowing segments
    fs = 2
    pxx, freqs, bins, im = plt.specgram(data, NFFT=nfft, Fs=fs, noverlap=64)
    plt.axis('off')
    plt.savefig(
        save_name + file[20:-5] + '.png',
        dpi=100,  # Dots per inch
        frameon='false',
        aspect='normal',
        bbox_inches='tight',
        pad_inches=0)  # Spectrogram saved as a .png
Exemplo n.º 40
0
def test():
    import aifc
    import EasyDialogs
    fn = EasyDialogs.AskFileForOpen(message="Select an AIFF soundfile",
                                    typeList=("AIFF", ))
    if not fn: return
    af = aifc.open(fn, 'r')
    print af.getparams()
    p = Play_Audio_mac()
    p.setoutrate(af.getframerate())
    p.setsampwidth(af.getsampwidth())
    p.setnchannels(af.getnchannels())
    BUFSIZ = 10000
    while 1:
        data = af.readframes(BUFSIZ)
        if not data: break
        p.writeframes(data)
        print 'wrote', len(data), 'space', p.getfillable()
    p.wait()
def get_spec_scipy(file):
    save_name = '../Spectrograms/scipy_spect/'
    save_name = 'C:\\Users\\jorge\\Desktop\\MAI\\scipy'
    with aifc.open(file, 'r') as f:
        nframes = f.getnframes()
        strsig = f.readframes(nframes)
        data = numpy.fromstring(strsig, numpy.short).byteswap()
        f, t, sxx = signal.spectrogram(data)
        plt.pcolormesh(t, f, sxx)
    plt.axis('off')
    plt.savefig(
        save_name + file[20:-5] + '.png',
        dpi=100,  # Dots per inch
        frameon='false',
        aspect='normal',
        bbox_inches='tight',
        pad_inches=0)  # Spectrogram saved as a .png
    plt.show()
    plt.close()
Exemplo n.º 42
0
Arquivo: sndhdr.py Projeto: za/cpython
def test_aifc(h, f):
    with warnings.catch_warnings():
        warnings.simplefilter('ignore', category=DeprecationWarning)
        import aifc
    if not h.startswith(b'FORM'):
        return None
    if h[8:12] == b'AIFC':
        fmt = 'aifc'
    elif h[8:12] == b'AIFF':
        fmt = 'aiff'
    else:
        return None
    f.seek(0)
    try:
        a = aifc.open(f, 'r')
    except (EOFError, aifc.Error):
        return None
    return (fmt, a.getframerate(), a.getnchannels(), a.getnframes(),
            8 * a.getsampwidth())
Exemplo n.º 43
0
 def AIFF_to_Audio(filename):
     # when making changes, consider WAV_to_Audio as well
     import aifc
     
     with aifc.open(filename, "rb") as file:
         buffer = np.frombuffer(file.readframes(file.getnframes()),
                                [np.uint8,np.int16,None,np.int32][file.getsampwidth()-1])
         buffer = buffer.byteswap().astype(np.float64) # byte swap for AIFF only, not WAV
         
         buffer = np.reshape(buffer,
                             newshape=(file.getnchannels(),
                                       int(len(buffer)/file.getnchannels()))[::-1]).T.copy(order='C')
         buffer /= 2**(8*file.getsampwidth()-1)
         
         from gensound.audio import Audio
         audio = Audio(file.getframerate())
         audio.from_array(buffer)
         
     return audio
Exemplo n.º 44
0
def test(fn=None):
    import sys
    if sys.argv[1:]:
        fn = sys.argv[1]
    else:
        fn = 'f:just samples:just.aif'
    import aifc
    af = aifc.open(fn, 'r')
    print fn, af.getparams()
    p = AudioDev()
    p.setoutrate(af.getframerate())
    p.setsampwidth(af.getsampwidth())
    p.setnchannels(af.getnchannels())
    BUFSIZ = af.getframerate() / af.getsampwidth() / af.getnchannels()
    while 1:
        data = af.readframes(BUFSIZ)
        if not data: break
        print len(data)
        p.writeframes(data)
    p.wait()
Exemplo n.º 45
0
def main():
    decompFolder = os.path.expanduser(input("Enter decomp directory: "))
    if not verify_decomp(decompFolder): return
    
    check_if_bank_exists(decompFolder)
    
    aiffPath = os.path.expanduser(input("Enter path for the .aiff file: "))
    if not verify_aiff(aiffPath): return
    
    a = aifc.open(aiffPath, "r")
    print("\nAIFF data:\n\tSample rate: %dHZ\n\tTotal samples: %d\n\tLength: %.1f seconds\n" % (a.getframerate(), a.getnframes(), a.getnframes()/a.getframerate()))
    if (a.getframerate() > 32000):
        ans = input("Warning: sample rate (%dHZ) exceeds recommended rate of 32000HZ.\nConsider reducing sample rate to save space.\nContinue? (y/n) ")
        if ans.upper() != "Y":
            return
    
    name = input("Enter a name for the streamed audio: ")
    if not verify_name(name): return
    
    add_streamed_audio(aiffPath, name, decompFolder)
Exemplo n.º 46
0
 def __init__(self, path, speed=1, interp=2, mul=1, add=0):
     PyoObject.__init__(self, mul, add)
     self._speed = speed
     self._interp = interp
     path, speed, interp, mul, add, lmax = convertArgsToLists(path, speed, interp, mul, add)
     self._base_players = []
     self._base_objs = []
     self._snd_size, self._dur, self._snd_sr, self._snd_chnls, _format, _type = sndinfo(path[0])
     for i in range(lmax):
         try:
             sf = aifc.open(wrap(path,i))
             markerstmp = sf.getmarkers()
             sf.close()
             self._markers = [m[1] for m in markerstmp]
         except:
             self._markers = []
         self._base_players.append(SfMarkerShuffler_base(wrap(path,i), self._markers, wrap(speed,i), wrap(interp,i)))
     for i in range(lmax * self._snd_chnls):
         j = i / self._snd_chnls
         self._base_objs.append(SfMarkerShuffle_base(wrap(self._base_players,j), i % self._snd_chnls, wrap(mul,j), wrap(add,j)))
Exemplo n.º 47
0
def open_audio(file):

    _, ext = os.path.splitext(os.path.basename(file))
    ext = ext.lower()

    # if ext in (".wav", ".wave"):
    # 	import wave
    # 	return wave.open(file, "rb"), 'little', 128

    if ext in (".aiff", ".aifc", ".aif"):
        import aifc
        return aifc.open(file, "rb"), 'big', 'AIFF'

    if ext in (".au", ".snd"):
        import sunau
        return sunau.open(file, "rb"), 'big', 'SUN'

    # default
    import wave
    return wave.open(file, "rb"), 'little', 'WAVE'
Exemplo n.º 48
0
    def readAudio(self, filePath):
        fileName, fileExtension = splitext(filePath)
        self.fileExtension = fileExtension

        if self.fileExtension == '.wav':
            self.sampleRate, self.data = read(filePath)

        elif self.fileExtension == '.aif':
            file = aifc.open(filePath)
            self.sampleRate = float(file.getframerate())
            numFrames = file.getnframes()
            self.data = file.readframes(numFrames)
            file.close()

        elif self.fileExtension == '.pcm':
            rawData = np.memmap(filePath, dtype='h', mode='r')
            self.data = np.asarray(rawData)

        else:
            raise AttributeError("Invalid file type")
Exemplo n.º 49
0
 def test_read(self):
     f = self.f = aifc.open(self.sndfilepath)
     self.assertEqual(f.readframes(0), b'')
     self.assertEqual(f.tell(), 0)
     self.assertEqual(f.readframes(2), b'\x00\x00\x00\x00\x0b\xd4\x0b\xd4')
     f.rewind()
     pos0 = f.tell()
     self.assertEqual(pos0, 0)
     self.assertEqual(f.readframes(2), b'\x00\x00\x00\x00\x0b\xd4\x0b\xd4')
     pos2 = f.tell()
     self.assertEqual(pos2, 2)
     self.assertEqual(f.readframes(2), b'\x17t\x17t"\xad"\xad')
     f.setpos(pos2)
     self.assertEqual(f.readframes(2), b'\x17t\x17t"\xad"\xad')
     f.setpos(pos0)
     self.assertEqual(f.readframes(2), b'\x00\x00\x00\x00\x0b\xd4\x0b\xd4')
     with self.assertRaises(aifc.Error):
         f.setpos(-1)
     with self.assertRaises(aifc.Error):
         f.setpos(f.getnframes() + 1)
Exemplo n.º 50
0
def readAudioFile(path):
    '''
    This function returns a numpy array that stores the audio samples of a specified WAV of AIFF file
    '''
    extension = os.path.splitext(path)[1]

    try:
        # if extension.lower() == '.wav':
            #[Fs, x] = wavfile.read(path)
        if extension.lower() == '.aif' or extension.lower() == '.aiff':
            s = aifc.open(path, 'r')
            nframes = s.getnframes()
            strsig = s.readframes(nframes)
            x = numpy.fromstring(strsig, numpy.short).byteswap()
            Fs = s.getframerate()
        elif extension.lower() == '.mp3' or extension.lower() == '.wav' or extension.lower() == '.au':
            audiofile = AudioSegment.from_file(path)

            if audiofile.sample_width == 2:
                data = numpy.fromstring(audiofile._data, numpy.int16)
            elif audiofile.sample_width == 4:
                data = numpy.fromstring(audiofile._data, numpy.int32)
            else:
                return (-1, -1)
            Fs = audiofile.frame_rate
            x = []
            for chn in range(audiofile.channels):
                x.append(data[chn::audiofile.channels])
            x = numpy.array(x).T
        else:
            print("Error in readAudioFile(): Unknown file type!")
            return (-1, -1)
    except IOError as e:
        print("Error: file not found or other I/O error.", e)
        return (-1, -1)

    if x.ndim == 2:
        if x.shape[1] == 1:
            x = x.flatten()

    return (Fs, x)
Exemplo n.º 51
0
    def __init__(self, filename):
        self._fh = open(filename, 'rb')

        try:
            self._file = aifc.open(self._fh)
        except aifc.Error:
            # Return to the beginning of the file to try the WAV reader.
            self._fh.seek(0)
        else:
            self._is_aif = True
            return

        try:
            self._file = wave.open(self._fh)
        except wave.Error:
            pass
        else:
            self._is_aif = False
            return

        raise UnsupportedError()
Exemplo n.º 52
0
 def test_flac_load(self):
     r = sr.Recognizer()
     with sr.AudioFile(self.AUDIO_FILE_FLAC) as source:
         audio = r.record(source)
     self.assertIsInstance(audio, sr.AudioData)
     process = subprocess.Popen([
         sr.get_flac_converter(), "--stdout", "--totally-silent",
         "--decode", "--force-aiff-format", self.AUDIO_FILE_FLAC
     ],
                                stdout=subprocess.PIPE)
     aiff_data, _ = process.communicate()
     aiff_file = io.BytesIO(aiff_data)
     audio_reader = aifc.open(aiff_file, "rb")
     self.assertEqual(audio.sample_rate, audio_reader.getframerate())
     self.assertEqual(audio.sample_width, audio_reader.getsampwidth())
     aiff_data = audio_reader.readframes(audio_reader.getnframes())
     aiff_data_little_endian = aiff_data[1::-1] + b"".join(
         aiff_data[i + 2:i:-1] for i in range(1, len(aiff_data), 2))
     self.assertEqual(audio.get_raw_data(), aiff_data_little_endian)
     audio_reader.close()
     aiff_file.close()
Exemplo n.º 53
0
def main():
    import getopt, string
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'o:p:')
    except getopt.error:
        sys.stderr.write('Usage ' + sys.argv[0] +
                         ' [ -o outfile ] [ args ] ...\n')
        sys.exit(1)
    dev = None
    for o, a in opts:
        if o == '-o':
            import aifc
            dev = aifc.open(a, 'w')
            dev.setframerate(44100)
            dev.setsampwidth(2)
            dev.setnchannels(1)
        if o == '-p':
            mkwave(string.atoi(a))
    if not dev:
        import audiodev
        dev = audiodev.AudioDev()
        dev.setoutrate(44100)
        dev.setsampwidth(2)
        dev.setnchannels(1)
        dev.close = dev.stop
        dev.writeframesraw = dev.writeframes
    if args:
        line = string.join(args)
    else:
        line = sys.stdin.readline()
    while line:
        mline = morse(line)
        play(mline, dev)
        if hasattr(dev, 'wait'):
            dev.wait()
        if not args:
            line = sys.stdin.readline()
        else:
            line = ''
    dev.close()
Exemplo n.º 54
0
def main(args=sys.argv[1:]):
    import getopt, string
    try:
        opts, args = getopt.getopt(args, 'o:p:')
    except getopt.error:
        sys.stderr.write('Usage ' + sys.argv[0] +
                         ' [ -o outfile ] [ args ] ...\n')
        sys.exit(1)
    dev = None
    for o, a in opts:
        if o == '-o':
            import aifc
            dev = aifc.open(a, 'w')
            dev.setframerate(FRAMERATE)
            dev.setsampwidth(SAMPWIDTH)
            dev.setnchannels(1)
        if o == '-p':
            mkwave(string.atoi(a))
    if not dev:
        dev = BufferedAudioDev()
        dev.setoutrate(FRAMERATE)
        dev.setsampwidth(SAMPWIDTH)
        dev.setnchannels(1)
        dev.close = dev.stop
    if args:
        line = string.join(args)
    else:
        line = sys.stdin.readline()
    while line:
        print line
        mline = morse(line)
        print mline
        play(mline, dev)
        if hasattr(dev, 'wait'):
            dev.wait()
        if not args:
            line = sys.stdin.readline()
        else:
            line = ''
    dev.close()
Exemplo n.º 55
0
def read(file):
    """
    Read a AIFC file.
    Parameters
    ----------
    file : string or file object
        Either the name of a file or an open file pointer.
    Returns
    -------
    wav : aifcio.Aifc() instance
        The return value is an instance of the class `wavio.Wav`,
        with the following attributes:
            data : numpy array
                The array containing the data.  The shape of the array
                is (num_samples, num_channels).  num_channels is the
                number of audio channels (1 for mono, 2 for stereo).
            rate : float
                The sampling frequency (i.e. frame rate)
            sampwidth : float
                The sample width, in bytes.  E.g. for a 24 bit AIFC file,
                sampwidth is 3.
    Notes
    -----
    This function uses the `wave` module of the Python standard libary
    to read the AIFC file, so it has the same limitations as that library.
    In particular, the function does not read files with floating point data.
    The array returned by `aifcio.read` is alway two-dimensional.  If the
    AIFC data is mono, the array will have shape (num_samples, 1).
    """
    aif = _aifc.open(file)
    rate = aif.getframerate()
    nchannels = aif.getnchannels()
    sampwidth = aif.getsampwidth()
    nframes = aif.getnframes()
    data = aif.readframes(nframes)
    aif.close()
    array = _aifc2array(nchannels, sampwidth, rate, data)
    a = Aifc(data=array, rate=rate, sampwidth=sampwidth)
    #    print(a)
    return a
Exemplo n.º 56
0
def all_glyphs_in_one_aiff():
    # all tones after another
    f = CurrentFont()
    a = aifc.open("aiff_out/aiffContours.aiff", "wb")
    a.setnchannels(1)
    a.setsampwidth(4)
    a.setframerate(44100)
    m = 0
    for n in f.selection:
        g = f[n]
        flattenGlyph(g, 4)
        print g.name
        m += 1
        a.setmark(m, a.tell(), g.name)
        cDists = {}
        for i in range(len(g)):
            cList = []
            c = g[i]
            b = c.box
            if b is None:
                # ignore anchors, they have no bounding box
                break
            pCenter = ((b[0] + b[2]) / 2, (b[1] + b[3]) / 2)
            for p in c.points:
                cList.append(distance(pCenter, (p.x, p.y), doRound=True))
            cDists[i] = cList
        amps = {}
        for k, myList in cDists.iteritems():
            amps[k] = scaleList(myList, 255)
        for k, v in amps.iteritems():
            print k
            #print v
            for i in range(100):
                for myVal in v:
                    a.writeframes(pack("i", myVal))
        myVal = pack("i", 0)
        for i in range(10000):
            a.writeframes(myVal)
    a.close()
    print "Done."
Exemplo n.º 57
0
def process_image(file_name, enlarge=True, image_height=129, image_width=23):
    '''Retrieves time data from the aiff file and compute the spectogram for time_data'''
    '''enlarge: gives option to resize the image to new dimensions WxH by interpolation'''
    if file_name.endswith('.aiff'):
        f = aifc.open(file_name, 'r')
        str_frames = f.readframes(f.getnframes())
        Fs = f.getframerate()
        time_data = np.fromstring(str_frames, np.short).byteswap()
        f.close()
        Pxx, freqs, bins, im = plt.specgram(time_data,
                                            NFFT=256,
                                            Fs=Fs,
                                            noverlap=90,
                                            cmap=plt.cm.gist_heat)
        Pxx = Pxx[[freqs < 250.]]  # Right-whales call occur under 250Hz
        #print Pxx.shape
        from scipy.misc import imresize
        from sklearn import preprocessing

        if enlarge:  #change image size
            #Pxx_prep = imresize(np.log10(Pxx),(image_height,image_width), interp= 'lanczos').astype('float32')
            Pxx_prep = imresize(Pxx, (image_height, image_width),
                                interp='lanczos').astype('float32')
        else:  #image size not changed
            Pxx_prep = np.log(Pxx).astype('float32')

        #Pxx_prep = preprocessing.MinMaxScaler().fit_transform(Pxx_prep) #rescale to 0-1
        Pxx_prep = preprocessing.StandardScaler(copy=True,
                                                with_mean=True,
                                                with_std=True).fit_transform(
                                                    Pxx_prep)  #rescale by std
        Pxx_ = (Pxx_prep * 255.0).astype(int)
        # Returning raw values to perform operations. Used to obtain raw data for ipynb
        #Pxx_ = Pxx_prep
        #Pxx_ = Pxx
        return Pxx_
    else:
        print("Error in file: " + file_name + "...\n")
        pass
Exemplo n.º 58
0
    def test_params(self):
        f = self.f = aifc.open(self.sndfilepath)
        params = f.getparams()
        self.assertEqual(f.getfp().name, self.sndfilepath)
        self.assertEqual(f.getnchannels(), 2)
        self.assertEqual(f.getsampwidth(), 2)
        self.assertEqual(f.getframerate(), 48000)
        self.assertEqual(f.getnframes(), 14400)
        self.assertEqual(f.getcomptype(), b'NONE')
        self.assertEqual(f.getcompname(), b'not compressed')
        self.assertEqual(
            f.getparams(),
            (2, 2, 48000, 14400, b'NONE', b'not compressed'),
        )

        params = f.getparams()
        self.assertEqual(params.nchannels, 2)
        self.assertEqual(params.sampwidth, 2)
        self.assertEqual(params.framerate, 48000)
        self.assertEqual(params.nframes, 14400)
        self.assertEqual(params.comptype, b'NONE')
        self.assertEqual(params.compname, b'not compressed')
Exemplo n.º 59
0
def readAudioFile(path):
	'''
	This function returns a numpy array that stores the audio samples of a specified WAV of AIFF file
	'''
	extension = os.path.splitext(path)[1]

	try:
		if extension.lower() == '.wav':
			[Fs, x] = wavfile.read(path)
		elif extension.lower() == '.aif' or extension.lower() == '.aiff':
			s = aifc.open(path, 'r')
			nframes = s.getnframes()
			strsig = s.readframes(nframes)
			x = numpy.fromstring(strsig, numpy.short).byteswap()
			Fs = s.getframerate()
		else:
			print "Error in readAudioFile(): Unknown file type!"
			return (-1,-1)
	except IOError:	
		print "Error: file not found or other I/O error."
		return (-1,-1)
	return (Fs, x)
Exemplo n.º 60
0
 def makesound(fl):
     """makesound(fl) -> None
     Generate AIFF sound data for a short musical note, and write the
     AIFF to the given file.
     """
     import aifc, math
     afl = aifc.open(fl, 'wb')
     afl.setnchannels(2)
     afl.setsampwidth(2)
     afl.setframerate(22050)
     nframes = 5000
     ratio = (0.5 * math.pi / nframes)
     for ix in range(nframes):
         amp = 0.5 * (math.sin(ix * 0.10) + math.sin(ix * 0.166666))
         amp *= math.cos(ix * ratio)
         if (ix < 10):
             amp *= (ix * 0.1)
         amp = int(amp * 0x4000)
         dat = chr((amp >> 8) & 0xFF) + chr(amp & 0xFF)
         amp = amp // 10
         dat += chr((amp >> 8) & 0xFF) + chr(amp & 0xFF)
         afl.writeframes(dat)
     afl.close()