在 ViewController 中播放时从 SKScene 静音 AVAudioPlayer
Posted
技术标签:
【中文标题】在 ViewController 中播放时从 SKScene 静音 AVAudioPlayer【英文标题】:muting AVAudioPlayer from SKScene while its playing in ViewController 【发布时间】:2014-02-25 08:41:19 【问题描述】:我有一个 AVAudioPlayer 设置为在 ViewController.m 中无限循环。 我的问题是我将如何从 SKScene 中静音 AVAudioPlayer
//ViewController.m
- (void)viewDidLoad
[super viewDidLoad];
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Space theme2" ofType:@"mp3"]];
_music = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[_music prepareToPlay];
[_music setVolume:0.5];
_music.numberOfLoops = -1;
[_music play];
所以 AVAudioPlayer 正在 ViewController.m 中播放,需要在 SKScene 中静音/取消静音。
//SKScene.m
if ([node.name isEqualToString:@"Mute"])
//Mute Music "[_music setVolume:0.0]; isn't doing anything"
self.Mute.position = CGPointMake(-100, self.Mute.position.y);
self.Unmute.position = CGPointMake(160, self.Unmute.position.y);
if ([node.name isEqualToString:@"Unmute"])
//Unmute Music [_music setVolume:0.5]; isn't doing anything"
self.Mute.position = CGPointMake(160, self.Mute.position.y);
self.Unmute.position = CGPointMake(-100, self.Unmute.position.y);
感谢任何帮助
【问题讨论】:
【参考方案1】:通过使用NSNotificationCenter
:
//ViewController.m
- (void)awakeFromNib
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(stopMusic:)
name:@"StopMusic"
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(playMusic:)
name:@"PlayMusic"
object:nil];
- (void)viewDidLoad
[super viewDidLoad];
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Space theme2" ofType:@"mp3"]];
_music = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[_music prepareToPlay];
[_music setVolume:0.5];
_music.numberOfLoops = -1;
[_music play];
- (void)stopMusic:(NSNotification*)notification
[_music stop];
- (void)playMusic:(NSNotification*)notification
[_music play];
- (void) dealloc
// If you don't remove yourself as an observer, the Notification Center
// will continue to try and send notification objects to the deallocated
// object.
[[NSNotificationCenter defaultCenter] removeObserver:self];
.
// Scene.m:
if ([node.name isEqualToString:@"Mute"])
[[NSNotificationCenter defaultCenter]
postNotificationName:@"StopMusic" object:self];
self.Mute.position = CGPointMake(-100, self.Mute.position.y);
self.Unmute.position = CGPointMake(160, self.Unmute.position.y);
if ([node.name isEqualToString:@"Unmute"])
[[NSNotificationCenter defaultCenter]
postNotificationName:@"PlayMusic" object:self];
self.Mute.position = CGPointMake(160, self.Mute.position.y);
self.Unmute.position = CGPointMake(-100, self.Unmute.position.y);
【讨论】:
非常感谢,很好的回答!【参考方案2】:您可以使用 NSNotification 或委托方法。您可以查看here 和here。
【讨论】:
以上是关于在 ViewController 中播放时从 SKScene 静音 AVAudioPlayer的主要内容,如果未能解决你的问题,请参考以下文章
嵌入 NavigationController swift4 时从 UIPageViewController 更新子 ViewController