I have added audio files to my Xcode project so that i can play them locally using AvQueuePlayer
(a subclass of AVPlayer
). In order to do this I must create an array of [AVPlayerItems]
which is then supplied to the AVQueuePlayer
to be played sequentially... here is my code ...
override func viewDidLoad() {
//fills songNameArray with the appropriate part of file name, example: print(songNameArray[0]) -> prints -> "SongName.mp3"
let path = NSBundle.mainBundle().resourcePath!
let songFiles = try! NSFileManager.defaultManager().contentsOfDirectoryAtPath(path)
for item in songFiles {
if item.hasSuffix("mp3") {
songNameArray.append(item)
print("appended to songNameArray \(item)")
}
}
//iterates thru songNameArray and uses combineStrings method to form fullSongPath//
for i in 0...songNameArray.count - 1 {
fullSongPaths.append(combineStrings(songNameArray[i]))
print("here are the full song paths \(fullSongPaths[i])")
}
func combineStrings(songName: String) -> String {
let fullSongPath = ("/Users/username/Desktop/Xcode Projects Folder/LocalAudioPlayer/LocalAudioPlayer/" + songName)
return fullSongPath
}
}
Then, here is my didSelectRowAtIndexPath
where a user taps a song to start playing...
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
makePlayerItemsArray()
queuePlayer = AVQueuePlayer(items: playerItemsArray)
queuePlayer?.play()
}
And here is that makePlayerItemsArray function ...
func makePlayerItemsArray () {
playerItemsArray.removeAll()
var createdURL = NSURL()
var createdItem = AVPlayerItem(URL: createdURL)
for i in 0...fullSongPaths.count - 1 {
createdURL = NSURL.fileURLWithPath(fullSongPaths[i])
createdItem = AVPlayerItem(URL: createdURL)
playerItemsArray.append(createdItem)
}
}
This all works perfectly on the computer, the audio starts playing almost immediately after tapping a row. The problem is when i run this on my iPhone no audio comes out. The song never starts playing. And, when running on iPhone, if i tap a row-- then wait a few seconds-- then tap a button that calls queuePlayer.currentItem.currentTime()
,-- the app crashes on that line, which I believe is due to the queuePlayer
not having any item to play.
But why, when I run it on my phone does the queuePlayer
not get the items from playerItemsArray?
... I am able to print out the contents of the fullSongPaths
array as well as the contents of the playerItemsArray
but the queuePlayer wont play them...