我有一个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];
}
}
答案 0 :(得分:2)
-(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,所以它只做了一次......但是现在 - 它可以工作。
答案 1 :(得分:1)
你可以这样做:
-(IBAction) buttonNoisePlay {
if(sound == nil || sound.playing == NO) //if not playing
{
...
//if nil initialize
[sound play];
}
else
{
[sound stop];
}
}