Best ways to play simple sound effect in iOS

前端 未结 5 579
野性不改
野性不改 2020-11-30 01:54

I\'m finding a number of conflicting data about playing sounds in iOS. What is a recommended way to play just a simple \"ping\" sound bite every time the user touches the sc

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 02:51

    I use this:

    Header file:

    #import 
    
    @interface SoundEffect : NSObject
    {
        SystemSoundID soundID;
    }
    
    - (id)initWithSoundNamed:(NSString *)filename;
    - (void)play;
    
    @end
    

    Source file:

    #import "SoundEffect.h"
    
    @implementation SoundEffect
    
    - (id)initWithSoundNamed:(NSString *)filename
    {
        if ((self = [super init]))
        {
            NSURL *fileURL = [[NSBundle mainBundle] URLForResource:filename withExtension:nil];
            if (fileURL != nil)
            {
                SystemSoundID theSoundID;
                OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)fileURL, &theSoundID);
                if (error == kAudioServicesNoError)
                    soundID = theSoundID;
            }
        }
        return self;
    }
    
    - (void)dealloc
    {
        AudioServicesDisposeSystemSoundID(soundID);
    }
    
    - (void)play
    {
        AudioServicesPlaySystemSound(soundID);
    }
    
    @end
    

    You will need to create an instance of SoundEffect and direct call the method play on it.

提交回复
热议问题