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