我是 iphone 新手。我正在开发音频播放器,因为在音频播放器中单击播放按钮时会涉及计时器我写了这段代码
- (IBAction)playButtonClicked:(id)sender {
bookTitleString=[[selectBook titleLabel]text];
startChapterString =[[startChapter titleLabel]text];
NSString *string = [[NSBundle mainBundle]pathForResource:startChapterString ofType:@"mp3" inDirectory:bookTitleString];
NSLog(@"string is %@",string);
NSURL *url = [NSURL fileURLWithPath:string isDirectory:YES];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
AVURLAsset *audioAsset = [AVURLAsset assetWithURL:url];
CMTime audioDuration = audioAsset.duration;
audioDurationInSeconds = CMTimeGetSeconds(audioDuration);
NSLog(@"audioDurationInSeconds is %f",audioDurationInSeconds);
slider.userInteractionEnabled= YES;
slider.minimumValue = 0.0;
slider.maximumValue = audioDurationInSeconds;
slider.value = 0.0;
slider.continuous = YES;
audioPlayer.delegate = self;
if(audioPlayer == nil){
NSLog(@"audio player is nil");
}
else
{
NSLog(@"audio player is not nil");
NSLog(@"audioplayer.deviceCurrentTime is %f",audioPlayer.deviceCurrentTime);
[audioPlayer play];
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(sliderTintChanged:) userInfo:nil repeats:YES];
}
}
在上面我将一个计时器作为一个类变量
完成歌曲播放后转到 AVAudioPlayerDelegate 即 audioPlayerDidFinishPlaying:(AVAudioPlayer *)player 成功:(BOOL)flag
这里是这个 audioPlayerDidFinishPlaying 的代码
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
[timer invalidate];
NSLog(@"song finished playing");
NSString *startSongNumber = [[startChapter titleLabel]text];
NSLog(@"startSongNumber is %@",startSongNumber);
int songNumber = [startSongNumber intValue];
NSLog(@"songNumber is %d",songNumber);
songNumber = songNumber+1;
NSLog(@"songNumber is %d",songNumber);
NSString *nextSongNumber = [NSString stringWithFormat:@"%d",songNumber];
NSLog(@"next song number is %@",nextSongNumber);
NSString *string = [[NSBundle mainBundle]pathForResource:nextSongNumber ofType:@"mp3" inDirectory:bookTitleString];
NSLog(@"string is in playerdidfinish is %@",string);
NSURL *url = [NSURL fileURLWithPath:string isDirectory:YES];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
AVURLAsset *audioAsset = [AVURLAsset assetWithURL:url];
CMTime audioDuration = audioAsset.duration;
audioDurationInSeconds = CMTimeGetSeconds(audioDuration);
NSLog(@"audioDurationInSeconds is %f",audioDurationInSeconds);
[audioPlayer play];
}
在上面开始时,我使计时器无效,然后获取下一首歌曲路径并开始播放,但我不知道如何启动在上述方法中停止的计时器
如果有人知道这一点,请帮助我..