swift play noise even if phone is locked or in background - ios

I have a Countdown Timer app that counts down but does not beep and crashes when it hits 0 if the phone is locked or on a different app.
I found this 3 year old link for Objective C objective c play music in the background
but the only thing I could figure was to add "Application does not run in background to Info.plist and set it to "No"
Here is my function to play it:
func timerBeep() {
// preperation
AVAudioSession.sharedInstance().setCategory("AVAudioSessionCategoryPlayback", error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
// play sound
var error: NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: sound, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
}

Related

Sound file doesn't play when followed by exit(0) in Swift 2.0

OK, I want to have code that plays a certain sound file if the user quits, or if the user is eliminated from the game. After that, I want to exit the app.
So far, I have this:
#IBAction func justQuit(sender: UIButton) // user just wants to quit game
{
let path = NSBundle.mainBundle().pathForResource
("PowerDown3", ofType:"wav")
let url = NSURL(fileURLWithPath: path!)
do
{
let sdfx2 = try AVAudioPlayer(contentsOfURL: url)
PowerDown3 = sdfx2
sdfx2.play()
} catch { /* couldn't load file */}
exit(0)
}
I have the closing bracket to the above function, and have initialized the variables needed. I tried the code without the exit(0) command, and it plays the sound file, but when I include exit(0) to exit the app, the sound file does not play at all. The point is to exit the app, but before exiting, to play the
sound file.
I even included a timer code to try to delay the exit(0) command, but still the sound file doesn't play. The timer didn't seem to make a difference to delay the exiting action.

Swift 2.0 Playing custom sound in app delegate while in background mode

I am using Google Cloud messaging to push notifications to my iOS app written in Swift 2.0 xCode 7.1. GCM doesn't allow custom notification sounds.
See here: https://developers.google.com/cloud-messaging/http-server-ref
So I turned off the default sound and am trying to play a sound whenever 'didReceiveRemoteNotification' is called. My problem is the sound is not playing when in background mode..however if I put the code(below) in 'didFinishLaunchingWithOptions' it works perfectly, just not when I want it to play.
I have added the background more in info.plist. Like I said its working just not when a push notification arrives.
let alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("GMNotification", ofType: "wav")!)
print(alertSound)
//var error:NSError?
do {
try self.audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, fileTypeHint:nil)
self.audioPlayer.prepareToPlay()
self.audioPlayer.play()
print("PLAY !!!")
} catch {
print("Error ???")
}
Can anyone help please?
You must create a shared instance "Singelton" to play sound. Refer back to:
Swift - AVAudioPlayer, sound doesn't play correctly
This should tell you how it can be done

AVAudioEngine stops device's background audio

I am using an AVAudioEngine object, that has many AVAudioPlayerNodes attached to it. The audio all works fine, except it stops any audio that the iPhone is playing in the background (i. e. from iTunes or another music app).
When my app is opened, it stops any other background audio. Is there a way to allow background audio to continue to play? Even when my app is using AVAudioPlayerNodes to play audio itself?
Music App has it's own audioSession, that makes audio engine stops, i had that problem too, please restart after music app.
func stepB_startEngine(){
if engine.running == false {
do { try engine.start() }
catch let error {
print(error)
}
}
}
setup audioSettion also:
func setUpAudioSession(){
do {
try AVAudioSession.sharedInstance().setCategory(.ambient, options: .mixWithOthers)
try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
} catch let error {
print(error)
}
}

Mute other application sound when my application is playing sound ios

I am new in playing audio sound. I am stuck in problem where I wanted to mute other application sound when my application is playing music sound and resume back when I stop my application's sound. I searched a lot but I could not get any solution.
Below code is for playing audio sound:-
var url:NSURL = NSURL.fileURLWithPath(NSBundle.mainBundle().pathForResource("\(soundFile)", ofType: "mp3")!)!
let audioPlayer1 = AVAudioPlayer(contentsOfURL: url, error: nil)
audioPlayer1!.numberOfLoops = -1
if(audioPlayer1 == nil)
{
println("error in playing")
}
else
{
audioPlayer1!.play()
}
You need to configure the AVAudioSession category :
AVAudioSession Class Reference : http://goo.gl/rh7CX7 . Look for which fit the most for your application. You only need to set it once in your code (make sure it's called).
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategorySoloAmbient, error: nil) // AVAudioSessionCategorySoloAmbient is default
AVAudioSession.sharedInstance().setActive(true, error: nil)
If it didn't help, please provide more information (which app isn't mute ? what have you tried ? ...).

AVAudioSession overrideOutputAudioPort & localNotifications in mute

Hello I tried the various solutions to similar questions but couldnt get my code to work. I have the following function that I call in my app:
func PlaySound (WhenToPlaySound:String) {
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
if WhenToPlaySound == "BeginningOfRound" {
if UIApplication.sharedApplication().applicationState == UIApplicationState.Background {
soundnotification.soundName = "BoxingBellStart.wav"
UIApplication.sharedApplication().scheduleLocalNotification(soundnotification)
println("timer is done in background mode")
} else {
// Load Sound
soundlocation = NSBundle.mainBundle().URLForResource("BoxingBellStart", withExtension: "wav")!
player = AVAudioPlayer(contentsOfURL: soundlocation, error: &Error)
player.volume = 1.0
// Play Sound
player.play()
println("timer is done in active mode")
}
} else {
if UIApplication.sharedApplication().applicationState == UIApplicationState.Background {
soundnotification.soundName = "Boxing.wav"
UIApplication.sharedApplication().scheduleLocalNotification(soundnotification)
println("timer is done in background mode")
} else {
// Load Sound
soundlocation = NSBundle.mainBundle().URLForResource("Boxing", withExtension: "wav")!
player = AVAudioPlayer(contentsOfURL: soundlocation, error: &Error)
player.volume = 1.0
// Play Sound
player.play()
println("timer is done in active mode")
}
}
}
Mostly it works except two things:
1. I can't seem to override the speaker volume. I want the system volume to be full volume before I play my sound.
The LocalNotifications that are set to activate when the app is in background mode only pay when the device isn't muted.
To address the first problem I wanted to the following but didnt know how to use it:
AVAudioSession.sharedInstance().overrideOutputAudioPort(<#portOverride: AVAudioSessionPortOverride#>, error: <#NSErrorPointer#>)
Thanks in advance,
Ace
overrideOutputAudioPort affects the audio routing, not the volume.
When you say that you want to "override the speaker volume", I assume that you mean you want to control the system output volume from you app code. This is not possible as Apple believes that output volume should remain in the control of the user at all times.
AVAudioPlayer's volume property sets the volume relative to the system output level. It defaults to 1.0 (player volume == system volume). You can't turn it up higher, spinal-tap style, to 1.1...
See also my answer here ... if you want to take control of the system volume, you will need the user interface provided by MPVolumeView.
Similarly regarding your notifications - if the user has muted the device, your app won't be able to ignore that.
update
regarding notifications, it isn't as straightforward as I suggested. It might work if you set the AVAudioSession category to AVAudioSessionCategoryPlayback (and read the apple docs on this setting).
When using this category, your app audio continues with the Silent switch set to silent or when the screen locks
You may also need to add 'audio' to UIBackgroundModes in your info.plist.

Resources