我想使用AvAudioPlayer停止音频,但是当另一个 View 消失时,有两个 View :
问题是,当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来做到这一点。
谢谢
最佳答案
您的应用程序委托(delegate)不是 View Controller 。也许您想要[[UIApplication sharedApplication] delegate].window.rootViewController
。
如您所见,这很脆弱。可以在 View Controller 之间没有指针,而可以使用松散耦合并使用“stop” NSNotification
。它甚至可能在您的应用程序中的其他地方很有用。
定义
NSString *StopPlayingVideoNotification = @"StopPlayingVideo";
这样两个 View 都可以看到它,因此将
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];
}
关于ios - 在其他View iOS中停止AvAudioPlayer,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22429880/