0
votes

It´s only possible to give the AVAudioPlayer an URL of the file to play via it´s init method. And as I understand it if one want´s to play another file, the old instance needs to be stopped from playing, and a new instance of AVAudioPlayer initialized with the URL to the new audiofile to play.

But this is making it hard cause I have a navigation controller, and when the user leaves the player screen the sound should keep playing, and it does. But when the user selects a new audio file to play from the tableview a new instance of the viewController and AVAudioPlayer is initalized and I have no way of stopping the old from playing. How do I get this working?

1
You need to keep track of the AVAudioPlayer somewhere (and since you only want to play one file at a time, you need to keep track of only one AVAudioPlayer), either in a singleton, App delegate like an answer suggested, or in the table view itself.Khanh Nguyen

1 Answers

0
votes

You can do something like this

In your v1AppDelegate.h file add,

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

@interface v1AppDelegate : UIResponder <UIApplicationDelegate>
{
    AVAudioPlayer *myAudioPlayer;
}
@property (nonatomic, retain) AVAudioPlayer *myAudioPlayer;
@property (strong, nonatomic) UIWindow *window;

@end

Now in your v1AppDelegate.m file add this

#import "v1AppDelegate.h"
#import <AVFoundation/AVFoundation.h>
#include <AudioToolbox/AudioToolbox.h>

@implementation v1AppDelegate

@synthesize window = _window;
@synthesize myAudioPlayer;


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

    //start a background sound
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Startsound" ofType: @"m4a"];
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath ];    
    myAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
    myAudioPlayer.numberOfLoops = -1; //infinite loop
    [myAudioPlayer play];


    // Override point for customization after application launch.
    return YES;
}

If you wish to stop or start this music from anywhere else in your code then simply add this

#import "v1AppDelegate.h"    
- (IBAction)stopMusic
{
    v1AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    [appDelegate.myAudioPlayer stop];
}

- (IBAction)startMusic
{
    v1AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    [appDelegate.myAudioPlayer play];
}