2013-12-21 17 views
-5

我需要你的幫助。問題:有一個數組,其中的對象4,當我按下播放聲音時,有一個按鈕,並改變(+1)數組索引=>當用戶第二次點擊時,聲音應該與索引「2」等。問題是索引不變,播放索引爲「1」的文件。陣列中的objective-c索引

* .H:

@interface AZViewController : UIViewController 

{ 

    NSInteger _acatindex; 
} 

@property (weak, nonatomic) NSMutableArray *acat; 

- (IBAction)catbutt:(id)sender; 

* .M

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    //array 

    NSMutableArray *acat = [NSMutableArray arrayWithObjects:@"cat1", @"cat2", @"cat3", @"cat4", nil]; 

    NSURL *url = [[NSBundle mainBundle] URLForResource:[acat objectAtIndex:_acatindex] withExtension:@"wav"]; 
    NSAssert(url, @"URL is valid."); 
    NSError* error = nil; 
    self.catplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
    if(!self.catplayer) 
    { 
     NSLog(@"Error creating player: %@", error); 
    } 

} 
    //button action 
- (IBAction)catbutt:(id)sender 
{  
    _acatindex++; 
    if (_acatindex == _acat.count) 
    { 
     _acatindex = 0; 
    } 

    AZTrace(); 
    [self.catplayer stop]; 
    [self stopTimer]; 
    self.catplayer.currentTime = 0; 
    [self.catplayer prepareToPlay]; 

    AZTrace(); 
    [self.catplayer play]; 
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES]; 
} 

回答

0

刪除這些行:

[acat addObject:@"cat1"]; 
    [acat addObject:@"cat2"]; 
    [acat addObject:@"cat3"]; 
    [acat addObject:@"cat4"]; 

聲明您的陣列和NSURL不viewDidLoad中,這樣做是不是您的.h:

@interface AZViewController : UIViewController 

{ 

    NSInteger _acatindex; 
    NSMutableArray *acat; 
    NSURL *url; 
} 

@property (weak, nonatomic) NSMutableArray *acat; 

- (IBAction)catbutt:(id)sender; 

現在從viewDidLoad()切下面的代碼:

url = [[NSBundle mainBundle] URLForResource:[acat objectAtIndex:_acatindex] withExtension:@"wav"]; 
    NSAssert(url, @"URL is valid."); 
    NSError* error = nil; 

self.catplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
    if(!self.catplayer) 
    { 
     NSLog(@"Error creating player: %@", error); 
    } 

並將其粘貼在- (IBAction)catbutt:(id)sender以上_acatindex++;

希望這會有所幫助。

+1

是啊,謝謝! – VELDT

+1

@VELDT不客氣。但是如果你想在這個網站上生存下來,請在發佈之前進行總結搜索。 –

0

你只加載URL在-viewDidLoad:方法。您需要通過-catbutt:方法告訴音頻播放器播放陣列中的下一個聲音。您正在停止播放器,但在重新啓動之前您並未更改播放的文件。

+0

請詳細向我解釋一下,如果這可以舉例 – VELDT

+0

謝謝!是工作! – VELDT