如何使用AVAudioPlayer在iPhone sdk中暂停和恢复相同的歌曲

时间:2011-04-05 09:23:18

标签: iphone objective-c avaudioplayer

我想暂停这首歌,并使用程序化的盟友在iphone中持续这段时间。当我试图暂停这首歌时,我又想开始播放我暂停的歌曲。它是如何编码的。是否有任何直接属性或建议任何代码可以解决我的问题。

-(void)playMusic
{
    path=[[NSBundle mainBundle]pathForResource:@"01my song here" ofType:@"mp3"];
    AVAudioPlayer *myAudio=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:path ] error:nil];
    self.audioPlayer=myAudio;
    [myAudio release];
    //audioPlayer.playing ;
    [audioPlayer play];
}

-(void)stopMusic
{
    [audioPlayer stop];
}
-(void)pauseMusic
{
    [audioPlayer pause];// here it is just stopping, how can I start where I sttoped.
}

谢谢你, Madan Mohan。

1 个答案:

答案 0 :(得分:4)

if(!player){


    NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
    resourcePath = [resourcePath stringByAppendingString:@"/grabbag.m4a"];
    NSLog(@"Path to play: %@", resourcePath);
    NSError* err;

    //Initialize our player pointing to the path to our resource
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:resourcePath] error:&err];

    if( err ){
        //bail!
        NSLog(@"Failed with reason: %@", [err localizedDescription]);
    }
    else{
        //set our delegate, flip the button and let the magic happen
        player.delegate = self;
        [self flipButton:YES];
        [player play];
    }
}
else{
    //If the player exists here, then we're already playing.
    NSLog(@"Resuming playback!");
    [player play];
    [self flipButton:YES];
}