AVAudioPlayer leaks?

夙愿已清 提交于 2019-12-11 15:35:10

问题


I've got a problem and don't know how to handle it. Tyring to build an app with sound and animation. It gives me a level 1 and then level 2 memory warning. I've tried build and analyze and i got all these potential leaks. If I release theAudio the sound won't play. Any hints?

Here is a part of the code and the leakes I've got

    - (IBAction)playsound2
    {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"cat" ofType:@"mp3"];
        AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
        *- **Method returns an Objective-C object with a +1 retain count (owning reference)***
        theAudio.delegate = self;
        [theAudio play];

        ***-  Object allocated on line 302 and stored into 'theAudio' is no longer referenced after this point and has a retain count of +1 (object leaked)***


        cat1.hidden = 0;
        cat.hidden = 1;
        [cat1 startAnimating];
        cat.center = cat1.center;
        [self performSelector:@selector(loadAnimations) withObject:nil afterDelay:1.0];
        catLabel.hidden = 0;
    }

回答1:


Here is the solution for the same problem asked so far.

    - (AVAudioPlayer *)audioPlayerWithContentsOfFile:(NSString *)path {
        NSData *audioData = [NSData dataWithContentsOfFile:path];
        AVAudioPlayer *player = [AVAudioPlayer alloc];
        if([player initWithData:audioData error:NULL]) {
            [player autorelease];
        } else {
            [player release];
            player = nil;
        }
        return player;
    }

And for better idea you can follow this.




回答2:


You have to state an instance variable for the AVAudioPlayer class instance.

//Instance variable:
{
    AVAudioPlayer* theAudio;
}

- (IBAction)playsound2
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"cat" ofType:@"mp3"];
    if (!theAudio ) {
        theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
        if (theAudio ) {
            theAudio.delegate = self;
            [theAudio play];
        }
    }

    cat1.hidden = 0;
    cat.hidden = 1;
    [cat1 startAnimating];
    cat.center = cat1.center;
    [self performSelector:@selector(loadAnimations) withObject:nil afterDelay:1.0];
    catLabel.hidden = 0;
}


来源:https://stackoverflow.com/questions/7221024/avaudioplayer-leaks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!