Beispiel #1
0
 def test_read_too_large_header(self):
     b = struct.pack('>LLLLLL', sunau.AUDIO_FILE_MAGIC, 124, 0,
                     sunau.AUDIO_FILE_ENCODING_LINEAR_8, 11025, 1)
     b += b'\0' * 100
     with self.assertRaisesRegex(sunau.Error,
                                 'header size ridiculously large'):
         sunau.open(io.BytesIO(b))
Beispiel #2
0
 def test_read_bad_magic_number(self):
     b = b'SPA'
     with self.assertRaises(EOFError):
         sunau.open(io.BytesIO(b))
     b = b'SPAM'
     with self.assertRaisesRegex(sunau.Error, 'bad magic number'):
         sunau.open(io.BytesIO(b))
Beispiel #3
0
def main():
    #source and destination file names
    sourceFile = "simple.au"
    destFile = "test.au"

    #opening source and dest file
    sFile = sunau.open(sourceFile, "r")
    dFile = sunau.open(destFile, "w")

    #getting parameters and data from source file
    params = sFile.getparams()
    numFrames = sFile.getnframes()

    #setting destination parametersto the same
    dFile.setparams(params)

    #setting packet size in terms of frames
    packetLen = 1000
    #setting threshold (ex 20% packet loss => threshold = 80)
    threshold = 80
    #setting playback policy (1->playing silence,
    #2->playing last sample,
    #3->replaying last packet)
    policy = 1

    #holding emptyData for policy 1
    emptyData = bytes("  " * packetLen, 'utf-8')
    #holding repeat for policy 3 and sample for policy 2
    repeat = emptyData
    sample = emptyData

    for i in range(1, numFrames + 1, packetLen):
        #randomizing packet loss
        packetLoss = random.randint(1, 101)

        #reading packet to be "received"
        packet = sFile.readframes(packetLen)

        if packetLoss < threshold:
            dFile.writeframes(packet)

        elif policy == 1:
            dFile.writeframes(emptyData)

        elif policy == 2:
            dFile.writeframes(sample)

        else:  #policy 3
            dFile.writeframes(repeat)

        #holding sample for policy 2
        sample = packet[len(packet) - 1:] * len(packet)

        #holding repeat for folicy 3
        repeat = packet

    dFile.close()
    sFile.close()
Beispiel #4
0
 def test_write_context_manager_calls_close(self):
     # Close checks for a minimum header and will raise an error
     # if it is not set, so this proves that close is called.
     with self.assertRaises(sunau.Error):
         with sunau.open(TESTFN, 'wb') as f:
             pass
     with self.assertRaises(sunau.Error):
         with open(TESTFN, 'wb') as testfile:
             with sunau.open(testfile):
                 pass
Beispiel #5
0
 def test_write_context_manager_calls_close(self):
     # Close checks for a minimum header and will raise an error
     # if it is not set, so this proves that close is called.
     with self.assertRaises(sunau.Error):
         with sunau.open(TESTFN, 'wb') as f:
             pass
     with self.assertRaises(sunau.Error):
         with open(TESTFN, 'wb') as testfile:
             with sunau.open(testfile):
                 pass
Beispiel #6
0
def simulatorZero(numFrames, filename, notLoss):
    wFile = sunau.open("(copy)" + filename, "w")
    rFile = sunau.open(filename, 'r')
    i = 0
    frames = rFile.getnframes()
    wFile.setparams(rFile.getparams())
    while i < frames:
        i += 1
        frame = rFile.readframes(numFrames)
        if (randomLoss(notLoss)):
            writeZero(wFile, numFrames)
        else:
            wFile.writeframes(frame)
Beispiel #7
0
 def test_context_manager_with_filename(self):
     # If the file doesn't get closed, this test won't fail, but it will
     # produce a resource leak warning.
     with sunau.open(TESTFN, 'wb') as f:
         f.setnchannels(nchannels)
         f.setsampwidth(sampwidth)
         f.setframerate(framerate)
     with sunau.open(TESTFN) as f:
         self.assertFalse(f.getfp().closed)
         params = f.getparams()
         self.assertEqual(params[0], nchannels)
         self.assertEqual(params[1], sampwidth)
         self.assertEqual(params[2], framerate)
     self.assertIsNone(f.getfp())
