LettersBa
LettersBa

Reputation: 767

Play audio with AVAudioPlayer inside NSObject class

To organize things , I decided to create a class called SoundPlayer where will run all audio files from my app. (This would avoid having many duplicate codes)

SoundPlayer.h

#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#include <AudioToolbox/AudioToolbox.h>

@interface SoundPlayer : NSObject <AVAudioPlayerDelegate>

@property (strong,nonatomic) AVAudioPlayer *backgroundMusicPlayer;

-(void)PlaySound:(NSString*)name extension:(NSString*)ext loops:(int)val;

@end

SoundPlayer.m

#import "SoundPlayer.h"

@implementation SoundPlayer

-(void)PlaySound:(NSString *)name extension:(NSString *)ext loops:(int)val{

    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:name ofType:ext];
    NSURL *soundPath = [[NSURL alloc] initFileURLWithPath:soundFilePath];
    NSError *error;
    self.backgroundMusicPlayer = [[AVAudioPlayer alloc]
                                  initWithContentsOfURL:soundPath error:&error];
    self.backgroundMusicPlayer.numberOfLoops = val;
    [self.backgroundMusicPlayer prepareToPlay];
    [self.backgroundMusicPlayer play];
}

@end

This code is very simple, and seems to work great. When the user open my app for first time I want to play a sound, for this I call this class inside didFinishLaunchingWithOptions, like this:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    SoundPlayer *sound = [[SoundPlayer alloc] init];
    [sound PlaySound:@"preview" extension:@"mp3" loops:0];

    return YES;//Diz que o retorno esta ok!
}

The problem is that the sound is not being executed (Now, if I copied all the code within the SoundPlayer class and put into the class I would use, the sound runs perfectly) what's the problem ?

Upvotes: 2

Views: 342

Answers (2)

try this out:

AppDelegate.h

 #import <UIKit/UIKit.h>
 #import "SoundPlayer.h"

 @interface AppDelegate : UIResponder <UIApplicationDelegate>
   @property (strong, nonatomic) UIWindow *window;
   @property(strong,nonatomic) SoundPlayer * soundPlayer;
@end

AppDelegate.m

#import "AppDelegate.h"
#import "SoundPlayer.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.soundPlayer = [[SoundPlayer alloc] init];
    [self.soundPlayer PlaySound:@"preview" extension:@"mp3" loops:0];
    return YES;
}

Upvotes: 1

Gordon Childs
Gordon Childs

Reputation: 36072

Your SoundPlayer class is going out of scope and being deallocated, which silences the sound.

Assign it to a member variable in your app delegate:

self.sound = [[SoundPlayer alloc] init];
[sound PlaySound:@"preview" extension:@"mp3" loops:0];

Upvotes: 4

Related Questions