I have a button that toggles between a play and a pause image when tapped. When play image is shown a looped sound is playing, when pause image is shown sound stops playing.
I have manage to get this to work, but there is one issue. When you tap the button to pause (stop) it plays the sound one last time (so the pause action is delayed by the number of seconds of the sound).
Here's my code:
@implementation ViewController
AVAudioPlayer *myAudio;
- (void)viewDidLoad {
[super viewDidLoad];
[self.myButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
[self.myButton setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateSelected];
}
- (IBAction)buttonTapped:(id)sender {
NSURL *musicFile;
musicFile = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"]];
myAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
if(self.myButton.selected)
[self.myButton setSelected:NO];
else
[self.myButton setSelected:YES];
if(self.myButton.selected)
[myAudio setNumberOfLoops:-1];
[myAudio play];
}
What you're doing is creating a player every time you tap on the button.
You should try and create one AVPlayer
(in viewDidLoad
), and use it's play
and pause
functions in the buttonTapped:
function.
- (void)viewDidLoad {
[super viewDidLoad];
[self.myButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
[self.myButton setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateSelected];
NSURL *musicFile = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"]];
myAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
}
- (IBAction)buttonTapped:(id)sender {
[self.myButton setSelected:!self.myButton.selected];
if (self.myButton.selected) {
[player seekToTime:kCMTimeZero];
[player play];
}
else {
[player pause];
}
}
Clicking on the button would first toggle it's state (selected or not) and then based on its state, the player will rewind and start playing, or pause itself (instantly).