Подтвердить что ты не робот

Лучший способ воспроизведения простого звукового эффекта в iOS

Я нахожу несколько противоречивых данных о воспроизведении звуков в iOS. Мне было интересно, сможет ли кто-нибудь указать мне лучший способ воспроизвести просто "звуковой укус" пинга каждый раз, когда пользователь прикасается к экрану.

Спасибо!

4b9b3361

Ответ 1

Это лучший способ воспроизведения простого звука в 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);

Ответ 2

Я использую это:

Заголовочный файл:

#import <AudioToolbox/AudioServices.h>

@interface SoundEffect : NSObject
{
    SystemSoundID soundID;
}

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

@end

Исходный файл:

#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

Вам нужно будет создать экземпляр SoundEffect и вызвать вызов метода на нем.

Ответ 3

(Небольшая поправка к правильному ответу на уход за звуком)

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);
});

Ответ 4

Вы можете использовать AVFoundation или AudioToolbox

Вот два примера, которые используют библиотеки отдельно.