2009-07-31 16 views
0

我有一個數組,可按特定順序創建幾個不同的聲音文件名。我已經成功創建了該數組,但是我不確定如何將數組中的值作爲文件URL調用,或者如何將其實現爲AudioServicesPlaySystemSoundID。如何調用數組值並使用它來播放聲音文件?

這是我的代碼至今:

 - (void)viewDidLoad { 
      NSArray *sounds = [[NSArray alloc] initWithObjects: @"0.wav", @"1.wav", @"2.wav, nil]; 
      NSUInteger currentSound = 0; 
      soundArray = sounds 
      [super viewDidLoad]; 
     } 

     - (void) playFailSound { 
      currentSound++; 
      if (currentSound >= [sounds count]) { 
       currentSound = 0; 
      } 
      [self playSoundWithFilename:[sounds objectAtIndex:currentSound]]; 
     } 

我也不知道我需要在頭文件中聲明這個工作,我如何存儲陣列的價值?

回答

0

你問的是如何調用playFailSound:?還是你問如何聲明頭文件中的聲音數組,使其成爲一個實例變量?

您遇到的第一個問題是您在兩種方法中對數組使用了不同的變量名稱。在viewDidLoad中使用soundArray,在playFailSound中使用聲音。

在你的頭文件,你需要聲明數組作爲實例變量:

#import <UIKit/UIKit.h> 

@interface MyObject : NSObject { 
    NSArray *_sounds; //declare the variables 
    NSInteger _currentSound; //this doesn't need to be unsigned, does it? 

} 

@property(nonatomic, retain) NSArray *sounds; //property 
@property(value) NSInteger currentSound; //property 


//method declarations 
- (void) playFailSound;  
- (void) playSoundWithFilename:(NSString *)fileName; 

@end 

你會發現我使用的變量名的下劃線,但在沒有屬性。這樣,當您意圖使用該屬性時,您不會意外使用該變量。

在實現文件中,你需要執行以下操作:

#import "MyObject.h" 

@implementation MyObject 

//synthesize the getters and setters, tell it what iVar to use 
@synthesize sounds=_sounds, currentSound=_currentSound; 

    - (void)viewDidLoad { 
     NSArray *tempSounds = [[NSArray alloc] initWithObjects: @"0.wav", 
                  @"1.wav", 
                  @"2.wav, nil]; 
     self.currentSound = 0; //use the setter 
     self.sounds = tempSounds; //use the setter 
     [tempSounds release]; //we don't need this anymore, get rid of the memory leak 
     [super viewDidLoad]; 
    } 

    - (void) playFailSound { 
     self.currentSound=self.currentSound++; //use the getters and setters 
     if (self.currentSound >= [self.sounds count]) { 
      self.currentSound = 0; 
     } 
     [self playSoundWithFilename:[self.sounds objectAtIndex:self.currentSound]]; 
    } 

    - (void) playSoundWithFilename:(NSString *)filename { 
     //you fill this in 
    } 
@end 

現在,所有你需要做的是從什麼地方打電話playFailSound,並在實際播放的聲音部分填補。

實質上,對於兩個方法來引用相同的變量,它們之間沒有傳遞,它需要是一個實例變量。

這是非常基本的東西,所以如果你沒有得到我在這裏解釋的內容,我會建議重新閱讀一些Apple的介紹性資料。

+1

不要忘記dealloc。 – 2009-08-02 00:04:07