Play a short sound in iOS

前端 未结 13 726
悲哀的现实
悲哀的现实 2020-11-27 10:23

I guess I could use AVAudioPlayer to play a sound, however, what I need is to just play a short sound and I don\'t need any loops or fine-grained control over t

相关标签:
13条回答
  • 2020-11-27 11:24

    Heres a quick clean method you can copy in and use in your app:

    -(BOOL) playSoundFXnamed: (NSString*) vSFXName Loop: (BOOL) vLoop
    {
        NSError *error;
    
        NSBundle* bundle = [NSBundle mainBundle];
    
        NSString* bundleDirectory = (NSString*)[bundle bundlePath];
    
        NSURL *url = [NSURL fileURLWithPath:[bundleDirectory stringByAppendingPathComponent:vSFXName]];
    
        AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    
        if(vLoop)
            audioPlayer.numberOfLoops = -1;
        else
            audioPlayer.numberOfLoops = 0;
    
        BOOL success = YES;
    
        if (audioPlayer == nil)
        {
            success = NO;
        }
        else
        {
            success = [audioPlayer play];
        }
        return success;
    }
    

    Then to use just:

    [self playSoundFXnamed:@"someAudio.mp3" Loop: NO];
    

    If you're gonna loop then you need to take your AVAudioPlayer *audioPlayer out into your class to be able to stop the sound.. Which you dont if you just want a short sound.

    Use ARC... and I never did do anything with the NSError, so use it if ya like...

    0 讨论(0)
提交回复
热议问题