0
我正在使用AVAudioPlayer类播放音频。我已经实现了一个随着音乐播放而进步的定时器滑块。如何在iOS中暂停音频及其定时器滑块?
这里是我的代码:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
AudioBool = YES;
}
- (IBAction)play:(id)sender
{
// Code to read the file from resource folder and sets it in the AVAudioPlayer
// Sets the audio timer in 1 sec intervals
sliderTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
// Sets the slider maximum value
slider.maximumValue = player.duration;
// Sets the valueChanged target
[slider addTarget:self action:@selector(sliderChanged :) forControlEvents : UIControlEventValueChanged];
// Play the audio
// [player prepareToPlay];
[player play];
if(AudioBool == YES)
{
[player play];
AudioBool = NO;
}
else
{
[player pause];
AudioBool = YES;
}
}
- (void)updateTime
{
// Updates the slider about the music time
slider.value = player.currentTime;
NSString *time = [self timeFormatted:slider.value];
self.timerLabe.text = time;
}
- (NSString *)timeFormatted:(int)totalSeconds
{
int seconds = totalSeconds % 60;
int minutes = (totalSeconds/60) % 60;
//int hours = totalSeconds/3600;
//return [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds];
return [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
}
- (IBAction)sliderChanged : (UISlider *)sender
{
// skips music with slider changged
[player pause];
[player setCurrentTime:slider.value];
// [player prepareToPlay];
[player play];
}
// Stops the timer when audio finishes
- (void)audioPlayerDidFinishPlaying : (AVAudioPlayer *)player successfully :
(BOOL)flag
{
// Music completed
if (flag)
{
[sliderTimer invalidate];
}
}
2个问题,我有:
我似乎无法暂停音频。当我重新点击播放按钮时,它会在开始时重新启动音频,而不是暂停播放。
该滑块也重新开始而不是暂停。
如何解决这些问题?
感谢
谢谢我会在稍后尝试,顺便说一句,为什么你需要prepareToPlay?我在我的代码中评论过它,它仍然有效。 – Pangu 2015-01-15 19:38:48
这工作完全谢谢! – Pangu 2015-01-16 01:55:09