2012-02-21 59 views
4

自从很久以来,我一直在挠头,但没有得到解决。我还没有找到一个音频编辑的例子!我想在原始音频文件的某个位置插入新的音频文件,将其保存为新的转换后的音频文件。iPhone:用于编辑的音频文件的NSData表示

为此我写了下面的代码。我从here得到了这个想法。

NSString *file1 = [[NSBundle mainBundle] pathForResource:@"file1" ofType:@"caf"]; // Using PCM format 
NSString *file2 = [[NSBundle mainBundle] pathForResource:@"file2" ofType:@"caf"]; 

NSData *file1Data = [[NSData alloc] initWithContentsOfFile:file1]; 
NSData *file2Data = [[NSData alloc] initWithContentsOfFile:file2]; 

NSMutableData *mergedData =[[NSMutableData alloc] initWithCapacity:([file1Data length] + [file2Data length])]; 

// First chunk from original sound file 
NSRange firstChunk; 
firstChunk.length = startingPosition; 
firstChunk.location = 0; 
[mergedData appendData:[file1Data subdataWithRange:firstChunk]]; 

// Add new sound 
[mergedData appendData:file2Data]; 

// First chunk from original sound file 
NSRange secondChunk; 
secondChunk.length = [file1Data length] - startingPosition; 
secondChunk.location = startingPosition; 
[mergedData appendData:[file1Data subdataWithRange:secondChunk]]; 

NSLog(@"File1: %d, File2: %d, Merged: %d", [file2Data length], [file2Data length], [mergedData length]); 

// Convert mergedData to Audio file 
[mergedData writeToFile:[self filePath:@"converted.caf"] atomically:YES]; 

[file1Data release]; 
[file2Data release]; 
[mergedData release]; 

使用下面的代码来播放转换的声音文件:

AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] 
          initWithContentsOfURL:[NSURL URLWithString:[self filePath:@"converted.caf"]] error:nil]; 
[audioPlayer prepareToPlay]; 
[audioPlayerr play]; 

转换后的文件无法播放。进一步研究这个我发现,转换声音NSData截断声音头/页脚。是对的吗?任何人都可以请帮我解决这个问题。

谢谢。

回答

3

我认为你最好的选择是使用ExtAudioFileRef将每个文件的音频采样提取到缓冲区中。

然后,您可以自由地将样本混合到您喜欢的任何位置,并使用ExtAudioFileWriteAsync将新混合文件保存到磁盘。

例如: 提取声音1到缓冲液A 提取声音2到缓冲B.

创建的缓冲液C的大小为A的长度加上B的长度。 然后使用ExtAudioFileWriteAsync将该缓冲区以任何格式写入磁盘。

该文件应该可以由AVAudioPlayer播放。

+1

谢谢。这对我有效。从http://www.modejong.com/iOS/#ex4获得样本 - 使用ExtendedAudioFile API读取/写入CAF文件 – applefreak 2012-02-22 11:35:52