AVAudioPlayer没有从Swift Programming中的url文件运行

时间:2015-06-22 02:13:18

标签: swift avaudioplayer nsurl

我是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()中遇到错误,其中包含"致命错误:在展开“可选”值时意外发现nil"和值是"错误NSError? domain:" NSOSStatusErrorDomain" - 代码:2003334207 0x00007fc3e3e4b820"

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

2 个答案:

答案 0 :(得分:0)

您不能使用NSURL(fileURLWithPath :)方法从Web链接创建URL。从链接创建url时,您需要使用NSURL(字符串:)但是您应该使用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()
    }
}

答案 1 :(得分:0)

你必须先加载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()
    }