Introduction
In this article, we will move forward and see how to implement the AV Player in iOS App Development. Basically, the function of the AV player is to play the songs in your app.
Step 1: First, open the Xcode Editor and choose the Single View Application. Then, set application type to universal and create the project. After that, download three images and one music file. Drag these four things and drop into your Xcode project.
Step 2: Now, go to the Main story board file. Drag three buttons from the object library and drop into the Main storyboard. Now, set the buttons' images as play, pause, and stop, as shown below.
Step 3: Now, move to the ViewController.Swift file and import the AVFoundation. Then, we make an instance of AVAudioPlayer and set the song path (give the music name and type). Then, we check for its condition. If it is true, then play the song, otherwise print the error message. Now, when you run the app, your song starts playing.
Code
- import UIKit
- import AVFoundation
- class ViewController: UIViewController
- {
- var myAudioPlayer = AVAudioPlayer()
- override func viewDidLoad()
- {
- super.viewDidLoad()
-
- let myFilePathString = NSBundle.mainBundle().pathForResource("hello", ofType: "mp3")
- if let myFilePathString = myFilePathString
- {
- let myFilePathURL = NSURL(fileURLWithPath: myFilePathString)
- do
- {
- try myAudioPlayer = AVAudioPlayer(contentsOfURL: myFilePathURL)
- myAudioPlayer.play()
- } catch
- {
- print("Error")
- }
- }
- }
Step 4 Open the Xcode in Assistant mode. At the top-right position, you see the double over lap circle. Press this button and your Xcode breaks in two parts. Now, create the actions of these three buttons and one volume control. Also, create the outlet of slider and give it the name as myVolumeController. Press the control button and click the button and drop into the left side.
Step 5
After the actions of three buttons and one slider along with the outlet of slider are ready, we just simply add a code in it. The code is not hard to understand.
Code
@IBOutlet weak var myVolumeController: UISlider!
@IBAction func stopAudio(sender: AnyObject) {
myAudioPlayer.stop()
myAudioPlayer.currentTime=0
}
@IBAction func pauseAudio(sender: AnyObject) {
myAudioPlayer.pause()
}
@IBAction func playAudio(sender: AnyObject) {
myAudioPlayer.play()
}
@IBAction func volumeControl(sender: AnyObject) {
myAudioPlayer.volume=myVolumeController.value
} Now, all the things are OK. Run the app and check the play, pause, and stop buttons.
All buttons are working correctly. You can also check the volume controller. Well, it’s also working fine. I have also uploaded the project files so that you can download and use them.