2012-09-08 34 views
0

我已經實現了一個減法計數器,它每秒鐘播放一次Click聲音直到計時器失效。同時,我顯示計數器值。在每秒鐘(iPhone)的計數中播放點擊/滴答聲?

-(IBAction)start{ 
    myTicker =[NSTimerscheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showactivity) userInfo:nil repeats:YES]; 
     } 

     -(void)showactivity;{ 

     int CurrentTime =[time.textintValue]; 

     NSString *soundFilePath=[[NSBundlemainBundle] pathForResource:@"Click03" ofType:@"wav"]; 
     NSURL *soundFileURL =[NSURLfileURLWithPath:soundFilePath]; 
     AVAudioPlayer *player=[[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil]; 
     player.numberOfLoops =1; 
     [player play]; 

     int newTime = CurrentTime-1; 
     time.text = [NSString stringWithFormat:@"%d",newTime]; 
     if(newTime ==0){ 
       [myTicker invalidate]; 
     time.text = @"0"; 

      } 

     } 

計數器完美地工作,但有一個小的初始延遲;但它不會發出聲音,任何人都可以幫助我有效地實現這個概念,最小延遲等...

+0

如果你使用'ARC',本地'AVAudioPlayer'對象將在塊完成後自動解除分配。因爲沒有其他強大的指針可以使它保持活躍狀態​​,所以沒有機會聽到/播放你的聲音......解決方案不是使用本地的'AVAudioPlayer'實例在你的類中使用全局的。 – holex

+0

@holex - 是的,它適用於全球,然後我需要在ViewDidLoad中加載聲音文件,並在 - (void)showactivity {}中使用它,這是一種更好的編程技術嗎?我認爲編程不是按照預期完成工作,而是要以最聰明的方式! :) – sam

+0

如果您一直使用相同的聲音效果,則只需加載一次即可,例如'-viewDidLoad'方法。你可以用這種方式節省一些資源。 – holex

回答

0

你可以發出一秒鐘長的聲音,其中包括點擊1秒(減去點擊的持續時間)的沉默樣本。將player.numberOfLoops設置爲不得不倒數秒,然後只播放一次。

0

要使用AVAudioPlayer

播放聲音

1)添加

@property (nonatomic, strong) AVAudioPlayer *player; 

到你的頭文件

記得合成在你的.m文件

2)初始化播放器並用以下代碼播放聲音:

 NSString *soundFilePath=[[NSBundle mainBundle]pathForResource:@"yourSoundFile" ofType:@"caf"]; 

    NSURL *soundFileURL =[NSURL fileURLWithPath:soundFilePath]; 

    NSError *err = nil; 

    self.player=[[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:&err]; 

    self.player.numberOfLoops = 0; 

    if ([self.player play]) { 
     NSLog(@"playing sound"); 
    }else { 
     NSLog(@"COULD NOT play sound"); 
    }; 

請注意,將self.player.numberOfLoops設置爲0會一次播放聲音。將其設置爲1,將循環一次,導致聲音連續播放兩次。

0

解決ARC釋放問題,你可以做的一件事就是將所有玩家添加到數組中。然後將自己設置爲玩家的代表,監聽音頻何時完成播放,然後將其從陣列中移除。這樣,玩家在完成遊戲之前不會被釋放。事情是這樣的:

@property (nonatomic, strong) NSMutableArray *playersArray 

-(void)showactivity 
{ 
    int CurrentTime =[time.textintValue]; 

    NSString *soundFilePath=[[NSBundlemainBundle] pathForResource:@"Click03" ofType:@"wav"]; 
    NSURL *soundFileURL =[NSURLfileURLWithPath:soundFilePath]; 
    AVAudioPlayer *player=[[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil]; 
    player.numberOfLoops =1; 
    player.delegate = self; 
    [player play]; 
    [self.playersArray addObject:player]; 

    int newTime = CurrentTime-1; 
    time.text = [NSString stringWithFormat:@"%d",newTime]; 
    if (newTime == 0) { 
     [myTicker invalidate]; 
     time.text = @"0"; 
    } 
} 

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag 
{ 
    [playersArray removeObject:player]; 
} 

記住要初始化您的數組。