2012年1月13日 星期五

用AVAudioPlayer播放音效

在.h的宣告部份
#import <AVFoundation/AVFoundation.h> //先import AVFoundation後才能使用這個功能

AVAudioPlayer *titleBGM; //宣告一個新的聲音叫titleBGM(自已隨便取)是屬於AVAudioPlayer型式

- (void) playBGM; //宣告播放playBGM的功能

在.m的實作部份
//在init的時侯先設定titleBGM要播放音效檔
-(id)init{
    
    if (self = [super init]) {
        //下面紅字這一段是設定titleBGM
        NSBundle *bundle = [NSBundle mainBundle];
        NSString *path = [bundle pathForResource:@"menu" ofType:@"wav"];
        NSURL * url = [NSURL fileURLWithPath:path];
        titleBGM =[[AVAudioPlayer alloc] initWithContentsOfURL:url
                                                         error:nil];
        self->titleBGM.delegate = self;
    }
    return self;
}

//實作playBGM
- (void) playBGM{
    
    [titleBGM play];
}

//播放的使用方法

[titleBGM play];

0 意見:

張貼留言