首页 文章

Swift - AVAudioPlayer 没有播放声音

提问于
浏览
0

我有一个名为speeding.mp3的声音,我试图通过在类的根目录中创建一个 AVAudioPayer 实例:

let speedingAudioPlayer = try! AVAudioPlayer(contentsOfURL: NSBundle.mainBundle().URLForResource("speeding", withExtension: "mp3")!)

然后,当我运行应用程序时,它会抛出错误,但我不知道为什么会发生这种情况。 speeding.mp3文件位于 Build Phases 的 Bundle Resources 下拉列表中,因此它应该很好。如果我尝试在模拟器中打印出 URL 并将其粘贴到 Safari 中,它会加载并正常播放文件。我将 AVFoundation 导入到类中,并将框架导入到项目中。

3 回答

  • 1

    使用此代码段调试错误,

    if let URL = NSBundle.mainBundle().URLForResource("speeding", withExtension: "mp3") {
        do {
            let speedingAudioPlayer = try AVAudioPlayer(contentsOfURL: URL)
        } catch  let error as NSError {
            print(error.localizedDescription)
        }
    } else {
        print("No such file exist")
    }
    
  • 1

    我发现另一个问题是 var 放在了课外,否则它会被电话解除分配。

    AVAudioPlayer 对象声音没有播放 - Swift

  • 1
    import UIKit
    import AVFoundation
    
    class CustomAudioPlayer {
      var audioPlayer : AVAudioPlayer!
    
      override func viewDidLoad() {
        super.viewDidLoad()
        playSound("sound_file_name")
      }
    
      func playSound(soundName: String)
      {
        let alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundName, ofType: "mp3")!)
        do{
            audioPlayer = try AVAudioPlayer(contentsOfURL:alertSound)
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        }catch {
            print("Error getting the audio file")
        }
      }
    }
    

    尝试使用此代码播放声音。

相关问题