Beispiel #8
0
 def test_context_manager_with_filename(self):
     # If the file doesn't get closed, this test won't fail, but it will
     # produce a resource leak warning.
     with sunau.open(TESTFN, 'wb') as f:
         f.setnchannels(nchannels)
         f.setsampwidth(sampwidth)
         f.setframerate(framerate)
     with sunau.open(TESTFN) as f:
         self.assertFalse(f.getfp().closed)
         params = f.getparams()
         self.assertEqual(params[0], nchannels)
         self.assertEqual(params[1], sampwidth)
         self.assertEqual(params[2], framerate)
     self.assertIsNone(f.getfp())
Beispiel #9
0
def sample_zero(input_file, packet_size, loss):
    in_file = sunau.open(input_file, 'r')
    out_file = sunau.open("simulated_zero_" + input_file, 'w')
    out_file.setparams(in_file.getparams())
    i, total_frames = 1, in_file.getnframes()

    while i <= total_frames:
        f = in_file.readframes(packet_size)
        if random.randint(0, 101) >= loss:
            out_file.writeframes(f)
        else:
            out_file.writeframes(bytes("00" * packet_size, 'utf-8'))

        i += packet_size
Beispiel #10
0
def simulatorPacket(numFrames, filename, notLoss):
    wFile = sunau.open("(copy)" + filename, "w")
    rFile = sunau.open(filename, 'r')
    i = 0
    frames = rFile.getnframes()
    wFile.setparams(rFile.getparams())
    frame = ""
    while i < frames:
        i += 1
        prevframe = frame
        frame = rFile.readframes(numFrames)
        if (randomLoss(notLoss)):
            writeLastPacket(wFile, prevframe)
        else:
            wFile.writeframes(frame)
Beispiel #11
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

        # None of the three libraries could open the file.
        self._fh.close()
        raise UnsupportedError()
Beispiel #12
0
def load_au(filename):
    """
    Load .au audio file.
    
    Parameters
    ----------
    filename : path and filename of desire file from the current directory

    Returns
    -------
    singal_data : Numpy array of the audio data in int16 format
    sample_rate : Sample rate of the audio as an int 
    """
    signal_fp = sunau.open(filename, 'r')
    sample_rate = signal_fp.getframerate()
    num_frames = signal_fp.getnframes()

    signal_data = np.fromstring(signal_fp.readframes(num_frames),
                                dtype=np.dtype('>h'))  # convert data to array

    # normalization (don't want this for LDA model)
    #signal_data = signal_data.astype(float)
    #signal_data /= 32766.0

    # we should normalize each audio signal to 0dB to ensure louder
    # recordings do no have frequencies weighted more greatly

    # Also, we many want to apply loudness curves to the
    # frequency data in order to

    signal_fp.close()

    return signal_data, sample_rate
Beispiel #13
0
def open_audio(name, mode):
    try:
        file = sunau.open(name, mode)
        return file
    except sunau.Error:
        print("Error opening file")
        return None
Beispiel #14
0
 def test_context_manager_with_open_file(self):
     with open(TESTFN, 'wb') as testfile:
         with sunau.open(testfile) as f:
             f.setnchannels(nchannels)
             f.setsampwidth(sampwidth)
             f.setframerate(framerate)
         self.assertFalse(testfile.closed)
     with open(TESTFN, 'rb') as testfile:
         with sunau.open(testfile) as f:
             self.assertFalse(f.getfp().closed)
             params = f.getparams()
             self.assertEqual(params[0], nchannels)
             self.assertEqual(params[1], sampwidth)
             self.assertEqual(params[2], framerate)
         self.assertIsNone(f.getfp())
         self.assertFalse(testfile.closed)
Beispiel #15
0
def get_info(au_file, name):
    file = sunau.open("genres/" + name + "/" + au_file, 'r')
    frames = file.readframes(file.getnframes())
    sound_info = pylab.fromstring(frames, 'Int16')
    frame_rate = file.getframerate()
    file.close()
    return sound_info, frame_rate
Beispiel #16
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()
Beispiel #17
0
 def test_context_manager_with_open_file(self):
     with open(TESTFN, 'wb') as testfile:
         with sunau.open(testfile) as f:
             f.setnchannels(nchannels)
             f.setsampwidth(sampwidth)
             f.setframerate(framerate)
         self.assertFalse(testfile.closed)
     with open(TESTFN, 'rb') as testfile:
         with sunau.open(testfile) as f:
             self.assertFalse(f.getfp().closed)
             params = f.getparams()
             self.assertEqual(params[0], nchannels)
             self.assertEqual(params[1], sampwidth)
             self.assertEqual(params[2], framerate)
         self.assertIsNone(f.getfp())
         self.assertFalse(testfile.closed)
