Open ialgahmi opened 9 years ago
Yes it can be done but you need add a new key into .plist file and put your external URL there then modify "setCurrentAudioPath" function accordingly and change code accordingly. Replace "prepareAudio" function with following. This is a working code with a sample .mp3 on external URL.
func prepareAudio(){
setCurrentAudioPath()
//keep alive audio at background
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
let url = NSURL(string: "http://www.zero-project.gr/singles/pandoras_dream/mp3s/zero-project%20-%2001%20-%20Pandora's%20dream.mp3")
var data = NSData(contentsOfURL: url)
audioPlayer = AVAudioPlayer(data: data, error: nil)
//audioPlayer = AVAudioPlayer(contentsOfURL: currentAudioPath, error: nil)
audioPlayer.delegate = self
audioLength = audioPlayer.duration
playerProgressSlider.maximumValue = CFloat(audioPlayer.duration)
playerProgressSlider.minimumValue = 0.0
playerProgressSlider.value = 0.0
audioPlayer.prepareToPlay()
showTotalSongLength()
updateLabels()
progressTimerLabel.text = "00:00"
}
Also, how can you show the audio information, such as the title, album, and artist, on the lock screen or control center and be able to pause/play and skip audio from there?
Its working Fine in Swift 3 - you can use below method for Swift 3
func prepareAudio(){ setCurrentAudioPath() //keep alive audio at background try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: []) try! AVAudioSession.sharedInstance().setActive(true) UIApplication.shared.beginReceivingRemoteControlEvents() let url = NSURL(string: currentAudio) let data = NSData.init(contentsOf: url! as URL) do { audioPlayer = try AVAudioPlayer(data: data! as Data) } catch{ print(error) }
audioPlayer.delegate = self
audioLength = audioPlayer.duration
playerProgressSlider.maximumValue = CFloat(audioPlayer.duration)
playerProgressSlider.minimumValue = 0.0
playerProgressSlider.value = 0.0
audioPlayer.prepareToPlay()
showTotalSongLength()
updateLabels()
progressTimerLabel.text = "00:00"
}
How can you load the music files from URLs instead of having the file locally? Can it be done using the .plist file?