开发者

Seemingly Simple AVAudioPlayer code will not play audio file on iPhone

开发者 https://www.devze.com 2023-01-09 08:07 出处:网络
I am trying to play a short sound whenever clicks a button on the iPhone; however, for some reason whenever I click the button (which calls the playClickSound method below), no sound plays. I have the

I am trying to play a short sound whenever clicks a button on the iPhone; however, for some reason whenever I click the button (which calls the playClickSound method below), no sound plays. I have the project linked with AudioFoundation.framework and the sound file (clickSound.mp3) in the Resources folder of my application bundle. Can someone please help me figure out what I am missing, and why the AVAudioPlayer won't play my sound file?

- (void) playClickSound {

    // Get path of sound file in bundle.
    NSString *path = [[NSBundle mainBundle] pathForResource: @"clickSound" of开发者_JAVA百科Type: @"mp3"];

    // Create url from path.
    NSURL *url = [NSURL URLWithString: path];

    // Create error.
    NSError *error;

    // Create audio player, and play file.
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: url error: &error];

    if (![audioPlayer play]) {
        [error localizedDescription];
    }

    [audioPlayer release];



} // playClickSound


Your method never actually tells the audioPlayer to play. Try this after you allocate the audio player:

[audioPlayer play];

Also - you may want to look into the delegate method to release the player after the sound has played. I don't think your sound will play if you immediately release it after creating it like you are doing here.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号