我想从每个视图控制器调用此方法。但我不知道这个方法将在哪里写,以及我如何调用此方法。
-(void)playSound{
NSURL *url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"]];
NSData *data =[NSData dataWithContentsOfURL:url];
audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil];
audioPlayer.delegate = self;
[audioPlayer setNumberOfLoops:0];
[audioPlayer play];
}
答案 0 :(得分:2)
您可以创建一个BaseViewController
并在BaseViewController.h
中声明此方法,并在BaseViewController.m
文件中实施,而不是将所有ViewController
设置为BaseViewController
的子项
<强> BaseViewController.h 强>
@interface BaseViewController : UIViewController
-(void)playSound;
@end
<强> BaseViewController.m 强>
@interface BaseViewController ()
@end
@implementation BaseViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
-(void)playSound {
NSURL *url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"]];
NSData *data =[NSData dataWithContentsOfURL:url];
audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil];
audioPlayer.delegate = self;
[audioPlayer setNumberOfLoops:0];
[audioPlayer play];
}
@end
现在在 viewController.h
中@interface ViewController : BaseViewController
@end
<强> ViewController.m 强>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self playSound];
}
@end
答案 1 :(得分:2)
您可以创建一个类别:
@interface UIViewController (UIViewControllerAudio)
-(void)playSound;
@end
@implementation UIViewController (UIViewControllerAudio)
- (void)playSound{
NSURL *url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"]];
NSData *data =[NSData dataWithContentsOfURL:url];
audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil];
audioPlayer.delegate = self;
[audioPlayer setNumberOfLoops:0];
[audioPlayer play];
}
@end
您可以在视图控制器中调用:
[self playSound];
答案 2 :(得分:2)
<强>步骤1 强>
创建一个BaseViewController
@interface BaseViewController : UIViewController
- (void) playSound;
@end
<强>步骤-2 强>
在 BaseViewController.m 上@implementation BaseViewController
-(void)playSound{
NSURL *url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"]];
NSData *data =[NSData dataWithContentsOfURL:url];
audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil];
audioPlayer.delegate = self;
[audioPlayer setNumberOfLoops:0];
[audioPlayer play];
}
@end
<强>步骤-3 强>
#import "BaseViewController.h"
// Notice this class is a subclass of BaseViewController (parent)
@interface yourViewController : BaseViewController
@end
步骤-4
你可以直接打电话
- (void)viewDidLoad
{
[super viewDidLoad];
[self playSound];
}