i am new to iOS/Xcode/Swift, need a solution for inserting an audio file into the background of a page, file will be playing while people reading the page.
2 Answers
I’d advice you to take a look at: AVAudioPlayer not playing audio in Swift for the how do I get a working audio player. For the “in the background” part of your questions I’ve found iOS swift streaming app does not play music in background mode after a minute of searching. I hope these 2 Questions can help you further
i had the same problem, what i did was create the AVAudioPlayer in my AppDelegate, then create an AppDelegate instance, that way the AVAudioPlayer instance will be global, in my desired ViewController and in the viewWillAppear method i called the [player play];
method if you want to pause the music when the view disappears, like when you move to another ViewController, just call the [player pause];
method in the viewWillDisappear.
what your AppDelegate.h file should look like:
#import <UIKit/UIKit.h>
@import AVFoundation;
@interface AppDelegate : UIResponder <UIApplicationDelegate, AVAudioPlayerDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (retain,nonatomic) AVAudioPlayer *myPlayer;
@property (retain, nonatomic) AVAudioSession *session;
@end
what your AppDelegate.m file should look like:
(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSError *error;
session = [AVAudioSession sharedInstance];
[session setCategory: AVAudioSessionCategorySoloAmbient error:&error];
NSString *path = [[NSBundle mainBundle] pathForResource:kSongTitle ofType:kSongFormat];
NSURL *pathURL = [NSURL fileURLWithPath:path];
myPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:pathURL error:&error];
[myPlayer setNumberOfLoops:-1.0];//for infinite loops set the value to a negative number..
[myPlayer setVolume:0.7];//this value varies between 0 and 1..
return YES;
}
your AppDelegate instance in your desired ViewController's .h file:
@property (nonatomic, strong) AppDelegate *appDelegate;
your viewWillAppear and viewWillDisappear methods:
-(void) viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[appDelegate.myPlayer pause];
}
-(void) viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[appDelegate.myPlayer play];
}
also if you want to handle interruptions, say like a phone call was received, just call the [myPlayer pause];
in the applicationWillResignActive
method in the AppDelegate.m file. To resume the audio just call the [myPlayer prepareToPlay];
and [myPlayer play];
in the applicationDidBecomeActive
method in the AppDelegate.m file.
P.S: I am using Objective-C.

- 19
- 7