简体   繁体   中英

Releasing Audio - Cocoa Xcode (Memory Management)

So in my previous question FOUND HERE , I was trying to find the most optimal way for playing a "jump" sound every time I make my sprite jump in my iOS Game...

For some reason today, I've become worried that I'm loading the audio file millions of time and wasting memory :(

Anywho, the following has been suggested to me, (so every time I jump by tapping the screen, the sound is loaded and played)...

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event
    {
            //NSString *
            jumpSound = [[NSBundle mainBundle] pathForResource:@"boing" ofType:@"mp3"];

            //AVAudioPlayer *
            jumpAffect = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:jumpSound] error:NULL];

            [jumpAffect prepareToPlay];
            [jumpAffect play];

            //then, make sprite jump
            jumpUp = 16;
    }

The above method allows me to press the jump quickly and restart the audio loop even if the previous loop (from the previous jump) hasn't finished yet.

It's worth baring in mind that this could happen hundreds of times a minute (or more realistically a couple of times a second)...

Is this a concern? Do I need to release the tracks when done with the method/game loop?

I think your last question was totally incorrect. AVAudioPlayer has too much latency for a game. When you jump the sound might happen a second later instead of immediately when you want it to. If you wan't to play a sound a million times a minute you should use AudioServices as so:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
     NSURL *pathURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"boing" ofType:@"wav"]];

     SystemSoundID audioEffect;
     AudioServicesCreateSystemSoundID((__bridge CFURLRef) pathURL, &audioEffect);
     AudioServicesPlaySystemSound(audioEffect);
     //then, make sprite jump
     jumpUp = 16;
}

You would have to convert your mp3 to a wav or caf. But I think the tradeoff is worth it...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM