其實就是把MP3檔案轉成NSData,然後再進行拼合。
- (void)viewDidLoad{ [super viewDidLoad];// Do any additional setup after loading the view, typically from a nib. //音頻檔案路徑 NSString *mp3Path1 = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp3"]; NSString *mp3Path2 = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"mp3"]; NSString *mp3Path3 = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"mp3"]; //音頻資料 NSData *sound1Data = [[NSData alloc] initWithContentsOfFile: mp3Path1]; NSData *sound2Data = [[NSData alloc] initWithContentsOfFile: mp3Path2]; NSData *sound3Data = [[NSData alloc] initWithContentsOfFile: mp3Path3]; //合并音頻 NSMutableData *sounds = [NSMutableData alloc]; [sounds appendData:sound1Data]; [sounds appendData:sound2Data]; [sounds appendData:sound3Data]; //儲存音頻 NSLog(@"data length:%d", [sounds length]); [sounds writeToFile:[self filePathWithName:@"tmp.mp3"] atomically:YES]; player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[self filePathWithName:@"tmp.mp3"]] error:nil]; player.delegate = self; [player prepareToPlay];}- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{ MPMusicPlayerController *ipodPlayer = [MPMusicPlayerController iPodMusicPlayer]; if ([ipodPlayer playbackState] == MPMusicPlaybackStateInterrupted) { [ipodPlayer play]; }}- (void)didReceiveMemoryWarning{ [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}- (NSString *)filePathWithName:(NSString *)filename{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; return [documentsDirectory stringByAppendingPathComponent:filename];}- (IBAction)buttonClick:(id)sender { [player play]; }