大家好,
请查看下面的代码,我希望能够在单击同一按钮,单击另一个按钮甚至返回主屏幕时停止声音。不确定在这里做什么


FoxViewController.m

#import "FoxViewController.h"
#import <AVFoundation/AVAudioPlayer.h>
AVAudioPlayer *newPlayer_Fox;

@interface FoxViewController ()

@end

@implementation FoxViewController

-(IBAction) Fox;
{
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: @"new"ofType: @"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil];
[newPlayer play];



}


- (id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
 {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}

 - (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}


@end

FoxViewController.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
AVAudioPlayer *newPlayer;

@interface FoxViewController : UIViewController

-(IBAction)Fox;

@end

贾斯汀,非常感谢您的帮助。

最佳答案

维护一个flag并说BOOL soundPlay作为FoxViewController.h文件中的全局变量

现在在FoxViewController.m's viewDidLoad方法中

 soundPlay = TRUE;

Action 按钮将如下所示:
-(IBAction) Fox;
{
 if(soundPlay){
   soundPlay = FALSE; //made false for next time another condition will be used.
   NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: @"new"ofType: @"mp3"];
   NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
 newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil];
  [newPlayer play];
 }
 else
 {
    if([newPlayer isPlaying])
    {
       [newPlayer stop];
    }
 }
}

对于stopping sound中的background,如果未添加,请添加此方法
 -(void)viewWillDisappear:(BOOL)animated
 {
   [super viewWillDisappear:animated];

   //stop background sound
   if([newPlayer isPlaying])
   {
    [newPlayer stop];
   }
 }

08-05 12:36