hamel@448: #!/usr/bin/env python hamel@448: # hamel@448: # audio_example.py hamel@448: # hamel@448: # hamel@448: # Created by Philippe Hamel (hamel.phil@gmail.com) on 11-01-05. hamel@448: # hamel@448: # methods to read and write aimc data files hamel@448: hamel@448: from struct import * hamel@448: import numpy as N hamel@448: hamel@448: #int_size = calcsize('i') hamel@448: #float_size = calcsize('d') hamel@448: hamel@448: def readbin(type,file) : hamel@448: """ hamel@448: used to read binary data from a file hamel@448: """ hamel@448: return unpack(type,file.read(calcsize(type))) hamel@448: hamel@448: def read_aimc_data(filename): hamel@448: file = open(filename,'rb') hamel@448: hamel@448: nFrames = readbin('i',file)[0] hamel@448: period = readbin( 'f', file)[0] # Frame period in ms hamel@448: nChannels = readbin( 'i', file)[0] # vertical axis of an AI hamel@448: nSamples = readbin( 'i', file)[0] # horizontal axis of an AI hamel@448: sample_rate = readbin('f', file)[0] # sample rate of each channel in Hz hamel@448: hamel@448: print 'nFrames, period, nChannels, nSamples, sample_rate' hamel@448: print nFrames, period, nChannels, nSamples, sample_rate hamel@448: hamel@448: nData = nFrames * nChannels * nSamples hamel@448: print nData hamel@448: vec_data = readbin('%if'%nData,file) hamel@448: hamel@448: file.close() hamel@448: data = N.reshape(vec_data,(nFrames, nChannels, nSamples)) hamel@448: return data, nFrames, period, nChannels, nSamples, sample_rate hamel@448: hamel@450: def write_aimc_data(filename, data, sample_rate, period = 0.0): hamel@450: hamel@450: nFrames, nChannels, nSamples = data.shape hamel@450: hamel@450: file = open(filename,'wb') hamel@450: hamel@450: file.write(pack('i',nFrames)) hamel@450: file.write(pack('f',period)) #Not correctly implemented yet hamel@450: file.write(pack('i',nChannels)) hamel@450: file.write(pack('i',nSamples)) hamel@450: file.write(pack('f',sample_rate)) hamel@450: hamel@450: vec_data = data.flatten() hamel@450: for elem in vec_data: hamel@450: file.write(pack('f',elem)) hamel@450: hamel@451: file.close() hamel@450: