Suhas Suhas - 1 year ago 52
iOS Question

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?

Any help or advice is greatly appreciated.

Answer Source

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

import UIKit
import AVFoundation

class ViewController: UIViewController {

    override func viewDidLoad() {
        // Do any additional setup after loading the view, typically from a nib.

    override func didReceiveMemoryWarning() {
        // Dispose of any resources that can be recreated.

    var audioPlayer = AVAudioPlayer()
    let alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("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(contentsOfURL: alertSound) //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
        } catch  {


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download