2015-06-01 62 views
1

我有一個音頻文件從服務器下載到我的文檔目錄。我試圖用AVPlayer播放相同的內容,但有些原因無法完成。以下是我的整個代碼。如果我們onlineResource取代localAudioPath它起着罰款AVPlayer播放在線資源,但不是相同的下載資源

import UIKit 
import AVFoundation 

class AudioController: UIViewController { 

    var player : AVPlayer! 

    override func viewDidLoad() { 
    super.viewDidLoad() 
    } 

    @IBAction func playAudio(sender: AnyObject) { 
    var name = "bell.mp3" 
    var docs = NSSearchPathForDirectoriesInDomains(directory, .UserDomainMask, true)[0] as! String 
    var localAudioPath = docs.stringByAppendingPathComponent(name) 
    var onlineResource = "path/to/online/bell.mp3" 

    if NSFileManager.defaultManager().fileExistsAtPath(localAudioPath!) { 
     let playerItem = AVPlayerItem(URL: NSURL(string: localAudioPath!)!) 
     player = AVPlayer(playerItem: playerItem) 
     player.play() 

    } else { 
     /* Alamo fire code to download file to docs directory*/ 
     let destination = Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask) 

     Alamofire.download(.GET, NSURL(string: audio.audioUrl)!.http, destination) 
     .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in 
     println(totalBytesRead) 
     } 
     .response { (request, response, _, error) in 
     println(response) 
     } 
    } 
    } 

} 

有人能告訴我,如果它甚至有可能發揮使用AVPlayer本地文件?

+1

http://stackoverflow.com/a/30471885/2303865 –

+0

@LeoDabus謝謝。這解決了我的問題。 :) –

+0

不客氣 –

回答

1

你應該使用fileURLWithPath:提供正確的url,它應該播放本地url就好了。

let playerItem = AVPlayerItem(URL: NSURL(fileURLWithPath: localAudioPath!)!)