Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 774
Suhas Avatar asked Aug 22 '16 21:08

Suhas


People also ask

How do you make both headphones sound the same on iPhone?

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.”

How do I get sound through both headphones?

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.


2 Answers

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

    }

}
like image 70
MwcsMac Avatar answered Oct 14 '22 00:10

MwcsMac


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

like image 45
Sam_M Avatar answered Oct 14 '22 00:10

Sam_M