Search code examples
iosswiftios9avfoundationcore-audio

Is there a way to play a sound note in only one ear of headphone in swift 2.0 using AVFoundation?


I have created a game (Swift 2.0, iOS9) in which a background music is played continuously and various other sounds are played based on user interaction.

But now, I would like to play a certain sound only in the right or left ear-phone, if the player is using head phones. Is this possible using AVFoundation?


Solution

  • This is how you would play a sound in left or right.

    import UIKit
    import AVFoundation
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            testSound()
        }
    
        var audioPlayer = AVAudioPlayer()
        let alertSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "CheckoutScannerBeep", ofType: "mp3")!) // If sound not in an assest
         //let alertSound = NSDataAsset(name: "CheckoutScannerBeep") // If sound is in an Asset
    
        func testSound(){
            do {
                //        audioPlayer = try AVAudioPlayer(data: (alertSound!.data), fileTypeHint: AVFileTypeMPEGLayer3) //If in asset
                audioPlayer = try AVAudioPlayer(contentsOf: alertSound as URL) //If not in asset
                audioPlayer.pan = -1.0 //left headphone
                //audioPlayer.pan = 1.0 // right headphone
                audioPlayer.prepareToPlay() // make sure to add this line so audio will play
                audioPlayer.play()
            } catch  {
                print("error")
            }
    
        }
    
    }