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?
On iPhone, iPad, or iPod touch: Go to Settings > Accessibility > Audio/Visual, then turn on Mono Audio. On Apple Watch: Go to Settings > Accessibility, then turn on Mono Audio below Hearing. On Mac: Choose Apple menu > System Preferences, click Accessibility, click Audio, then select “Play stereo audio as mono.”
You can also set up your phone's Dual Audio feature, which will allow you to connect two different Bluetooth headphones simultaneously. Get an audio splitter with two output jacks and plug it into your device's AUX output. Plug both pairs of one-side working earbuds into the audio splitter's output jacks.
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")
}
}
}
You can check if audio is being played through headphones before you play that sound with this function
func headsetPluggedIn() -> Bool {
let route = AVAudioSession.sharedInstance().currentRoute
return (route.outputs ).filter({ $0.portType == AVAudioSessionPortHeadphones }).count > 0
}
And you can change the audio to left or right ear with AVAudioPlayer's pan property like this
myAudioPlayer.pan = 1
set it to -1 for left ear or 1 for right ear
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With