bpolat / Music-Player

Fully functional music player which is written in swift programming language
The Unlicense
253 stars 76 forks source link

Loading Music Files from URLs #2

Open ialgahmi opened 9 years ago

ialgahmi commented 9 years ago

How can you load the music files from URLs instead of having the file locally? Can it be done using the .plist file?

bpolat commented 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"
}
ialgahmi commented 9 years ago

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?

KushThakkar commented 7 years ago

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"
}