2011-07-11 25 views
0

我试图阻止来自另一个类的声音。 只要应用程序打开,声音开始播放,并设置为在循环播放,除非'用户'更改设置并将声音关闭。如何暴露类成员或如何实现对这些成员行事的方法

这可以工作,但只适用于启动应用程序时,它检查设置声音是否设置为“开启/关闭”,但我希望在设置中更改设置时它会这样做。

这是我迄今为止...

的Firstclass

// grab the path to the caf file 
NSString *soundFilePath = 
[[NSBundle mainBundle] pathForResource: @"Menu_Loop" 
           ofType: @"mp3"]; 
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath]; 
// create a new AVAudioPlayer initialized with the URL to the file 
AVAudioPlayer *newPlayer = 
[[AVAudioPlayer alloc] initWithContentsOfURL: fileURL 
             error: nil]; 
[fileURL release]; 
// set our ivar equal to the new player 
self.player = newPlayer; 
[newPlayer release]; 
// preloads buffers, gets ready to play 
[player prepareToPlay]; 
player.numberOfLoops = -1; // Loop indefinately 
if ([SoundSwitch isEqualToString:@"1"]){ 
[self.player play]; // Plays the sound 
}else{ 
[self.player stop]; // Stops the sound 
} 

此播放声音。 如果我想简单地停止它:

[self.player stop] 

但在同一类这仅适用于我将如何得到它在其他工作吗?

+0

所以你的问题基本上是如何将'self.player'暴露给其他类。我会为球员创造一个属性。它看起来好像你可能已经有一个,但我不能没有更多的代码。 –

回答

0

我会用NSNotifications,这样就可以停止发送或从应用程序的任何位置播放通知。这是你如何做到这一点:

在init方法

为的Firstclass做这样的:

//Notification for stoping 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stop) name:@"StopSound" object:nil]; 
//Notification for playing 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(play) name:@"PlaySound" object:nil]; 

现在创建从选择这两种方法(stop方法和播放方法)

-(void)stop{ 
    [self.player stop] 
} 

-(void)play{ 
    [self.player play] 
} 

在dealloc记得删除通知观察者:

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"StopSound" object:nil]; 
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"PlaySound" object:nil]; 

现在从任何地方你应用离子只是发送通知停止或播放声音

//Stop 
[[NSNotificationCenter defaultCenter] postNotificationName:@"StopSound" object:nil]; 
//Play 
[[NSNotificationCenter defaultCenter] postNotificationName:@"PlaySound" object:nil]; 
+0

谢谢你的回复, –

+0

@Eli没问题。 – Cyprian

+0

我刚刚注意到似乎有问题。 对不起,如果这是非常noobish问题(因为我)在前两行添加时。 我得到两个错误: 1.使用未声明的标识符'Self' 2.预期的标识符或'(' –

0

我会在黑暗中拍摄,因为我不知道那些苹果的东西,但我认为你必须创建你想要从中操纵你的声音的实例AVAudioPlayer。如果您提供的这个课程可以在第二个地方访问,您想播放/停止播放声音,也许您可​​以将您的“播放器”成员暴露给外部使用者?或者什么可以更好,你可以添加到这个类的方法PlaySound(),StopSound(),并通过它们允许外部代码播放声音。

示例代码与谷歌:)

- (void)playSound:{ 
    [self.player play]; 
} 

- (void)stopSound:{ 
    [self.player stop]; 
} 

一点帮助,现在你可以调用外部playSoundstopSound方法类的