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?
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")
}
}
}