Thursday, August 18, 2011

Read audio data from a file on iPhone

// define an ID for the audio data to be read from the file
AudioFileID audioFile;
// define error varaible
OSStatus theErr = noErr;
UInt64 fileDataSize = 0;
// in order to read how many bytes there are in the audio file we need to define
//
AudioStreamBasicDescription type data structure
AudioStreamBasicDescription theFileFormat;
UInt32 thePropertySize = sizeof( theFileFormat );
// read data from the file : see previous post for "
recordedTmpFile"
theErr = AudioFileOpenURL((CFURLRef)recordedTmpFile, kAudioFileReadPermission, 0, &audioFile);
thePropertySize = sizeof( fileDataSize );
// read byte count
theErr = AudioFileGetProperty(audioFile, kAudioFilePropertyAudioDataByteCount, &thePropertySize, &fileDataSize);

/* read data into buffer */
UInt32 dataSize = fileDataSize;
void* theData = malloc(dataSize);
if (theData) {
// the data is being read into a single buffer: theData, as a byte array
AudioFileReadBytes(audioFile, false, 0, &dataSize, theData);
}
// we know that each sample is 2 bytes or 16 bits long and non-floats, so read
// the byte-array as 16bits integer array
SInt16* dataAs16bitsInt = (SInt16*) theData;

// save the data into "data.txt" file inside of the Documents directory
NSMutableString *filePath = [ [NSMutableString alloc] init];
[filePath setString: NSHomeDirectory()];
[filePath appendString: @"/Documents/data.txt"];
NSFileManager* fileManager;
NSFileHandle* fileHandle;
fileManager = [[NSFileManager defaultManager] retain];
[fileManager createFileAtPath:filePath contents:nil attributes:nil];
fileHandle = [[NSFileHandle fileHandleForWritingAtPath:filePath] retain];
if (!fileHandle) {
NSLog(@"ERROR: file handle is nil");
}

NSLog(@"Data size = %d", dataSize);
for (int i = 0; i < dataSize/2; i++) {
// save each sample as 16bits integer in the data.txt file
NSString *stringBuffer = [ NSString stringWithFormat: @"%d\n", dataAs16bitsInt[i]];
[ fileHandle writeData:[stringBuffer dataUsingEncoding:NSASCIIStringEncoding] ];
//NSLog(@"%d", dataAs32bitInt[i]);
}

No comments:

Post a Comment