簡體   English   中英

如何在 iPhone 中將樣本數組保存為音頻文件?

[英]How can I save array of samples as audio file in iPhone?

我有一個聲音作為樣本數組。 如何將其保存為音頻文件?

我檢查了 iPhone Core Audio API。 而且我了解如何從麥克風錄制和播放音樂。 但我找不到如何做到這一點。

這是一段對我有用的代碼。 有關更多信息,您應該查看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];           

}

如果您下載http://www.dspdimension.com/technology-licensing/dirac2/的免費版本,您將在示例源代碼中找到用於讀取和寫入音頻文件的函數,我不記得是什么格式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM