如何在iPhone中将样本数组保存为音频文件?

时间:2011-06-07 02:44:59

标签: iphone objective-c core-audio

我的声音是一系列样本。 如何将其保存为音频文件?

我检查过iPhone Core Audio API。 我知道如何从麦克风录制和播放音乐。 但我找不到怎么做。

2 个答案:

答案 0 :(得分:4)

这是一段适合我的代码。有关更多信息,请查看 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];           

}

答案 1 :(得分:0)

如果您下载http://www.dspdimension.com/technology-licensing/dirac2/的免费版本,您会在示例源代码函数中找到读取和写入音频文件的内容,我不记得是什么格式。