IOS拼接MP3,歌曲文件合成。

来源:互联网 发布:淘宝的来历,知乎 编辑:程序博客网 时间:2024/04/30 14:04

其实就是把MP3文件转成NSData,然后再进行拼合。

[cpp] view plaincopy
  1. - (void)viewDidLoad  
  2. {  
  3.     [super viewDidLoad];  
  4.     // Do any additional setup after loading the view, typically from a nib.  
  5.       
  6.     //音频文件路径  
  7.     NSString *mp3Path1 = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp3"];  
  8.     NSString *mp3Path2 = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"mp3"];  
  9.     NSString *mp3Path3 = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"mp3"];  
  10.     //音频数据  
  11.     NSData *sound1Data = [[NSData alloc] initWithContentsOfFile: mp3Path1];  
  12.     NSData *sound2Data = [[NSData alloc] initWithContentsOfFile: mp3Path2];  
  13.     NSData *sound3Data = [[NSData alloc] initWithContentsOfFile: mp3Path3];  
  14.       
  15.     //合并音频  
  16.     NSMutableData *sounds = [NSMutableData alloc];  
  17.     [sounds appendData:sound1Data];  
  18.     [sounds appendData:sound2Data];  
  19.     [sounds appendData:sound3Data];  
  20.     //保存音频  
  21.       
  22.     NSLog(@"data length:%d", [sounds length]);  
  23.       
  24.     [sounds writeToFile:[self filePathWithName:@"tmp.mp3"] atomically:YES];  
  25.       
  26.       
  27.     player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[self filePathWithName:@"tmp.mp3"]] error:nil];  
  28.     player.delegate = self;  
  29.     [player prepareToPlay];  
  30. }  
  31.   
  32. - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag  
  33. {  
  34.     MPMusicPlayerController *ipodPlayer = [MPMusicPlayerController iPodMusicPlayer];  
  35.     if ([ipodPlayer playbackState] == MPMusicPlaybackStateInterrupted) {  
  36.         [ipodPlayer play];  
  37.     }  
  38. }  
  39.   
  40. - (void)didReceiveMemoryWarning  
  41. {  
  42.     [super didReceiveMemoryWarning];  
  43.     // Dispose of any resources that can be recreated.  
  44. }  
  45.   
  46. - (NSString *)filePathWithName:(NSString *)filename  
  47. {  
  48.     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
  49.     NSString *documentsDirectory = [paths objectAtIndex:0];  
  50.     return [documentsDirectory stringByAppendingPathComponent:filename];  
  51. }  
  52.   
  53.   
  54. - (IBAction)buttonClick:(id)sender {  
  55.       
  56.       
  57.     [player play];  
  58.       
  59. }  
0 0