AVAudioPlayer没有在Swift中播放音频

Ken*_*eth 9 cocoa-touch avfoundation avaudioplayer ios swift

我在一个非常简单的单视图Swift应用程序中有这个代码ViewController:

var audioPlayer = AVAudioPlayer()

@IBAction func playMyFile(sender: AnyObject) {

    let fileString = NSBundle.mainBundle().pathForResource("audioFile", ofType: "m4a")
    let url = NSURL(fileURLWithPath: fileString)
    var error : NSError?
    audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
    audioPlayer.delegate = self
    audioPlayer.prepareToPlay()
    if (audioPlayer.isEqual(nil)) {
        println("There was an error: (er)")
    } else {
        audioPlayer.play()
        NSLog("working")
    }
Run Code Online (Sandbox Code Playgroud)

我添加了import AVFoundation并且audioPlayer是一个全局变量.当我执行的代码,它打印"工作",所以它使通过没有错误,但没有播放声音.该设备没有沉默.

mat*_*att 18

你的代码有太多错误,以至于苏格拉底方法崩溃了; 它可能是最简单的把它扔出去告诉你:

var player : AVAudioPlayer! = nil // will be Optional, must supply initializer

@IBAction func playMyFile(sender: AnyObject?) {
    let path = NSBundle.mainBundle().pathForResource("audioFile", ofType:"m4a")
    let fileURL = NSURL(fileURLWithPath: path)
    player = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
    player.prepareToPlay()
    player.delegate = self
    player.play()
}
Run Code Online (Sandbox Code Playgroud)

我没有费心去做任何错误检查,但好处是,如果出现问题,你会崩溃.

最后一点,可能相关也可能不相关:并非每个m4a文件都可以播放.例如,高度压缩的文件可能会无声地失败(双关语).

  • @lostinthebits 刚遇到同样的事情。您需要更新您的`ViewController` 类定义以包含`AVAudioPlayerDelegate`,如下所示:`class ViewController: UIViewController, AVAudioPlayerDelegate {` (2认同)

bpo*_*lat 6

这是我的 swift 项目中的一个工作片段。用您的文件名替换“audiofile”。

    var audioPlayer = AVAudioPlayer()
    let audioPath = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("audiofile", ofType: "mp3"))
    audioPlayer = AVAudioPlayer(contentsOfURL: audioPath, error: nil)
    audioPlayer.delegate = self
    audioPlayer.prepareToPlay()
    audioPlayer.play()
Run Code Online (Sandbox Code Playgroud)

您可以从这里下载功能齐全的 Swift 音频播放器应用程序源代码 https://github.com/bpolat/Music-Player


小智 6

重要的是AvPlayer是类成员,而不是在给定的函数中,否则它将超出范围... :)


ful*_*oon 6

我必须声明一个全局玩家变量

var player: AVAudioPlayer!
Run Code Online (Sandbox Code Playgroud)

并将其设置在 viewDidLoad

   override func viewDidLoad() {
        super.viewDidLoad()
        player = AVAudioPlayer()
    }
Run Code Online (Sandbox Code Playgroud)

然后我可以像这样在任何地方播放音频文件:

    func playAudioFile(){
    do {
        if audioFileUrl == nil{
            return 
        }
           try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
           try AVAudioSession.sharedInstance().setActive(true)
           /* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
           player = try AVAudioPlayer(contentsOf: audioFileUrl, fileTypeHint: AVFileType.m4a.rawValue)
           /* iOS 10 and earlier require the following line:
           player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */
           guard let player = player else { return }
           player.play()
        print("PLAYING::::: \(audioFileUrl)")
       }
    catch let error {
           print(error.localizedDescription)
       }
}
Run Code Online (Sandbox Code Playgroud)

}