有没有办法在swift 2.0中使用AVFoundation在耳机的一只耳朵中播放声音?

Suh*_*has 6 core-audio avfoundation ios swift ios9

我创建了一个游戏(Swift 2.0,iOS9),其中连续播放背景音乐,并根据用户交互播放各种其他声音.

但是现在,如果播放器使用的是头戴式耳机,我只想在右耳或左耳手机中播放一定的声音.这可能使用AVFoundation吗?

Mwc*_*Mac 7

这就是你如何向左或向右播放声音.

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

    }

}
Run Code Online (Sandbox Code Playgroud)