使用AVFoundation有没有一种方法可以在swift 2.0中的耳机的一个耳朵中播放声音?
问题描述:
我已经创建了一个游戏(Swift 2.0,iOS9),其中连续播放背景音乐,并基于用户交互播放各种其他声音。使用AVFoundation有没有一种方法可以在swift 2.0中的耳机的一个耳朵中播放声音?
但现在,如果玩家正在使用头戴式耳机,我只想在右耳机或左耳机上播放某种声音。 这可能使用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()
}
override func didReceiveMemoryWarning() {
super.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
audioPlayer.play()
} catch {
print("error")
}
}
}
答
您可以检查是否音频正在通过耳机里所播放的声音之前,该功能
func headsetPluggedIn() -> Bool {
let route = AVAudioSession.sharedInstance().currentRoute
return (route.outputs).filter({ $0.portType == AVAudioSessionPortHeadphones }).count > 0
}
,你可以改变的音频左耳或右耳与AVAudioPlayer的这样
pan属性myAudioPlayer.pan = 1
将其设为-1为左耳或1右耳
+0
这是非常有用的。在播放声音之前,我没有想过检查耳机。但是你提出的观点很有道理。 – Suhas
是的,这个工作。非常感谢你.. – Suhas
我希望我可以upvote这两次..所有的评论是非常有用的,它使代码高度可读。非常好的答案,再次感谢。 也可以,请你说明声明的必要性audioPlayer.prepareToPlay() – Suhas