5

I've been trying to use AVAudioPlayer to play remote MP3 files in my app and I've read some of the other answers on Stack Overflow but I still cannot get it to work. The common suggestion I'm reading is to use AVPlayer instead of AVAudioPlayer. I don't know why this is. Also, in one of the questions the accepted answer mentioned that one needs to create an instance of AVPlayer in order to use it in the app. What should I do?

Nick Forge
  • 21,344
  • 7
  • 55
  • 78
user817238593
  • 131
  • 1
  • 5
  • To answer the title, there is https://stackoverflow.com/questions/3282866/avplayer-vs-avaudioplayer – Cœur Mar 16 '17 at 07:26

1 Answers1

1

What you've read is correct. Creating an instance of AVPlayer will allow you to successfully run your code.

You should initialize your AVPlayer outside of where you want to call it.

var myPlayer = AVPlayer()

Now, in a separate place in your code, try something like this:

func playAudio() {

//initialize whatever you have to (you seem to have that correct)
//now call myPlayer.play(), and that should work correctly 

}

Let me know if this helps.

Nicolas S
  • 5,325
  • 3
  • 29
  • 36
sterling archer
  • 334
  • 3
  • 16
  • 2
    yay! it seem to work now... idk why initializing AVPlayer outside of the function helped. can u explain? – user817238593 Jul 03 '15 at 23:45
  • Thank you. But how can I get the duration from the AVPlayer? – user3163404 Aug 22 '15 at 00:41
  • @user3163404 you can get it via the currentItem method "yourAVPlayerInstance.currentItem.duration". – TimD Sep 04 '15 at 05:13
  • @user817238593 I believe initializing an item inside a function and it de-allocating has something to do with scope and how Swift cleans itself up whenever a variable is no longer in use. For example, whenever you declare a variable inside the scope, the class doesn't have access to it. Once the function has ran, I assume whatever variable it was using to hold information is garbage collected. Thus if you initialize an AVPlayer instance inside a function that completes it is then garbage collected and deallocated. – TimD Sep 04 '15 at 05:15