2011-06-07 14 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

相關問題