create a music player in swift

To create a music player in Swift, follow these steps:

  1. First, add the AVFoundation framework to your project by clicking on your project target, selecting "Build Phases", and then adding "AVFoundation.framework" to "Link Binary With Libraries".

  2. Next, import AVFoundation in your view controller file:

main.swift
import AVFoundation
20 chars
2 lines
  1. Create a variable to hold your audio player and another variable to hold the audio URL:
main.swift
var audioPlayer: AVAudioPlayer?
var audioURL: URL?
51 chars
3 lines
  1. Load the audio file by setting the audioURL variable to the audio file's URL and then initializing the audioPlayer with that URL:
main.swift
audioURL = Bundle.main.url(forResource: "song", withExtension: "mp3")
do {
    audioPlayer = try AVAudioPlayer(contentsOf: audioURL!)
} catch {
    print("Error loading audio file")
}
184 chars
7 lines

Note: replace "song" and "mp3" with the name and extension of your audio file.

  1. Add controls to play, pause, and stop the audio player. For example, for a play button:
main.swift
@IBAction func playButtonTapped(_ sender: UIButton) {
    audioPlayer?.play()
}
80 chars
4 lines

For a pause button:

main.swift
@IBAction func pauseButtonTapped(_ sender: UIButton) {
    audioPlayer?.pause()
}
82 chars
4 lines

For a stop button:

main.swift
@IBAction func stopButtonTapped(_ sender: UIButton) {
    audioPlayer?.stop()
    audioPlayer?.currentTime = 0
}
113 chars
5 lines
  1. Finally, don't forget to handle errors gracefully such as if the user's device is muted or if the audio file could not be loaded.

That's it! You now have a simple music player in Swift using AVFoundation.

related categories

gistlibby LogSnag