如何在iOS应用程序中使用Swift 2音频?

前端之家收集整理的这篇文章主要介绍了如何在iOS应用程序中使用Swift 2音频?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_403_1@我使用SpriteKit和 Swift在Xcode 7测试版上制作了一个游戏,我试图把Audio放在它里面,但是它不是可以使用的,因为Xcode发现了3个错误,我是初学者,我不知道如何解决它们.
  1. import AVFoundation
  2.  
  3. var audioPlayer = AVAudioPlayer()
  4.  
  5.  
  6. func playAudio() {
  7. // Set the sound file name & extension
  8. var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Flip 02",ofType: "wav")!)
  9.  
  10. // Preperation
  11. AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback,error: nil)
  12. AVAudioSession.sharedInstance().setActive(true,error: nil)
  13.  
  14. // Play the sound
  15. var error: NSError?
  16. audioPlayer = AVAudioPlayer(contentsOfURL: alertSound,error: &error)
  17. audioPlayer.prepareToPlay()
  18. audioPlayer.play()
  19. }

代码错误在这里:

代码1:

  1. AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback,error: nil)

错误1:

Extra argument ‘error’ in call

代码2:

  1. AVAudioSession.sharedInstance().setActive(true,error: nil)

错误2:

Extra argument ‘error’ in call

代码3:

  1. audioPlayer = AVAudioPlayer(contentsOfURL: alertSound,error: &error)

错误3:

Cannot find an initializer for type ‘AVAudioPlayer’ that accepts an argument list of type ‘(contentsOfURL: NSURL,error: inout NSError?)’

你的贡献可能会帮助我.谢谢.

解决方法

使用内部的功能捕捉和使用尝试的投掷:
  1. var audioPlayer = AVAudioPlayer()
  2.  
  3. func playAudio() {
  4. do {
  5. if let bundle = NSBundle.mainBundle().pathForResource("Flip 02",ofType: "wav") {
  6. let alertSound = NSURL(fileURLWithPath: bundle)
  7. try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
  8. try AVAudioSession.sharedInstance().setActive(true)
  9. try audioPlayer = AVAudioPlayer(contentsOfURL: alertSound)
  10. audioPlayer.prepareToPlay()
  11. audioPlayer.play()
  12. }
  13. } catch {
  14. print(error)
  15. }
  16. }

有关完整的Swift 2错误处理说明,请参见this answer.

猜你在找的iOS相关文章