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

时间:2016-08-22 21:12:12

标签: ios swift ios9 avfoundation core-audio

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

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

2 个答案:

答案 0 :(得分: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")
        }

    }

}

答案 1 :(得分:1)

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

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

您可以使用AVAudioPlayer的pan属性将音频更改为左耳或右耳

myAudioPlayer.pan = 1

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