在iOS中播放简单音效的最佳方式

Jam*_*nay 20 iphone objective-c ios

我发现了许多关于在iOS中播放声音的冲突数据.我想知道是否有人能指出我每次用户触摸屏幕时只播放一个简单的"ping"声音的最佳方式.

谢谢!

tig*_*ero 29

我用这个:

头文件:

#import <AudioToolbox/AudioServices.h>

@interface SoundEffect : NSObject
{
    SystemSoundID soundID;
}

- (id)initWithSoundNamed:(NSString *)filename;
- (void)play;

@end
Run Code Online (Sandbox Code Playgroud)

源文件:

#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
Run Code Online (Sandbox Code Playgroud)

您需要创建一个SoundEffect实例并直接调用方法play.

  • 但这不适用于ARC.要在ARC中使用它,您必须添加一个完成回调函数,您可以在其中处置systemound.如果你在dealloc中这样做,声音会立即被杀死:`AudioServicesAddSystemSoundCompletion(soundID,NULL,NULL,completionCallback,(__ bridge_retained void*)self);`喜欢这个例子 (2认同)

Ant*_* MG 25

这是在iOS中播放简单声音的最佳方式(不超过30秒):

//Retrieve audio file
NSString *path  = [[NSBundle mainBundle] pathForResource:@"soundeffect" ofType:@"m4a"];
NSURL *pathURL = [NSURL fileURLWithPath : path];

SystemSoundID audioEffect;
AudioServicesCreateSystemSoundID((__bridge CFURLRef) pathURL, &audioEffect);
AudioServicesPlaySystemSound(audioEffect);

// call the following function when the sound is no longer used
// (must be done AFTER the sound is done playing)
AudioServicesDisposeSystemSoundID(audioEffect);
Run Code Online (Sandbox Code Playgroud)


Oxc*_*cug 10

(对正确处理音频的正确答案的小修改)

NSString *path  = [[NSBundle mainBundle] pathForResource:@"soundeffect" ofType:@"m4a"];
NSURL *pathURL = [NSURL fileURLWithPath : path];

SystemSoundID audioEffect;
AudioServicesCreateSystemSoundID((__bridge CFURLRef) pathURL, &audioEffect);
AudioServicesPlaySystemSound(audioEffect);
// Using GCD, we can use a block to dispose of the audio effect without using a NSTimer or something else to figure out when it'll be finished playing.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    AudioServicesDisposeSystemSoundID(audioEffect);
});
Run Code Online (Sandbox Code Playgroud)