AVaudioPlayer returns 无

AVaudioPlayer returns nil

我不知道该怎么办了。下面的代码在 audioPlayer = AVAudioPlayer(contentsOfURL: newPath, error: &err)

时崩溃

这是我传递的文件的 URL file:///var/mobile/Containers/Data/Application/1174C37F-CB78-4AB5-9C69-E1B906B48D97/Documents/Rocket_002.mp3

我也试过通过 NSData 传递文件,但它也不起作用。

import AVFoundation



class Player: NSObject, AVAudioPlayerDelegate {
var audioPlayer: AVAudioPlayer = AVAudioPlayer()


func playPodcastAt(path: String) {
    var err: NSError?
    let url = NSURL(string: path)
    if let newPath = url {
    println("attempting to play")
    audioPlayer = AVAudioPlayer(contentsOfURL: newPath, error: &err)
    if let error = err {
        println("audioPlayer error \(error.localizedDescription)")
    }
    println("Setting delegate")
    audioPlayer.delegate = self
    println("Playing")
    audioPlayer.prepareToPlay()
    audioPlayer.play()

        }
    }
}

这是我的 ViewController 中的函数,它调用上面的 class

    @IBAction func playEpisode(sender: UIButton) {
    let indexPath = NSIndexPath(forRow: sender.tag, inSection: 0)

    let object = self.objectAtIndexPath(indexPath)
    if let result = object {
    if let isDownloaded = result["isDownloaded"] as? String {
        if isDownloaded == "yes" {
            if let url = result["localPath"] as? String {
                println("Attempting to play \(url)")
                 audioPlayer.playPodcastAt(url)
            }
        }
    }
  }
}

编辑:我尝试将文件名保存在我的数据库中,并使用下面的代码在主包中检索文件。还是不行:

 import AVFoundation



class Player: NSObject, AVAudioPlayerDelegate {
var audioPlayer: AVAudioPlayer = AVAudioPlayer()


func playPodcastAt(path: String) {
    println("path \(path)")
    let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(path, ofType: "mp3")!)
    var err: NSError?
    audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &err)
    if let error = err {
        println("audioPlayer error \(error.localizedDescription)")
    }
    println("Setting delegate")
    audioPlayer.delegate = self
    println("Playing")
    audioPlayer.prepareToPlay()
    audioPlayer.play()

        }
    }

编辑 2:下面的两个回复让我想到尝试这种方法,它奏效了:

 import AVFoundation



class Player: NSObject, AVAudioPlayerDelegate {
var audioPlayer: AVAudioPlayer = AVAudioPlayer()


func playPodcastAt(path: String) {
    println("path \(path)")
    if let directoryURL = NSFileManager.defaultManager()
        .URLsForDirectory(.DocumentDirectory,
            inDomains: .UserDomainMask)[0]
        as? NSURL {

    let newPath = directoryURL.URLByAppendingPathComponent(path)
    println(newPath)
    var err: NSError?
    audioPlayer = AVAudioPlayer(contentsOfURL: newPath, error: &err)
    if let error = err {
        println("audioPlayer error \(error.localizedDescription)")
    }
    println("Setting delegate")
    audioPlayer.delegate = self
    println("Playing")
    audioPlayer.prepareToPlay()
    audioPlayer.play()

        }
    }

}

问题是 NSURL(string:) 仅用于网络链接。您必须对本地资源文件使用 NSURL(fileURLWithPath:)。像这样尝试:

if let url = NSURL(fileURLWithPath: path) {
    // you can use your local resource file url here
    var error:NSError?
    // you can also check if your local resource file is reachable
    if url.checkResourceIsReachableAndReturnError( &error ) {
         // url is reacheable
    } else if let error = error {
        println(error.description)
    }
}

// 也许可以为您的播放器尝试这个 Class。如果您的文件不是 m4a,您将需要更改扩展名。

class 播放器:NSObject, AVAudioPlayerDelegate {

var audioPlayer: AVAudioPlayer = AVAudioPlayer()

func playPodcastAt(path: String) {

    if let soundUrl = NSBundle.mainBundle().URLForResource(path, withExtension:".m4a") {

        var err: NSError?
        audioPlayer = AVAudioPlayer(contentsOfURL: soundUrl, error: &err)
        if let error = err {
            println("audioPlayer error \(error.localizedDescription)")
        }
        audioPlayer.numberOfLoops = -1  // -1 runs forever, 0 runs once, 1 runs twice, etc.
        audioPlayer.volume = 1.0
        //audioPlayer.prepareToPlay()
        audioPlayer.play()

    } else {

        println("Path for file not found for audioPlayer.")
    }

}

}