2011-06-07 18 views
2

我有一个样本数组的声音。 如何将其保存为音频文件?如何将样品阵列保存为iPhone中的音频文件?

我检查过iPhone核心音频API。 我知道如何从麦克风录音和播放音乐。 但我找不到如何做到这一点。

+0

你从哪里得到样品? – Anurag 2011-06-07 03:18:59

+0

哦,我自己做的。好吧,我用“采样”这个词作为信号序列。抱歉让你困惑。 – akira108 2011-06-07 04:31:31

回答

4

这是一段代码,适合我。对于任何更多的信息,你应该看看这本书核心音频粗切割

#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];   

} 
+0

酷,thanx很多! – headkit 2012-03-02 09:14:17

相关问题