重新编辑:音频未在真实 ios 设备中播放,但在 Swift2 中的模拟设备中播放

ReEdited : Audio not playing in real ios Device but playing in simulated devices in Swift2

这是我在 swift2 中的代码,绝对没有错误,我在真实设备上 运行 但是没有声音?没有例外,我是不是遗漏了什么?

  import UIKit
    import AVFoundation

class ViewController: UIViewController {


    @IBAction func play() {
        audioPlayer.play()
    }

    var audioPlayer : AVAudioPlayer!



    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


         let alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("drum", ofType: "mp3")!)

        do {
            audioPlayer = try AVAudioPlayer(contentsOfURL: alertSound)
            audioPlayer.prepareToPlay()
            audioPlayer.volume = 1.0
            audioPlayer.play()
            print("yes")

        }catch _ {
            audioPlayer = nil
        }
      }
}

我从 Apple WWDC 大会的一个视频中发现了问题所在

http://adcdownload.apple.com/videos/wwdc_2010__hd/session_412__audio_development_for_iphone_os_part_1.mov(只能在 Safari 上查看)

问题出在音频路由上,当我插入耳机时,我可以听到真实设备的声音。 更改路由后,我们需要使用 AVAudioSession 设置正确的音频路由。上面那个视频中有更多信息。

导入 AVFoundation 并将其添加到您的 viewDidLoad:

var 错误 = NSErrorPointer() AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, 错误: err)