Wolfgang Fleck Wolfgang Fleck - 2 months ago 9
iOS Question

AVAudioPlayer not playing when outsourced in class

I'm relatively new to iOS development, but not new to (object-orientated) programming in general.

I am programming a kind of recorder app, and I need your help when it comes to this:
I've tried to outsource the AVAudioPlayer object into an extra class,

AudioPlayer
, so I can access it from different controllers.
I does everything it should, except playing any sound.
Heres a simplified project of my problem:

ViewController.m
:

- (IBAction)playButtonPressed:(id)sender
{
NSArray *pathComponents = [NSArray arrayWithObjects:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],@"AudioMemo.m4a",nil];
NSURL *fileURL = [NSURL fileURLWithPathComponents:pathComponents];

AudioPlayer *myPlayer = [[AudioPlayer alloc] init];
[myPlayer myPlayAudio:fileURL];
}


The rest of the file is empty/standard.

ViewController.h
:

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

@interface ViewController : UIViewController

@property (strong, nonatomic) IBOutlet UIButton *playButton;

- (IBAction)playButtonPressed:(id)sender;

@end


AudioPlayer.m
:

#import "AudioPlayer.h"

@implementation AudioPlayer

@synthesize aPlayer;

-(id) myPlayAudio:(NSURL *)myURL
{
NSLog(@"in myPlayAudio; before play");

NSError *err = nil;

AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:NULL];
[audioSession setActive:YES error:&err];
if(err)
{
NSLog(@"%@",err);
}
aPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:myURL error:&err];
if(err)
{
NSLog(@"%@",err);
}
[aPlayer play];

NSLog(@"in myPlayAudio; after play");

//[audioSession setActive:NO error:&err];

return err;
}

@end


AudioPlayer.h
:

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

@interface AudioPlayer : NSObject <AVAudioPlayerDelegate> {
AVAudioPlayer *aPlayer;
}

@property (nonatomic, strong) AVAudioPlayer *aPlayer;

-(id) myPlayAudio:(NSURL *) myURL;

@end


I've added
AudioToolbox Framework
, activated iTunes file sharing in the .plist file and loaded an
AudioMemo.m4a
file to the documents folder.

It shows the two NSLogs (before + afterplay), but doesn't make any noise. I know I didn't enable the loudspeaker of the iPhone, i wanted to keep it simple in this case.
Of course I checked volume, silent mode etc.

When I make everything local (put everything in the
ViewController.m
), like most of the tutorials on the net, it works fine.

I searched, but didn't find this problem before, so I would be very thankful if anybody could help me.

Answer

As I see you are using ARC, so this object:

AudioPlayer *myPlayer = [[AudioPlayer alloc] init];

is released shortly after you allocated it. Keep it in a property instead of a local variable and it should work.

Comments