4,549,531 th visitor since 2017.2.1 ( Today : 5923 )
Programming
No. 592
Name. 로꼬다
Subject. SystemSoundID 사용시의 메모리 누수 문제 방지
Main Cate. iOS
Sub Cate. iOS
Date. 2009-04-09 18:59
Hit. 4266 (211.36.27.28)
File.
웹에서 사운드 실행관련 소스를 찾아서 적용하다가
분명히 alloc으로 할당함에도 불구하고 release 관련 부분이 없어서
메모리 누수를 확인해보니 역시나 메모리 누수가 존재하더군요.

실행은 다음과 같이 합니다.

    SoundEffect *soundEffect=[[SoundEffect alloc] initWithSoundType:1];
    [soundEffect playSound];
    //[soundEffect release];
위의 주석 부분 처럼 바로 release 처리할 경우 사운드 재생이 되지 않습니다.
재생 완료 후 사용할 콜백 함수를 선언하고 거기서 release 처리해 주어야 합니다.


전체 소스는 아래와 같습니다. 중간에 주석으로 처리해 두었으니 확인해 주세요.

#SoundEffect.h
#import <Foundation/Foundation.h>
#import <AudioToolbox/AudioServices.h>    // SystemSoundID 사용을 위한 임포트

@interface SoundEffect : NSObject {
    SystemSoundID soundID;
}
- (id)initWithSoundType:(int)soundType;
- (void)playSound;
static void completionCallback (SystemSoundID mySSID, void* myself);
@end




#SoundEffect.m
#import "SoundEffect.h"

@implementation SoundEffect

// 객체 생성
// soundType 0:reset 1:up 2:down
// 웨이브 포맷에 따라 재생이 안되는 것인가? 윈도우 시스템 wav파일을 사용해본 결과 재생이 되지 않음
- (id)initWithSoundType:(int)soundType {
    self = [super init];
    id sndPath;
    if (soundType==0) {
        sndPath = [[NSBundle mainBundle] pathForResource:@"Purr" ofType:@"aiff" inDirectory:@"/"];
    } else if (soundType==1) {
        sndPath = [[NSBundle mainBundle] pathForResource:@"Tink" ofType:@"aiff" inDirectory:@"/"];
    } else {
        sndPath = [[NSBundle mainBundle] pathForResource:@"Pop" ofType:@"aiff" inDirectory:@"/"];
    }
    CFURLRef baseURL = (CFURLRef) [[NSURL alloc] initFileURLWithPath:sndPath];
    AudioServicesCreateSystemSoundID(baseURL, &soundID);
    [baseURL release];
    return self;
}

//사운드 재생 - 완료 이후 메모리에서 해제
- (void)playSound {
    //재생후 메모리 해제를 위한 콜백 추가
    AudioServicesAddSystemSoundCompletion (soundID,NULL,NULL,completionCallback,(void*) self);
    AudioServicesPlaySystemSound(soundID);
}

static void completionCallback (SystemSoundID mySSID, void* myself) {
    //릴리즈 전 콜백 제거
    AudioServicesRemoveSystemSoundCompletion (mySSID);
    [(SoundEffect*)myself release];
}

- (void)dealloc {
    if (soundID) {
        AudioServicesDisposeSystemSoundID(soundID);
    }
    [super dealloc];
}

@end


[바로가기 링크] : http://coolx.net/cboard/develop/592



Name
Password
Comment
Copyright © 1999-2017, swindler. All rights reserved. 367,611 visitor ( 1999.1.8-2004.5.26 ), 2,405,771 ( -2017.01.31)

  2HLAB   2HLAB_Blog   RedToolBox   Omil   Omil_Blog