2014-03-06 86 views
0

我有兩個類,一個是初始化SystemSoundID,然後是一個鏈接到實際聲音文件的方法。 但是,當我在我的MainViewController中調用方法並通過IBAction播放時,沒有聲音播放。使用AudioToolBox播放聲音文件編譯但沒有聲音的類

Sound.h:

#import <Foundation/Foundation.h> 
    #import <AudioToolbox/AudioServices.h> 

    @interface TheSound : NSObject { 
     SystemSoundID yayFileID; 
    } 
    @property(nonatomic) SystemSoundID yayFileID; 
    - (void) initSound; 

    @end 

Sound.m:

#import "TheSound.h" 
    #import <AudioToolbox/AudioServices.h> 

    @implementation TheSound 
    @synthesize yayFileID; 

    - (void) initSound { 
     NSString *yayPath = [[NSBundle mainBundle] pathForResource: @"yay" ofType: @"wav"]; 
     CFURLRef yayURL = (__bridge CFURLRef) [NSURL fileURLWithPath:yayPath]; 
     AudioServicesCreateSystemSoundID(yayURL, &yayFileID); 
    } 

    @end 

MainViewController.h:

#import <UIKit/UIKit.h> 
    #import "TheSound.h" 

    @interface MainViewController : UIViewController 

    - (IBAction) playSound: (id) sender; 

    @end 

MainViewController.m:

#import "MainViewController.h" 
    #import <AudioToolbox/AudioServices.h> 
    #import "TheSound.h" 

    @interface MainViewController() 
    @property SystemSoundID yayFileID; 
    @property (nonatomic) TheSound *foo; 
    @end 

    @implementation MainViewController 
    @synthesize foo; 

    - (void)viewDidLoad { 
     [foo initSound]; 
     [super viewDidLoad]; 
    } 


    - (IBAction)playSound:(id)sender { 
     AudioServicesPlaySystemSound(_yayFileID); 
    } 

    @end 

幫助我做錯了什麼將非常感謝!提前致謝!

回答

0

這裏

- (IBAction)playSound:(id)sender { 
    AudioServicesPlaySystemSound(_yayFileID); 
} 

可變_yayFileID指變量在MainViewController這是完全無關的在TheSound對象的yayFileID變量。

也許如果你嘗試

AudioServicesPlaySystemSound(foo.yayFileID); 

即使你做到這一點,我不認爲它會奏效,因爲除此之外,你foo變量沒有初始化,因此呼叫initSound被髮送到空。你應該這樣做

foo = [[TheSound alloc] init]; 
[foo initSound]; 
+0

就是這樣,非常感謝你! :) – gymbry