Swift 编程中的 url 文件中没有 运行 AVAudioPlayer

AVAudioPlayer didn't run from url file in Swift Programming

我对 Swift 编程还很陌生,现在已经开始学习几周了。我正在测试 YouTube 教程中的 AVAudioPlayer,它运行良好。这是代码。

let filelocation  = NSString( string: NSBundle.mainBundle().pathForResource(self.navigationItem.title, ofType: "mp3")!)
player = AVAudioPlayer(contentsOfURL: NSURL( fileURLWithPath: filelocation as String)!, error: &error)

那些mp3文件放在项目里所以在本地播放。我将代码更改为以下代码以从 URL 获取 mp3 文件并在此处播放。但是没用。

let url : NSString = "https://ia601409.us.archive.org/20/items/UsaNationalAnthemFromSilo/silosinging-us-anthem_64kb.mp3"
let urlStr : NSString = url.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
player = AVAudioPlayer(contentsOfURL: NSURL( fileURLWithPath: urlStr as String)!, error: &error)

我在 player.prepareToPlay() 处遇到一个错误 "fatal error: unexpectedly found nil while unwrapping an Optional value",值为 "error NSError? domain: "NSOSStatusErrorDomain" - 代码:2003334207 0x00007fc3e3e4b820"

我在想 NSURL(fileURLWithPath: urlStr as String)!是不正确的,所以它只给出零。关于如何纠正它的任何想法!谢谢。

您不能使用 NSURL(fileURLWithPath:) 方法从网络 link 创建 url。从 links 创建 url 时,您需要使用 NSURL(string:) 但您应该使用 dataTaskWithUrl 异步下载数据,如下所示:

import UIKit
import AVFoundation

class ViewController: UIViewController {
    var player:AVAudioPlayer!
    override func viewDidLoad() {
        super.viewDidLoad()
        let link = "https://ia601409.us.archive.org/20/items/UsaNationalAnthemFromSilo/silosinging-us-anthem_64kb.mp3"
        if let linkUrl = NSURL(string: link) {
            println(linkUrl)
            NSURLSession.sharedSession().dataTaskWithURL(linkUrl, completionHandler: { (data, response, error) -> Void in
                dispatch_async(dispatch_get_main_queue()) {
                    println("Finished downloading")
                    // you can use the data! here
                    if let data = data {
                        var error:NSError?
                        self.player = AVAudioPlayer(data: data, error: &error)
                        if let error = error {
                            println(error.description)
                        } else {
                            self.player.prepareToPlay()
                            self.player.play()
                        }
                        // there is data. do this
                    } else if let error = error {
                        println(error.description)
                    }
                }
            }).resume()
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

你必须先预加载mp3,你可以试试这个:

var p: AVAudioPlayer?

override func viewDidLoad() {
        super.viewDidLoad()
        var errorPointer: NSErrorPointer = NSErrorPointer()
        var url = NSURL(string: "https://ia601409.us.archive.org/20/items/UsaNationalAnthemFromSilo/silosinging-us-anthem_64kb.mp3")
        var request:NSMutableURLRequest = NSMutableURLRequest(URL:url!)
        let conf: NSURLSessionConfiguration = NSURLSession.sharedSession().configuration
        let session = NSURLSession(configuration: conf)
        session.dataTaskWithRequest(request) {
            data, response, error in
            if error != nil {
                println("\(error)")
            }else {
                self.p = AVAudioPlayer(data: data, error: errorPointer)
            }
            }.resume()

    }

然后在一个动作中这样做:

@IBAction func pushButton(sender: AnyObject) {
        p!.prepareToPlay()
        p!.volume = 100
        p!.play()
    }