2016-08-22 14 views
5

배경 음악이 계속 재생되고 사용자 상호 작용을 기반으로 여러 가지 다른 소리가 재생되는 게임 (Swift 2.0, iOS9)을 만들었습니다.AVFoundation을 사용하여 신속하게 2.0의 헤드폰 한쪽 귀에 사운드 노트를 재생하는 방법이 있습니까?

하지만 이제는 플레이어가 헤드 폰을 사용하고 있다면 오른쪽 또는 왼쪽 이어폰에서만 특정 사운드를 재생하고 싶습니다. AVFoundation을 사용하면 가능합니까?

도움이나 조언을 크게 듣습니다.

답변

6

왼쪽 또는 오른쪽으로 사운드를 재생하는 방법입니다.

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

    } 

} 
+0

예를 위해 왼쪽 귀 또는 1 -1로,이 일했다. 고맙습니다. .. – Suhas

+0

나는 이걸 두 번 upvote 할 수 있으면 좋겠어. 모든 코멘트는 매우 유용했고 코드를 읽기 쉽도록 만들었습니다. 아주 좋은 대답, 다시 한번 감사드립니다. 또한 성명서의 필요성을 표시해주십시오. audioPlayer.prepareToPlay() – Suhas

1

이 기능

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

와 함께 그 소리를 재생 그리고이

같은 AVAudioPlayer의 팬 속성과 귀 왼쪽 오디오 또는 권리를 변경하기 전에 오디오 헤드폰을 통해 재생되는 경우가 확인할 수 있습니다
myAudioPlayer.pan = 1 

세트는 오른쪽 귀

+0

이것은 매우 유용했습니다. 사운드를 재생하기 전에 헤드폰을 확인하는 것에 대해서는 생각하지 않았습니다. 하지만 당신이 만든 요점은 많은 의미를가집니다. – Suhas