我想用AvAudioPlayer停止音频,但当另一个视图消失时,有两种观点:
问题是当view2消失时,音频不会停止......我该怎么做?
View1.h
@property (nonatomic, retain) AVAudioPlayer *audioPlayer;
- (IBAction)playAudio:(id)sender;
- (IBAction)stopAudio:(id)sender;
View1.m
- (void)viewDidLoad
{
[super viewDidLoad];
[self playSound];
}
- (void) playSound
{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"simpsonsTheme"
ofType:@"mp3"]];
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
//[self.audioPlayer play];
[self playAudio:audioPlayer];
}
- (IBAction)playAudio:(id)sender {
[audioPlayer play];
}
- (IBAction)stopAudio:(id)sender {
[audioPlayer stop];
}
View2.m
-(void)viewWillDisappear:(BOOL)animated{
view1 = (View1 *)[[UIApplication sharedApplication] delegate];
[view1 stopAudio:view1.audioPlayer];
}
在View2中我导入View1来做到这一点。 感谢
答案 0 :(得分:0)
您的app委托不是视图控制器。也许你想要[[UIApplication sharedApplication] delegate].window.rootViewController
。
如你所见,那是脆弱的。您可以使用松散耦合并使用“停止”NSNotification
,而不是在视图控制器之间使用指针。它甚至可能在您的应用程序的其他地方有用。
定义
NSString *StopPlayingVideoNotification = @"StopPlayingVideo";
因此两个视图都可以看到它,因此将extern NSString *StopPlayingVideoNotification;
放在一个头文件中。
在View1.m的init中:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopAudio:) name:StopPlayingVideoNotification object:nil];
向View1添加dealloc:
-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:StopPlayingVideoNotification object:nil];
}
在View2.m
中-(void)viewWillDisappear:(BOOL)animated{
[[NSNotificationCenter defaultCenter] postNotificationName:StopPlayingVideoNotification object:self];
}