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

来源:互联网 发布:js原生打开新页面 编辑:程序博客网 时间:2024/06/09 14:44

其实就是把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];    }


原创粉丝点击