我已设置要在 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
没有连接的 Controller 的音乐,您可以尝试通过通知执行此操作。
例如:
在您的 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];
关于ios - 如何停止在 Xcode 中播放不同类的背景音乐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28608480/