2011-05-04 3 views
1

AVAudioPlayer를 사용하고 있습니다. 다시 소리를 내고 agian을 호출하고이 응용 프로그램을이 응용 프로그램에서 100 번 호출합니다. 문제는 내가 항상 알록하지만 시간이 갈 때입니다. 놓으면 소리가 나지 않습니다. 나는 무엇을 할 것이다.AVAudioPlayer 누수와 경고 그리고 결국 응용 프로그램이 깨졌습니다.

-(void) ButtonSound 
{ 

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Button1" 
     ofType:@"mp3"]; 
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath]; 
player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil]; 
[player play]; 
[fileURL release]; 

} 

메모리가 누수되어 응용 프로그램이 손상된 경우 플레이어를 한 번에 할당하고 계속해서 사용하고 싶습니다.

답변

0
-(void) ButtonSound 
{ 

    NSBundle  *mainBundle = [NSBundle mainBundle]; 
    NSError   *error; 
    NSURL   *audioURL = [NSURL fileURLWithPath:[mainBundle pathForResource:@"Button1" ofType: @"mp3"]]; 
    AVAudioPlayer *player1 = [(AVAudioPlayer*) [AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error]; 
    self.player = player1; 
    [self.player play]; 
    [player1 release]; 
} 

이 코드는 무료로 오류가 구현에 이미

AVAudioPlayer *buttonSoundPlayer; 

다음 헤더 파일에 선언에게 그것을 플레이어를이

과 같은 작업을 수행 할 수 있습니다 이 코드를 사용하여 누출을 발견하지 못했습니다.

1
이에 코드를 변경

:

-(void) ButtonSound 
{ 
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Button1" 
     ofType:@"mp3"]; 
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath]; 
    if (player) { 
     [player release]; 
    } 
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil]; 
    [player play]; 
    [fileURL release]; 
} 

는 또한 dealloc 방법에 player를 해제해야합니다. 또한 버튼을 클릭 할 때 player이 이미 재생 중인지 확인해야하며, 그렇다면이 방법을 건너 뛸 수 있습니다.

또한 플레이어 개체가 retain 일 필요가 있지만, 플레이어 개체를 선언 한 방법에 따라 다릅니다 (예제에는 표시되지 않음).

4

당신은

-(void)playButtonSound { 
    if(buttonSoundPlayer == nil) { 
     NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Button1" ofType:@"mp3"]; 
     NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath]; 
     buttonSoundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil]; 
     [fileURL release]; 
    } 
    [buttonSoundPlayer play]; 
} 
관련 문제