2010-03-31 5 views
3
-(IBAction)playSound{ AVAudioPlayer *myExampleSound; 

NSString *myExamplePath = [[NSBundle mainBundle] pathForResource:@"myaudiofile" ofType:@"caf"]; 

myExampleSound =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:myExamplePath] error:NULL]; 

myExampleSound.delegate = self; 

[myExampleSound play]; 

} 

Je souhaite émettre un bip lorsque vous cliquez sur un bouton. J'avais utilisé le code ci-dessus. Mais il faut du temps pour jouer le son.Retarder la lecture des sons à l'aide de AVAudioPlayer

Quelqu'un s'il vous plaît aider.

Répondre

7

Il existe deux sources de délai. Le premier est plus grand et peut être éliminé en utilisant la méthode prepareToPlay de AVAudioPlayer. Cela signifie que vous devez déclarer myExampleSound comme une variable de classe et initialiser un certain temps avant que vous allez en avoir besoin (et bien sûr appeler le prepareToPlay après l'initialisation):

- (void) viewDidLoadOrSomethingLikeThat 
{ 
    NSString *myExamplePath = [[NSBundle mainBundle] 
     pathForResource:@"myaudiofile" ofType:@"caf"]; 
    myExampleSound =[[AVAudioPlayer alloc] initWithContentsOfURL: 
     [NSURL fileURLWithPath:myExamplePath] error:NULL]; 
    myExampleSound.delegate = self; 
    [myExampleSound prepareToPlay]; 
} 

- (IBAction) playSound { 
    [myExampleSound play]; 
} 

Cela devrait prendre le retard à environ 20 millisecondes, ce qui est probablement bien pour vos besoins. Sinon, vous devrez abandonner AVAudioPlayer et passer à une autre façon de jouer les sons (comme le Finch sound engine).

Voir aussi ma propre question sur lags in AVAudioPlayer.

1

AudioServicesPlaySystemSound est une option. Didacticiel here, exemple de code here.

+0

thx, zoul, pour l'exemple de lien de code. – ohho

+3

Mais vous ne pouvez pas contrôler le volume avec ceci. – arundevma

+0

Pour autant que je sache, vous ne pouvez jouer qu'un seul son à la fois. – VagueExplanation

Questions connexes