开发者

iOS - How to stop background music when changing views

How to stop background music when changing views? I have no clue. If i press a button which takes me to a new view, there is new background music. But the old background music开发者_如何学JAVA (which goes in an infinite loop) keeps on going. Please help! also sample some code please, here is mine:

- (void)viewDidLoad {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"MathMusic2" ofType:@"wav"];
    AVAudioPlayer* theAudio= [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    theAudio.delegate = self;
    [theAudio play];
    theAudio.numberOfLoops = -1;

    [super viewDidLoad];
}

I just need to know how to make the background music from the new view stop playing. And vice versa when i press the back button from the new view


Create a property for the AVAudioPlayer *theAudio so you can access the audioPlayer from any point in your class.

Header file of viewController

... 
AVAudioPlayer *theAudio;
...
@property (nonatomic, retain) AVAudioPlayer *theAudio;

Implentation file of viewController

...
@synthesize theAudio;
...

- (void)viewDidLoad {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"MathMusic2" ofType:@"wav"];
    self.theAudio= [[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]] autorelease];
    theAudio.delegate = self;
    [theAudio play];
    theAudio.numberOfLoops = -1;

    [super viewDidLoad];
}

If viewWillDisappear is called you can then just stop the audio with

- (void)viewWillDisappear
{
    [theAudio stop];
}


it gaves errors in here : "theAudio.delegate = self;" as something like assigning to id...

its yellow anyway.. still when i change view and go to another class music not stoping....

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