Stopping sound from another class
I have played a sound in classA, and does anyone know how to stop it in classB?
I have read several posts already, most of them just mention about creating an instance (i.e. things like Class A *a in .h, and a =[[Class A alloc]init] in .m). This wont work for some reasons.
Here are some codes: In classA.m
path1 = [[NSBundle mainBundle] pathForResource:[@"songName" ofType:@"mp3"];
av1 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL f开发者_如何学运维ileURLWithPath: path1] error:NULL];
[av1 play];
In classB.m,
a = [[classA alloc] initWithNibName:nil bundle:nil];
[a.av1 stop];
Do you know how to stop the sound in class A?
Just do the same thing, but in class B.
What you're doing here,
a = [[classA alloc] initWithNibName:nil bundle:nil];
[a.av1 stop];
is wrong. You're creating a completely new object which is all probability isn't playing any music and sending a stop
message to its player. If you want to stop the player in the other class, you must store an assign
ed reference of the other class. If you wish to keep them independent, you can look at notifications. This
is a definitive guide from Apple. Basically, this will involve registering A as the observer to a notification and then when B is ready to play it will post the notification that it's about to play music. When A receives that notification should turn off its music.
So in the init
of A
, register yourself as an observer,
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(turnOffMusic:)
name:@"BWillPlayMusicNotification"
object:nil];
and then when the B object is ready to play music, post the notification,
[[NSNotificationCenter defaultCenter] postNotification:@"BWillPlayMusicNotification"];
This will result in A's turnOffMusic
being invoked which will pretty much do,
- (void)turnOffMusic:(NSNotification *)notification {
[self.av1 stop];
}
Remember to stop listening to notifications when the object is deallocated,
[[NSNotificationCenter defaultCenter] removeObserver:self];
This approach allows you to keep both classes independent.
精彩评论