AVAudioPlayer stop a sound and play it from the beginning

夙愿已清 提交于 2019-12-04 09:57:30

问题


I used the AVAudioPlayer to play a 10 sec wav file and it works fine. Now I what to stop the wav at the 4th sec and then play it again from the very 1st sec.

Here is the code I tried:

NSString *ahhhPath = [[NSBundle mainBundle] pathForResource:@"Ahhh" ofType:@"wav"];
AVAudioPlayer *ahhhhhSound =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:ahhhPath] error:NULL];

[ahhhhhSound stop];
[ahhhhhSound play];

What I get is, the wav stops at the 4th sec but when I run the [XXX play] again, the wav continues to play the 5th sec instead of playing from the beginning.

How could I get this done? Any help will be appreciated.


回答1:


Apple's AVAudioPlayer class reference 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 should be able to restart it with:

[ahhhhhSound stop];
ahhhhhSound.currentTime = 0;
[ahhhhhSound play];



回答2:


So I had some troubles as you can see from my comment on DarkDust's answer. The problem only appeared on iOS 4.3.3/4.3.5, iPhone 4. Possibly earlier iOS versions as well, but not iOS 5.0.1. Somehow the AVAudioPlayer itself seemed to "break" when stopping it and the latter play would just fail unexplicably. Actually a "stop" would unload some stuff loaded on prepareToPlay, that is not unloaded if you just "pause" the player - according to the reference. So my solution would be using pause instead of stop - regarded the player is currently playing - otherwise there would be no reason to stop anything. Should theoretically be faster too. Solved it for me.

if (ahhhhhSound.playing) {
    [ahhhhhSound pause];
}
ahhhhhSound.currentTime = 0;
[ahhhhhSound play];

Now I can get on with life again.




回答3:


Swift:

mySound.audioPlayer?.stop()
mySound.audioPlayer?.currentTime = 0
mySound.audioPlayer?.play()


来源:https://stackoverflow.com/questions/3845906/avaudioplayer-stop-a-sound-and-play-it-from-the-beginning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!