1

I'm writing a podcast app and I want the user to play the local file they've downloaded if it exists (rather than stream it). The streaming works fine, but if the local file is found, it's not played by AVPlayer (this is actually not true for one out of about 5 files for reasons beyond me -- tapping on one podcast will play locally (I'm in airplane mode to verify).

I believe this is the Swift equivalent of this question, but I haven't been able to implement that solution in Swift.

Here's the code:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    var theURL = posts.objectAtIndex(indexPath.row).valueForKey("enclosure") as? String
    var theMp3Filename = theURL!.lastPathComponent

    for i in downloadedList {
        if i as! String == theMp3Filename {
            // If we've d/l'ed the mp3, insert the local path
            theURL = documentsDirectory().stringByAppendingPathComponent(theMp3Filename)
            var path: NSURL = NSURL.fileURLWithPath(theURL!)!
            player = AVPlayer(URL: path)
            player.play()

        } else {
            let podcastEpisode = AVPlayerItem(URL: NSURL(string: theURL!))
            player = AVPlayer(playerItem: podcastEpisode)
            player.play()
        }
    }
}

downloadedList is just an array I generate with the downloaded filenames. I am getting into the local condition, and the path looks right, but AVPlayer usually isn't working.

Any guidance would be appreciated.

Community
  • 1
  • 1
allocate
  • 1,323
  • 3
  • 14
  • 28
  • You can use AVAudioPlayer() – cmashinho May 01 '15 at 19:38
  • I started using AVPlayer because AVAudioPlayer wasn't playing well with streaming content. And I don't want to use both. – allocate May 01 '15 at 19:40
  • You have problem in path line. Use `NSURL(fileURLWithPath: "path")`, it really work. – cmashinho May 01 '15 at 19:45
  • I changed it to var path = NSURL(fileURLWithPath: theURL!)! and it still doesn't work. Actually, even the one file that was playing before stopped working this way. I did confirm though that `path` exists. – allocate May 01 '15 at 20:03
  • @JoshuaAuriemma Were you able to find a solution for this ? I'm facing the same problem. – Penkey Suresh May 26 '15 at 12:04
  • @redo1135 unfortunately no. I was forced to simultaneously work with AVAudioPlayer and AVPlayer depending on the scenario. Wasn't a huge, huge pain but definitely not ideal. – allocate May 26 '15 at 15:48

1 Answers1

1

Add this right after you set your path variable for playing downloaded audio:

let asset = AVURLAsset(URL: path)
let playerItem = AVPlayerItem(asset: asset)
player = AVPlayer(playerItem: playerItem)
player.play()
Jfusion
  • 11
  • 1