Beispiel #18
0
    def open(self, filename):
        """Get an audio from a Audio Interchange File Format file.

        :param filename: (str) input file name.

        """
        # Use the standard wave library to load the wave file
        # open method returns a Wave_read() object
        self._audio_fp = sunau.open(filename, "r")
Beispiel #19
0
    def test_lin(self):
        self.f = sunau.open(TESTFN, 'w')
        self.f.setnchannels(nchannels)
        self.f.setsampwidth(sampwidth)
        self.f.setframerate(framerate)
        self.f.setcomptype('NONE', 'not compressed')
        output = b'\xff\x00\x12\xcc' * (nframes * nchannels * sampwidth // 4)
        self.f.writeframes(output)
        self.f.close()

        self.f = sunau.open(TESTFN, 'rb')
        self.assertEqual(nchannels, self.f.getnchannels())
        self.assertEqual(sampwidth, self.f.getsampwidth())
        self.assertEqual(framerate, self.f.getframerate())
        self.assertEqual(nframes, self.f.getnframes())
        self.assertEqual('NONE', self.f.getcomptype())
        self.assertEqual(self.f.readframes(nframes), output)
        self.f.close()
Beispiel #20
0
    def __init__(self, filename):
        import wave, numpy
#        print filename
        if not len(filename) >0:
            print "Invalid wavfile name : %s"%filename
        
        elif filename[-3:] == 'raw':
            self.filename = filename[(filename.rfind('/'))+1:]
            self.filepath = filename[:(filename.rfind('/'))]
            wavfile = open(filename , 'r');

            self.filetype = filename[len(filename)-3:]
            self.nbChannel = 1 # fixed value
            self.sampleRate = 11025 # fixed value
            #self.nframes = wavfile.getnframes() # fixed value
            self.sample_width = 2 # format is signed int16
            #data = data/max([abs(min(data)) max(data)]);
            str_bytestream = wavfile.read(-1)
            self.data = numpy.fromstring(str_bytestream,'h')
            self.nframes = len(self.data)
            wavfile.close()

        elif filename[-3:] == 'wav' or filename[-3:] == 'WAV' or filename[-2:] == 'au':
            self.filename = filename[(filename.rfind('/'))+1:]
            self.filepath = filename[:(filename.rfind('/'))]
            
            if filename[-2:] == 'au':
                import sunau
                wavfile = sunau.open(str(filename) , 'r');
            else:
                wavfile = wave.open(filename, 'r')
            self.filetype = filename[len(filename)-3:]
            self.nbChannel = wavfile.getnchannels()
            self.sampleRate = wavfile.getframerate()
            self.nframes = wavfile.getnframes()
            self.sample_width = wavfile.getsampwidth()

            #self.data = array.array('h') #creates an array of ints
            str_bytestream = wavfile.readframes(self.nframes)

            #print filename,self.sampleWidth, self.nbChannel , self.sampleRate,self.nframes
#            print wavfile.getparams()

            if self.sample_width == 1:
                typeStr = 'int8'
            elif self.sample_width == 2:
                typeStr = 'int16'
            elif self.sample_width == 3:
                typeStr ='int24' # WARNING NOT SUPPORTED BY NUMPY
            elif self.sample_width == 4:
                typeStr = 'uint32'
            self.data = numpy.fromstring(str_bytestream,dtype=typeStr)

#            self.data = numpy.fromstring(str_bytestream,'h')
            wavfile.close()
        else:
            raise TypeError('Audio format not recognized')
Beispiel #21
0
    def test_lin(self):
        self.f = sunau.open(TESTFN, "w")
        self.f.setnchannels(nchannels)
        self.f.setsampwidth(sampwidth)
        self.f.setframerate(framerate)
        self.f.setcomptype("NONE", "not compressed")
        output = b"\xff\x00\x12\xcc" * (nframes * nchannels * sampwidth // 4)
        self.f.writeframes(output)
        self.f.close()

        self.f = sunau.open(TESTFN, "rb")
        self.assertEqual(nchannels, self.f.getnchannels())
        self.assertEqual(sampwidth, self.f.getsampwidth())
        self.assertEqual(framerate, self.f.getframerate())
        self.assertEqual(nframes, self.f.getnframes())
        self.assertEqual("NONE", self.f.getcomptype())
        self.assertEqual(self.f.readframes(nframes), output)
        self.f.close()
Beispiel #22
0
    def open(self, filename):
        """ Get an audio from a Audio Interchange File Format file.

        :param filename: (str) input file name.

        """
        # Use the standard wave library to load the wave file
        # open method returns a Wave_read() object
        self._audio_fp = sunau.open(filename, "r")
Beispiel #23
0
def simulatorSample(numFrames, filename, notLoss):
    wFile = sunau.open("(copy)" + filename, "w")
    rFile = sunau.open(filename, 'r')
    i = 0
    frames = rFile.getnframes()
    wFile.setparams(rFile.getparams())
    sample = ""
    while i < frames:
        i += 1
        frame = rFile.readframes(numFrames - 2)
        prevsample = sample
        sample = rFile.readframes(2)
        if (randomLoss(notLoss)):
            writeLastSample(wFile, numFrames, prevsample)

        else:
            wFile.writeframes(frame)
            wFile.writeframes(sample)
Beispiel #24
0
    def test_lin(self):
        self.f = sunau.open(TESTFN, 'w')
        self.f.setnchannels(nchannels)
        self.f.setsampwidth(sampwidth)
        self.f.setframerate(framerate)
        self.f.setcomptype('NONE', 'not compressed')
        output = b'\xff\x00\x12\xcc' * (nframes * nchannels * sampwidth // 4)
        self.f.writeframes(output)
        self.f.close()

        self.f = sunau.open(TESTFN, 'rb')
        self.assertEqual(nchannels, self.f.getnchannels())
        self.assertEqual(sampwidth, self.f.getsampwidth())
        self.assertEqual(framerate, self.f.getframerate())
        self.assertEqual(nframes, self.f.getnframes())
        self.assertEqual('NONE', self.f.getcomptype())
        self.assertEqual(self.f.readframes(nframes), output)
        self.f.close()
 def getFrames(self,normalize=False):
     'Method: Extract the data from the audio file'
     auread=sunau.open(self.filePath,'r')
     auDataUnpack=[None]*self.nFrames
     for i in range(0,self.nFrames):
         auData = auread.readframes(1)
         auDataUnpack[i] = struct.unpack(">h", auData)[0]
         if normalize:
             auDataUnpack[i]/=self.maxValue
     return auDataUnpack
Beispiel #26
0
def get_wav_info(au_file):
    auInfo = sunau.open(au_file, 'r')
    frameRate = auInfo.getframerate()
    print("frameRate: " + str(frameRate))
    data = auInfo.readframes(auInfo.getnframes())
    audio_data = np.fromstring(data, dtype=np.dtype('>h'))
    auInfo.close()
    print(audio_data)
    # rate, data = wavfile.read(wav_file)
    return frameRate, audio_data
Beispiel #27
0
def get_data(aufile_path):
    """ Opens .au file and return its frame rate and all frames """
    aufile = sunau.open(aufile_path)
    sample_rate = aufile.getframerate()

    # read in frames as byte strings
    frames = aufile.readframes(aufile.getnframes())
    frames = np.fromstring(frames, dtype=np.int16)

    return (sample_rate, frames)
Beispiel #28
0
def sample_prev_samp(input_file, packet_size, loss):
    in_file = sunau.open(input_file, 'r')
    out_file = sunau.open("simulated_prevsamp_" + input_file, 'w')

    out_file.setparams(in_file.getparams())
    i, total_frames, f = 1, in_file.getnframes(), None

    while i <= total_frames:

        f = in_file.readframes(packet_size - 3)
        prev_samp = in_file.readframes(3)

        if random.randint(0, 101) >= loss:
            out_file.writeframes(f)
            out_file.writeframes(prev_samp)
        else:
            out_file.writeframes(prev_samp * (packet_size // 3))

        i += packet_size
Beispiel #29
0
 def __init__(self, filepath):
     AudioReader.__init__(self, filepath)
     if filepath.lower().endswith(".aif") or filepath.lower().endswith(".aiff"):
         self.wf = aiff.open(self.filepath)
     elif filepath.lower().endswith('.au'):
         self.wf = sunau.open(self.filepath)
     else:
         self.wf = wave.open(self.filepath)
     self.framesread = 0
     self.frames_per_read = self.wf.getframerate() / 10
def audio_file_to_vectors(fname):
    """Split a *.au files into two equal length vectors
    """
    au = sunau.open(fname, 'r')
    f = au.readframes(au.getnframes())
    v = np.fromstring(f, dtype=np.dtype('>h'))
    v = np.float16(v)
    v = v/MAX_INT
    v = librosa.util.fix_length(v, LENGTH)
    return v[:LENGTH/2], v[LENGTH/2:]
Beispiel #31
0
    def test_ulaw(self):
        self.f = sunau.open(TESTFN, 'w')
        self.f.setnchannels(nchannels)
        self.f.setsampwidth(sampwidth)
        self.f.setframerate(framerate)
        self.f.setcomptype('ULAW', '')
        # u-law compression is lossy, therefore we can't expect non-zero data
        # to come back unchanged.
        output = b'\0' * nframes * nchannels * sampwidth
        self.f.writeframes(output)
        self.f.close()

        self.f = sunau.open(TESTFN, 'rb')
        self.assertEqual(nchannels, self.f.getnchannels())
        self.assertEqual(sampwidth, self.f.getsampwidth())
        self.assertEqual(framerate, self.f.getframerate())
        self.assertEqual(nframes, self.f.getnframes())
        self.assertEqual('ULAW', self.f.getcomptype())
        self.assertEqual(self.f.readframes(nframes), output)
        self.f.close()
Beispiel #32
0
    def test_getparams(self):
        self.f = sunau.open(TESTFN, 'w')
        self.f.setnchannels(nchannels)
        self.f.setsampwidth(sampwidth)
        self.f.setframerate(framerate)
        self.f.setcomptype('ULAW', '')
        output = b'\0' * nframes * nchannels * sampwidth
        self.f.writeframes(output)
        self.f.close()

        self.f = sunau.open(TESTFN, 'rb')
        params = self.f.getparams()
        self.assertEqual(params.nchannels, nchannels)
        self.assertEqual(params.sampwidth, sampwidth)
        self.assertEqual(params.framerate, framerate)
        self.assertEqual(params.nframes, nframes)
        self.assertEqual(params.comptype, 'ULAW')

        dump = pickle.dumps(params)
        self.assertEqual(pickle.loads(dump), params)
Beispiel #33
0
def conv(dataset):

    infiles = os.listdir("./au/" + dataset)  #get file list

    for file in infiles:
        print file

        wave_file = sunau.open("./au/" + dataset + file, "r")  #open file

        nchannles = wave_file.getnchannels()
        framerate = wave_file.getframerate()
        mfr = wave_file.getnframes()
        samplewidth = wave_file.getsampwidth()
        """
        print nchannles
        print framerate
        print mfr
        print samplewidth
        """
        """convert csv"""

        fr = 0
        oa = []
        wv = wave_file.readframes(mfr)
        data = np.frombuffer(wv, dtype="int16")

        for fr in range(mfr / red):
            X = np.fft.fft(data[fr:fr + red])
            amp = [np.sqrt(c.real**2 + c.imag**2) for c in X]
            freqList = np.fft.fftfreq(red, d=1.0 / framerate)
            fq = 0
            fqList = 0.0
            fqp = []
            print str(len(X))
            while (55 * (2**(fqList / 12))) < 1760:
                tgt = 55 * (2**(fqList / 12))
                fqp.append(int(amp[int()]) // 200000)
                fqList = fqList + 1
            oa.append(fqp)
            fr = fr + red

        print str(len(oa))

        opcsv = open(('./output/' + dataset + file).rstrip('.au') + '.txt',
                     'w')

        writer = csv.writer(opcsv, lineterminator='\n')

        writer.writerow(oa)
        opcsv.close()

        plt.clf()
        plt.plot(oa[0])
        plt.savefig(('./output/' + dataset + file).rstrip('.au') + '.png')
Beispiel #34
0
    def test_getparams(self):
        self.f = sunau.open(TESTFN, 'w')
        self.f.setnchannels(nchannels)
        self.f.setsampwidth(sampwidth)
        self.f.setframerate(framerate)
        self.f.setcomptype('ULAW', '')
        output = b'\0' * nframes * nchannels * sampwidth
        self.f.writeframes(output)
        self.f.close()

        self.f = sunau.open(TESTFN, 'rb')
        params = self.f.getparams()
        self.assertEqual(params.nchannels, nchannels)
        self.assertEqual(params.sampwidth, sampwidth)
        self.assertEqual(params.framerate, framerate)
        self.assertEqual(params.nframes, nframes)
        self.assertEqual(params.comptype, 'ULAW')

        dump = pickle.dumps(params)
        self.assertEqual(pickle.loads(dump), params)
Beispiel #35
0
    def test_ulaw(self):
        self.f = sunau.open(TESTFN, 'w')
        self.f.setnchannels(nchannels)
        self.f.setsampwidth(sampwidth)
        self.f.setframerate(framerate)
        self.f.setcomptype('ULAW', '')
        # u-law compression is lossy, therefore we can't expect non-zero data
        # to come back unchanged.
        output = b'\0' * nframes * nchannels * sampwidth
        self.f.writeframes(output)
        self.f.close()

        self.f = sunau.open(TESTFN, 'rb')
        self.assertEqual(nchannels, self.f.getnchannels())
        self.assertEqual(sampwidth, self.f.getsampwidth())
        self.assertEqual(framerate, self.f.getframerate())
        self.assertEqual(nframes, self.f.getnframes())
        self.assertEqual('ULAW', self.f.getcomptype())
        self.assertEqual(self.f.readframes(nframes), output)
        self.f.close()
Beispiel #36
0
def sample_prev_packet(input_file, packet_size, loss):
    in_file = sunau.open(input_file, 'r')
    out_file = sunau.open("simulated_prevpacket_" + input_file, 'w')

    out_file.setparams(in_file.getparams())
    i, total_frames, f = 1, in_file.getnframes(), None
    prev = None
    print('total_frames:', total_frames)
    print('packet_size:', packet_size)

    while i <= total_frames:

        if f:
            prev = f
        f = in_file.readframes(packet_size)
        if random.randint(0, 101) >= loss or not prev:
            out_file.writeframes(f)
        else:
            out_file.writeframes(prev)

        i += packet_size
def read_sound_file(path):
    with open(path, 'rb') as fp:
        au = sunau.open(fp)
        rate = au.getframerate()
        nchannels = au.getnchannels()
        encoding = au._encoding
        fp.seek(0)
        data = fp.read()
    if encoding != sunau.AUDIO_FILE_ENCODING_MULAW_8:
        raise RuntimeError('Expect .au file with 8-bit mu-law samples')
    data = audioop.ulaw2lin(data, 2)
    return data, rate, 16, nchannels
 def extractAudioInformation(self):
     'Method: Extracts useful audio information'                        
     auFile=sunau.open(self.filePath, 'r')
     self.samplingFrequency=auFile.getframerate()
     self.sampleWidth = auFile.getsampwidth()
     self.nChannels = auFile.getnchannels()
     self.nFrames=auFile.getnframes()
     self.duration = auFile.getnframes()/ auFile.getframerate()
     self.compressionType = auFile.getcomptype()
     self.compressionName = auFile.getcompname()
     self.maxValue=float(2**(self.sampleWidth*8-1)-1) #inner -1 for excluding sign bit
     auFile.close()
Beispiel #39
0
 def raw_load(self, filename, csamp):
     fl = sunau.open(filename, 'r')
     numframes = fl.getnframes()
     dat = fl.readframes(numframes)
     numchannels = fl.getnchannels()
     samplebits = fl.getsampwidth() * 8
     framerate = fl.getframerate()
     fl.close()
     params = (framerate, numframes, dat, -1, -1, numchannels, samplebits,
               1, 1)
     res = cboodle.load_sample(csamp, params)
     if (not res):
         raise SampleError('unable to load au data')
Beispiel #40
0
    def open(self, filename):
        """
        Get an audio from a Audio Interchange File Format file.

        @param filename (string) input file name.

        """

        # Use the standard wave library to load the wave file
        # open method returns a Wave_read() object
        self.audiofp = sunau.open( filename, "r")

        # Find out how many frames the frameduration second value is
        self.nbreadframes = int(self.frameduration * self.audiofp.getframerate())
Beispiel #41
0
def read_sound_file(path):
    with open(path, 'rb') as fp:
        au = sunau.open(fp)
        rate = au.getframerate()
        nchannels = au.getnchannels()
        encoding = au._encoding
        fp.seek(0)
        data = fp.read()

    if encoding != sunau.AUDIO_FILE_ENCODING_MULAW_8:
        raise RuntimeError("Expect .au file with 8-bit mu-law samples")

    # Convert the data to 16-bit signed.
    data = audioop.ulaw2lin(data, 2)
    return (data, rate, 16, nchannels)
Beispiel #42
0
def au2wav(au_file, wav_file):
    '''
        au_file: au filename
        wav_file: wave filename
        ex) au2wav('test.au', 'wav_file')
    '''
    
    au = sunau.open(au_file, 'r')
    wav = wave.open(wav_file, 'w')
 
    wav.setnchannels(au.getnchannels())
    wav.setsampwidth(au.getsampwidth())
    wav.setframerate(au.getframerate())
 
    wav.writeframes(au.readframes(au.getnframes()))
 
    wav.close()
    au.close()
Beispiel #43
0
def get_training_arrays(genre):
    for x in range(0, num_training):
        if (x < 10):
            ind_string = "0"+str(x)
        else:
            ind_string = str(x)
        filepath = data_dir + genre + "/" + genre + ".000" + ind_string + ".au"
        song = sunau.open(filepath, 'r')
        amp_string = song.readframes(660000)
        amp_array = np.fromstring(amp_string, dtype=np.dtype('>h'))
        #print("amplitude array (hopefully): ",amp_array.shape)
        if (x==0):
            training_array = amp_array
        else:
            training_array = np.vstack([training_array, amp_array])

    print(genre + "'s arrays are",training_array)
    return training_array
Beispiel #44
0
def get_validation_arrays(genre):
    for x in range(num_training, (num_training+num_validation)):
        if (x < 10):
            ind_string = "0"+str(x)
        else:
            ind_string = str(x)
        filepath = data_dir + genre + "/" + genre + ".000" + ind_string + ".au"
        song = sunau.open(filepath, 'r')
        amp_string = song.readframes(660000)
        amp_array = np.fromstring(amp_string, dtype=np.dtype('>h'))
        song.close()
        #print("amplitude array (hopefully):\n\t",amp_array)
        if (x==num_training):
            validation_array = amp_array
        else:
            validation_array = np.vstack([validation_array, amp_array])

    print(genre + "'s arrays are",validation_array)
    return validation_array
Beispiel #45
0
 def raw_load(self, filename, csamp):
     if (isinstance(filename, boopak.pinfo.File)):
         afl = filename.open(True)
     else:
         afl = open(filename, 'rb')
     try:
         fl = sunau.open(afl, 'r')
         numframes = fl.getnframes()
         dat = fl.readframes(numframes)
         numchannels = fl.getnchannels()
         samplebits = fl.getsampwidth()*8
         framerate = fl.getframerate()
         fl.close()
     finally:
         afl.close()
         
     params = (framerate, numframes, dat, -1, -1, numchannels, samplebits, 1, 1)
     res = cboodle.load_sample(csamp, params)
     if (not res):
         raise SampleError('unable to load au data')
Beispiel #46
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'
Beispiel #47
0
def conv(dataset):
    
    infiles = os.listdir("./au/"+dataset) #get file list
    
    for file in infiles:
        print file
        
        wave_file = sunau.open("./au/"+dataset+file,"r") #open file
        
        nchannles = wave_file.getnchannels()
        framerate = wave_file.getframerate()
        mfr = wave_file.getnframes()
        samplewidth = wave_file.getsampwidth()
        """
        print nchannles
        print framerate
        print mfr
        print samplewidth
        """
        
        """convert csv"""
        red = 200
        fr = 0
        oa=[]
        wv = wave_file.readframes(mfr)
        data = np.frombuffer(wv, dtype = "int16")
        
        for fr in range(mfr/red):
            X = np.fft.fft(data[fr:fr+red])
            amp = [np.sqrt(c.real ** 2 + c.imag ** 2) for c in X]
            freqList = np.fft.fftfreq(red, d=1.0/framerate)
            fq = 0
            fqList = 0.0
            fqp = []
            print str(len(X))
            while (55*(2**(fqList/12))) < 1760:
        writer.writerow(oa)
                fqp.append(int( amp[ int(  ) ] )//200000)
                fqList = fqList+1
            oa.append(fqp)
            fr = fr+red
Beispiel #48
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 next reader.
            self._fh.seek(0)
        else:
            self._needs_byteswap = True
            self._check()
            return

        try:
            self._file = wave.open(self._fh)
        except wave.Error:
            self._fh.seek(0)
            pass
        else:
            self._needs_byteswap = False
            self._check()
            return

        try:
            self._file = sunau.open(self._fh)
        except sunau.Error:
            self._fh.seek(0)
            pass
        else:
            self._needs_byteswap = True
            self._check()
            return

        # None of the three libraries could open the file.
        self._fh.close()
        raise UnsupportedError()
Beispiel #49
0
from datetime import datetime
import shutil
import sqlite3

inputdir = "."
outputdir = "../tmp/"

conn = sqlite3.connect(outputdir+"recordings.db")
c = conn.cursor()
try:
    c.execute('create table rec (freq text, name text, time text, filename text);')
    c.execute('create index f_idx on rec(freq);')
    c.execute('create index n_idx on rec(name);')
except sqlite3.OperationalError:
    pass

for root, dirs, files in os.walk(inputdir):
    for filename in fnmatch.filter(files, "*.AU"):
        objname = os.path.join(root, filename)
        f = sunau.open(objname, 'r')
        M =  f.getmetadata()
        f.close()
        # generate a new unique filename; a uuid based on the recording's time
        t = int(mktime(M['datetime'].timetuple()))      # time in epochseconds -> rec.time
        newf = str(uuidT(t)) + ".au"                    # new file name -> rec.filename
        print objname, "->", outputdir+newf
        c.execute('insert into rec values(?,?,?,?);', (M['freq'], M['alpha tag'], t, newf) )
        shutil.move(objname, outputdir+newf)
    conn.commit()

Beispiel #50
0
import sunau

w = sunau.open("samples/sample.au", "r")

if w.getnchannels() == 1:
    print "mono,",
else:
    print "stereo,",

print w.getsampwidth()*8, "bits,",
print w.getframerate(), "Hz sampling rate"

## mono, 16 bits, 8012 Hz sampling rate
Beispiel #51
0
import matplotlib.pyplot as plt
import numpy as np
import sunau
import sys
import matplotlib as mpl
import wave
from scipy.io.wavfile import read
from scikits.audiolab import auread

#mpl.rcParams['agg.path.chunksize']= 20000

au = sunau.open('blues.00002.au','r')

ausignal = au.readframes(-1)
ausignal = np.fromstring(ausignal, 'Int16')

scausignal, scaufs, enc = auread('./blues.00002.au')

aufs = au.getframerate()
auTime=np.linspace(0, len(ausignal)/aufs, num=len(ausignal))

scauTime = np.linspace(0, len(scausignal)/scaufs, num=len(scausignal))

plt.subplot(3,1,1)
plt.plot(auTime,ausignal)
plt.xlabel('AU file with SUNAU module')

plt.subplot(3,1,2)
plt.plot(scauTime,scausignal)
plt.xlabel('AU file with SCIKITS AU module')
'''
sunau 模块

sunau 模块用于读写 Sun AU 音频文件. 
'''
import sunau

w = sunau.open('samples/sample.au', 'r')

if w.getnchannels() == 1:
	print("mono,",)
else:
	print("stereo,",)
	print(w.getsampwidth()*8, "bits,",)
	print(w.getframerate(), "Hz sampling rate")






Beispiel #53
0
import sunau
import math
import audioop
import time
import random

#initializing global variables
nframes=0;
w = sunau.open("soundfiles/whatYouFeel.au", "r")

J = []
J.append(sunau.open("soundfiles/whatYouFeel0a.au","w"))
J.append(sunau.open("soundfiles/whatYouFeel0b.au","w"))
J.append(sunau.open("soundfiles/whatYouFeel0c.au","w"))
J.append(sunau.open("soundfiles/whatYouFeel0d.au","w"))
J.append(sunau.open("soundfiles/whatYouFeel0e.au","w"))
J.append(sunau.open("soundfiles/whatYouFeel0f.au","w"))
J.append(sunau.open("soundfiles/whatYouFeel0g.au","w"))

K = []
K.append(sunau.open("soundfiles/whatYouFeel1a.au","w"))
K.append(sunau.open("soundfiles/whatYouFeel1b.au","w"))
K.append(sunau.open("soundfiles/whatYouFeel1c.au","w"))
K.append(sunau.open("soundfiles/whatYouFeel1d.au","w"))
K.append(sunau.open("soundfiles/whatYouFeel1e.au","w"))
K.append(sunau.open("soundfiles/whatYouFeel1f.au","w"))
K.append(sunau.open("soundfiles/whatYouFeel1g.au","w"))


k= sunau.open("soundfiles/whatYouFeel1.au","w")
currentIndex = 0;