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 fileURLWithPath: path1] error:NULL];
[av1 play];
In classB.m,
a = [[classA alloc] initWithNibName:nil bundle:nil];
[a.av1 stop];
What you’re doing here,
is wrong. You’re creating a completely new object which is all probability isn’t playing any music and sending a
stopmessage to its player. If you want to stop the player in the other class, you must store anassigned reference of the other class. If you wish to keep them independent, you can look at notifications.Thisis 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
initofA, register yourself as an observer,and then when the B object is ready to play music, post the notification,
This will result in A’s
turnOffMusicbeing invoked which will pretty much do,Remember to stop listening to notifications when the object is deallocated,
This approach allows you to keep both classes independent.