在iPhone中创建虚拟音频文件



我想以编程方式创建并保存到磁盘上一个虚拟音频文件,以便在涉及AVAudioPlayer的单元测试中使用。

在iOS中最简单的方法是什么?

您可以使用AVAudioRecord记录一些随机噪声,持续一段时间。

或者,您可以使用以下链接中给出的详细信息从头创建一个波文件:http://www.iphonedevsdk.com/forum/iphone-sdk-development/45613-creating-audio-programmatically.html

编辑:链接已失效。试试这个https://web.archive.org/web/20120701191443/http://www.iphonedevsdk.com/forum/iphone-sdk-development/45613-creating-audio-programmatically.html

NSString *path = [[NSBundle mainBundle] pathForResource:@"WavHeader" ofType:@"wav"];

NSMutableData *audioData = [[NSMutableData alloc] initWithContentsOfFile:path];

int samples = 22050;

uint8_t dataToRecord(样本),

int x;

for(x = 0;x & lt;样品;x + +) {

// populate the "dataToRecord" array with audio data. //
    

}

[audioData appendBytes:(const void *)dataToRecord length:samples];

// Get path to documents folder and set a file name  //

[audioData writeToFile:pathToFile atomically:YES];

一位同事提出了另一种解决方案:使用audacity创建尽可能小的音频文件,获取其字节,并将其复制到代码中。

结果如下:

const char bytes[] = {0x52, 0x49, 0x46, 0x46, 0x26, 0x0, 0x0, 0x0, 0x57, 0x41, 0x56, 0x45, 0x66, 0x6d, 0x74, 0x20, 0x10, 0x0, 0x0, 0x0, 0x1, 0x0, 0x1, 0x0, 0x44, 0xac, 0x0, 0x0, 0x88, 0x58, 0x1, 0x0, 0x2, 0x0, 0x10, 0x0, 0x64, 0x61, 0x74, 0x61, 0x2, 0x0, 0x0, 0x0, 0xfc, 0xff};
NSData* data = [NSData dataWithBytes:bytes length:sizeof(bytes)];
NSString* filePath = [path_ stringByAppendingPathComponent:@"test.wav"];
[data writeToFile:filePath atomically:YES];
audioURL_ = [NSURL fileURLWithPath:filePath];

最新更新