0

I am using the following function to play sound fx in my app. I want to make it so the user can be listening to their iphone music at the same time.

I am using this on multiple view controllers also.. not sure if that will change anything. What is the easiest way to accomplish this?

var audioPlayer = AVAudioPlayer()
func playSound (Sound: String, Type: String) {

    let path = NSBundle.mainBundle().pathForResource(Sound, ofType: Type)!
    let url = NSURL(fileURLWithPath: path)

    do {
        let sound = try AVAudioPlayer(contentsOfURL: url)
        audioPlayer = sound
        sound.play()
    } catch {
        // couldn't load file :(
    }
}
Ryan Claxton
  • 175
  • 1
  • 2
  • 13

1 Answers1

1

You can just do

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)

Update:

Remember to import AVFoundation in the file where you're doing this and also to use error handling since this method throws.

It could be used in something like this for example, passing the responsibility of handling the error upwards.

import AVFoundation

func configureAudioSession() throws {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
}

Or if don't want to handle the error (not recommended), something like:

_ = try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)

You'd need to do this only once (since we're accessing the sharedInstance()), so whenever you're configuring your Audio Session will be a good place to do this.

If you're creating more AVAudioSessions, you'll need to do this for every Audio Session.

fdiaz
  • 2,600
  • 21
  • 27
  • this doesn't work with Swift 2 you need to implement do try catch error handling – Leo Dabus Feb 25 '16 at 02:30
  • where would I put this line? at the top of every view controller that plays sounds? or inside the function? – Ryan Claxton Feb 25 '16 at 04:13
  • Something isnt working thats for sure.. – Ryan Claxton Feb 25 '16 at 04:37
  • Did you Import AVFoundation into your file? – Dan Leonard Feb 25 '16 at 04:54
  • Yes, you need to use error handling, I actually included that in my original response but found it's not really relevant since it's not in the scope of the question. I'll edit my answer to include this info ;) – fdiaz Feb 25 '16 at 16:38
  • 1
    Okay so I added a this line ... "var session: AVAudioSession = AVAudioSession.sharedInstance()" at the top of the starting view controller of my app.. cut and paste the second line of code you gave me into the view did load section.. and it is working now for all view controllers in my app.. Thanks for your help.. as you can see I haven't learned swift properly at all yet. :( sorry – Ryan Claxton Feb 26 '16 at 04:02