2016-08-22 11 views
5

मैंने एक गेम (स्विफ्ट 2.0, आईओएस 9) बनाया है जिसमें पृष्ठभूमि संगीत लगातार खेला जाता है और उपयोगकर्ता इंटरैक्शन के आधार पर कई अन्य ध्वनियां बजायी जाती हैं।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

मेरी इच्छा है कि मैं इसे दो बार ऊपर उठा सकूं .. सभी टिप्पणियां बहुत उपयोगी थीं और इसने कोड को अत्यधिक पठनीय बना दिया। एक बहुत अच्छा जवाब, फिर से धन्यवाद। भी, क्या आप कृपया कथन की आवश्यकता को इंगित कर सकते हैं 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

संबंधित मुद्दे