Swift play mp3 from your app
Swift play mp3 from your app with this small example. To make swift play mp3 files we need to start with importing AVFoundation. That is where the audio player is.
import AVFoundation
Next we will create a variable for our music player.
var player = AVAudioPlayer()
Then we create a function to initialise the music player, and prepare the song. If you are using it as a background music you can run the function from viewDidLoad.
This is what you need to set up the player.
func initAudio() {
let path = NSBundle.mainBundle().pathForResource("music", ofType: "mp3")!
do {
player = try AVAudioPlayer(contentsOfURL: NSURL(string: path)!)
player.prepareToPlay()
player.numberOfLoops = -1
player.play()
} catch let err as NSError {
print(err.debugDescription)
}
}
If you plan to start the music programmatically or from a button you will need to remove the player.play() line. Thats all the code you need to load and play a mp3 file.
Lets do an example with starting and stopping the music from a button. I assume you have created both and Action and IBOutlet for the button. Even though the IBoutlet can be skipped and solved in a different way.
The IBOutlet is called button. I’m not going thru how to create an IBOutlet here now. The following code will create a function you can call from your IBAction.
func playPause() {
if player.playing {
player.pause()
button.setTitle("Play music", forState: UIControlState.Normal)
} else {
player.play()
button.setTitle("Pause music", forState: UIControlState.Normal)
}
}
Now as I mentioned you can skip the IBOutlet if the only purpose is to change the button text. If you other things to the button you might need it. If not here is how you can skip that. First we need to take the code above (the code inside the playPause function) and paste it into the IBAction function. Then we change the button.setTitle(“Play music”, forState: UIControlState.Normal), to sender.setTitle(“Play music”, forState: UIControlState.Normal). Sender will be the same as button. Here is the complete code for the IBAction.
@IBAction func btnPlayMusic(sender: AnyObject) {
if player.playing {
player.pause()
sender.setTitle("Play music", forState: UIControlState.Normal)
} else {
player.play()
sender.setTitle("Pause music", forState: UIControlState.Normal)
}
}
To download a working example, please go to my github account here: https://github.com/solron/Swift-Play-Mp3
You will need to add your own mp3 file to that project. Mine was called music.mp3
Thats it for swift play mp3.
Happy playing!