【问题标题】:AVAudioPlayer leaks?AVAudioPlayer 泄漏?
【发布时间】:2023-11-25 03:06:01
【问题描述】:

我遇到了问题,不知道如何处理。想要构建一个有声音和动画的应用程序。它给了我一个 1 级然后是 2 级的内存警告。我已经尝试构建和分析,我得到了所有这些潜在的泄漏。如果我释放音频,声音将不会播放。有什么提示吗?

这是代码的一部分和我得到的泄漏

    - (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;
    }

【问题讨论】:

    标签: iphone objective-c ios xcode avaudioplayer


    【解决方案1】:

    Here 是迄今为止提出的相同问题的解决方案。

        - (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;
        }
    

    为了更好的想法,您可以关注this.

    【讨论】:

      【解决方案2】:

      您必须为 AVAudioPlayer 类实例声明一个实例变量。

      //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;
      }
      

      【讨论】: