I have a sound as array of samples. How can I save this as audio file?
I have examined iPhone开发者_如何学C Core Audio APIs. And I understand how to record from mic and play music. But I can't find how to do that.
Here is a piece of code that works for me. For any more information you should check out the book Core Audio Rough Cuts.
#include "WavGenerator.h"
#import <Foundation/Foundation.h>
#import <AudioToolbox/AudioToolbox.h>
#include "AudioController.h"
#define SAMPLE_RATE 44100
#define DURATION 5.0
#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
// #define FILENAME @"newFile.caf"
extern unsigned int global_size_of_instrumental;
extern unsigned int global_size_output;
void createNewWAV (const char *location, int *sample_array){
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *filePath = NSTemporaryDirectory();
filePath = [filePath stringByAppendingPathComponent:@"name_of_your_file.wav"];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
AudioStreamBasicDescription asbd;
memset(&asbd,0, sizeof(asbd));
asbd.mSampleRate = SAMPLE_RATE;
asbd.mFormatID = kAudioFormatLinearPCM;
asbd.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
// asbd.mFormatFlags = kAudioFormatFlagIsBigEndian;
asbd.mBitsPerChannel = 16;
asbd.mChannelsPerFrame = 1;
asbd.mFramesPerPacket = 1;
asbd.mBytesPerFrame = 2;
asbd.mBytesPerPacket = 2;
AudioFileID audioFile;
OSStatus audioErr = noErr;
audioErr = AudioFileCreateWithURL((CFURLRef)fileURL,
kAudioFileWAVEType,
&asbd,
kAudioFileFlags_EraseFile,
&audioFile);
assert (audioErr == noErr);
printf("WAV GENERATOR --- global_size_output %d \n", global_size_output);
int size_of_output = global_size_output;
SInt16 *the_samples = (SInt16 *) malloc(global_size_of_instrumental*size_of_output*sizeof(SInt16));
for (int i=0; i< global_size_of_instrumental*size_of_output; i++)
{
the_samples[i] = sample_array[i];
}
UInt32 numSamples = global_size_of_instrumental*size_of_output;
UInt32 bytesToWrite = numSamples;
audioErr = AudioFileWriteBytes(audioFile, false, 0, &bytesToWrite, the_samples);
audioErr = AudioFileClose(audioFile);
assert(audioErr == noErr);
[pool drain];
}
If you download the free version of http://www.dspdimension.com/technology-licensing/dirac2/ you will find in the sample sourcecode functions for reading and writing audio files, I can't remember what format tho.
精彩评论