AVAudioPlayer UIButton - 第二次触摸停止当前音频播放
Posted
技术标签:
【中文标题】AVAudioPlayer UIButton - 第二次触摸停止当前音频播放【英文标题】:AVAudioPlayer UIButton - second touch stop current audio play 【发布时间】:2011-03-09 14:09:12 【问题描述】:我有一个 UIButton,当触摸它时会播放音频文件。此刻连续按两次按钮播放音频文件两次,而不是停止播放。
我希望第二次单击停止音频文件,而不是播放第二个实例。任何建议将不胜感激。谢谢
-(IBAction) buttonNoisePlay
NSString *pathsoundFile = [[NSBundle mainBundle] pathForResource:@"noise" ofType:@"mp4"];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:pathsoundFile] error:NULL];
sound.delegate = self;
sound.numberOfLoops = -1;
sound.volume = 1;
if(sound == nil || sound.playing == NO) //if not playing
[sound play];
else
[sound stop];
【问题讨论】:
【参考方案1】:嗯,我就是这样做的,它只播放一次:
-(void) playSound: (NSString *) strFileName
if(audioPlayer == nil || audioPlayer.playing == NO) //check if it's already playing in case they dbl-tapped (or more) b/c we only want to play it once per found item
//Get the filename of the sound file:
NSString *urlAddress = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], strFileName];
//Get a URL for the sound file
NSURL *url = [NSURL fileURLWithPath:urlAddress];
NSError *error;
//Use AVAudioPlayer to play the sound
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
if (audioPlayer == nil)
NSLog(@"audioPlayer nil Error:%@", [error description]);
else
[audioPlayer play];
在标题中:
AVAudioPlayer *audioPlayer;
我可能还应该在初始化 audioPlayer 之前检查 nil,所以它只完成了一次......但现在 - 它可以工作。
【讨论】:
【参考方案2】:你可以这样做:
-(IBAction) buttonNoisePlay
if(sound == nil || sound.playing == NO) //if not playing
...
//if nil initialize
[sound play];
else
[sound stop];
【讨论】:
谢谢。我编辑了代码,但结果仍然相同。连续触摸两次按钮会播放音频文件两次而不是停止它。我需要在头文件中定义“播放”吗?以上是关于AVAudioPlayer UIButton - 第二次触摸停止当前音频播放的主要内容,如果未能解决你的问题,请参考以下文章