Reproducir sonido en el iPhone con Objective-C 
Reproducir sonido en el iPhone con Objective-C

En http://developer.apple.com hay un ejemplo (BubbleLevel) que tiene la siguiente clase para reproducir sonidos:

Declaración de SoundEffect.h:

#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioServices.h>

@interface SoundEffect : NSObject {
SystemSoundID _soundID;
}

+ (id)soundEffectWithContentsOfFile:(NSString *)aPath;
- (id)initWithContentsOfFile:(NSString *)path;
- (void)play;

@end



Implementación de SoundEffect.m:

#import “SoundEffect.h”

@implementation SoundEffect
+ (id)soundEffectWithContentsOfFile:(NSString *)aPath {
if (aPath) {
return [[[SoundEffect alloc] initWithContentsOfFile:aPath] autorelease];
}
return nil;
}

- (id)initWithContentsOfFile:(NSString *)path {
self = [super init];

if (self != nil) {
NSURL *aFileURL = [NSURL fileURLWithPath:path isDirectory:NO];

if (aFileURL != nil)  {
SystemSoundID aSoundID;
OSStatus error = AudioServicesCreateSystemSoundID((CFURLRef)aFileURL, &aSoundID);

if (error == kAudioServicesNoError) { // success
_soundID = aSoundID;
} else {
NSLog(@”Error %d loading sound at path: %@”, error, path);
[self release], self = nil;
}
} else {
NSLog(@”NSURL is nil for path: %@”, path);
[self release], self = nil;
}
}
return self;
}

-(void)dealloc {
AudioServicesDisposeSystemSoundID(_soundID);
[super dealloc];
}

-(void)play {
AudioServicesPlaySystemSound(_soundID);
}

@end

Que nos prepara el sonido para ser reproducido, el archivo a reproducir viene en la ruta aFileURL, y la referencia al sonido en cuestión es &aSoundID, dicha referencia es la que guardaremos en _soundID, que es el atributo que hace referencia a cada objeto de sonido que creemos.

Y para reproducirlo solo hay que llamar a:

AudioServicesPlaySystemSound(_soundID);

Para usar esta clase en un proyecto, tan solo hay que crear un objeto de la clase y otro de NSBundle. NSBundle representa la ruta de nuestro proyecto (nuestra carpeta de recursos por ejemplo).
Así que los sonidos a ejecutar se meterían en una carpeta Sounds, con la opción de Add existing files.
Y la llamada sería:

SoundEffect *clickSound; //creamos el objeto en el .h de nuestra clase controller

Y en el .m de dicha clase controller reproducimos con:

NSBundle *mainBundle = [NSBundle mainBundle];
clickSound = [[SoundEffect alloc] initWithContentsOfFile:[mainBundle pathForResource:@"tick" ofType:@"caf"]];

Esto reproduce un archivo llamado tick.caf de la carpeta de recursos.



No hay comentarios »

Aún no hay comentarios.

Canal RSS de los comentarios de la entrada. URL para Trackback

Deja un comentario

Tienes que iniciar sesión para escribir un comentario.

---