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

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

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

但是现在,我想只在右耳或左耳播放某种声音-phone,如果播放器使用的是头phones。 这可能使用 AVFoundation 吗?

这就是您向左或向右播放声音的方式。

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

    }

}

您可以在使用此功能播放声音之前检查是否正在通过耳机播放音频

func headsetPluggedIn() -> Bool {
    let route = AVAudioSession.sharedInstance().currentRoute
    return (route.outputs ).filter({ [=10=].portType == AVAudioSessionPortHeadphones }).count > 0
}

你可以像这样用 AVAudioPlayer 的声像 属性 将音频切换到左耳或右耳

myAudioPlayer.pan = 1

左耳设置为 -1,右耳设置为 1