[英]How to stop background music playing from a different class playing in Xcode?
我已经设置了音乐曲目,以在ViewController.h和.m文件中播放,如下所示。 加载新场景时,我想停止此操作。 (。H):
@interface ViewController : UIViewController<AVAudioPlayerDelegate>{
AVAudioPlayer *startingMusic;
}
@property (nonatomic, retain) AVAudioPlayer *startingMusic;
@end
然后.m
@synthesize startingMusic;
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *music = [[NSBundle mainBundle] pathForResource:musicTrack ofType:@"mp3"];
startingMusic=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:music] error:NULL];
startingMusic.delegate=self;
startingMusic.numberOfLoops=-1;
[startingMusic play];
}
然后,当使用此代码的init方法中加载新场景的另一个类名为PlayLevel.m时,我尝试阻止其播放。
ViewController *test = [[ViewController alloc] init];
[test.startingMusic stop];
但是,当新影片加载时,音乐将继续播放。 有什么建议么?
当你做ViewController *test = [[ViewController alloc] init];
您创建了新的ViewController实例,这意味着您现在在内存中有两个ViewController的对象。
您真正需要做的就是在您当前的电话上stop
通话。
如果要停止另一个与ViewController
没有连接的控制器的音乐,可以尝试通过通知进行操作。
例如:
导入后,在ViewController.h
文件中:
static NSString * const kStopMusicNotificationName = @"kStopMusicNotificationName";
在您的ViewController viewDidLoad:
[NSNotificationCenter.defaultCenter addObserverForName:kStopMusicNotificationName object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
[self.startingMusic stop];
}];
以及何时需要停止音乐:
[NSNotificationCenter.defaultCenter postNotificationName:kStopMusicNotificationName object:nil];
您正在以错误的方式进行操作,实际上应该停止ViewController
的音乐,而不是来自另一个类。 ViewController应该尽可能独立。
您如何加载第二场景? 我想您正在使用Segue?
如果使用的是segue,则可以重写-prepareForSegue
函数,它是UIViewController
函数。 然后,在-prepareForSegue
停止音乐。
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Stop Music
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.