ios - 重新编辑: Audio not playing in real ios Device but playing in simulated devices in Swift2

标签 ios swift avfoundation avaudioplayer swift2

这是我在 swift2 中的代码,绝对没有错误,我在真实设备上运行但没有声音?没有异常(exception),没有什么我错过了什么?

  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 设置正确的音频路由。更多信息请参见上面的视频。

关于ios - 重新编辑: Audio not playing in real ios Device but playing in simulated devices in Swift2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31773093/

相关文章:

ios - 在 Swift 中动画 drawRect 圆

ios - Objective-C:淡化 GUI

ios - 无法在 ios swift Promisekit 上使用 then

java - Swift 的 CharacterSet.decimalDigits 和 unicodeScalars 在 Kotlin 中的等价物是什么

ios - 无法在表格 View 单元格中容纳多行

Xamarin.Forms 中的 Android CoordinatorLayout

JSONSerialization 与 URLSession.shared.dataTask 错误

ios - AVFoundation 位置音频无法在 iOS 设备上运行

ios - 使用 AVPlayer 从远程 URL 播放视频

ios - 使用 swift 2.0 代码 Xcode 7.1 IOS 9.1 播放嵌入式声音