开发者

avaudioplayer problem

i've got a problem with avaudioplayer. i've got a method that plays the music:

-(void)playBgMusic {

NSString *path = [[NSBundle mainBundle] pathForResource:@"bgmusic" ofType:@"aif"];
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileU开发者_如何学CRLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];    }

It's called in the viewDidLoad method:

- (void)viewDidLoad {
[super viewDidLoad];

[self playBgMusic]; }

Now the problem: when I switch to another view the music goes on but when I go back again the music starts a second time and overlaps.

how can I solve this problem?


Why start your music in -viewDidLoad? Put it in your controller's initializer. If you're just creating it in a XIB and haven't already overridden the initializer, implement -initWithCoder:, like this:

- (id)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];

    if(self)
    {
        [self playBgMusic];
    }

    return self;
}

... or if you're allocating/initializing it manually, do the same thing, but with -init (or whatever custom initializer you've set up) instead. This way, the music player will only start when you first create the view controller, which from the sound of it you're probably only doing once.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