Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS: AVAudioPlayer stop and play

I have this code:

NSString *path = [NSString stringWithFormat:@"%@/%@",
                  [[NSBundle mainBundle] resourcePath],
                  @"change.mp3"];
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
change = [[AVAudioPlayer alloc] initWithContentsOfURL:filePath error:nil];
[change prepareToPlay]; 

I write in this code in viewdidload; now with a button I start this sound, but if I press the same button, I want to stop this sound and restart the sound; I try this code inside IBAction but it don't work

[change stop];
[change prepareToPlay];
[change play];

what can I do?

like image 660
cyclingIsBetter Avatar asked Dec 09 '22 01:12

cyclingIsBetter


2 Answers

How about this:

[change pause];
change.currentTime = 0.0;
[change play];
like image 52
Till Avatar answered Dec 23 '22 01:12

Till


The documentation of the method -stop says:

The stop method does not reset the value of the currentTime property to 0. In other words, if you call stop during playback and then call play, playback resumes at the point where it left off.

So you have to use the property currentTime and set it to 0:

[change pause];
[change setCurrentTime:0];
[change play];
like image 40
sch Avatar answered Dec 23 '22 01:12

sch