Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

iphone - Delay in playing sounds using AVAudioPlayer

-(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];

}

I want to play a beep sound when a button is clicked. I had used the above code. But it is taking some delay in playing the sound.

Anyone please help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are two sources of the delay. The first one is bigger and can be eliminated using the prepareToPlay method of AVAudioPlayer. This means you have to declare myExampleSound as a class variable and initialize it some time before you are going to need it (and of course call the prepareToPlay after initialization):

- (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];
}

This should take the lag down to about 20 milliseconds, which is probably fine for your needs. If not, you’ll have to abandon AVAudioPlayer and switch to some other way of playing the sounds (like the Finch sound engine).

See also my own question about lags in AVAudioPlayer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...