How To Make A MP3 Player With Swift? (With Code Samples)

import AVFoundation

class MP3Player {
var player: AVAudioPlayer?

func play(fileName: String) {
guard let url = Bundle.main.url(forResource: fileName, withExtension: "mp3") else { return }

do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)

player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)

guard let player = player else { return }

player.play()

} catch let error {
print(error.localizedDescription)
}
}

func stop() {
guard let player = player else { return }
player.stop()
}
}

import AVFoundation

class MP3Player {
// Declare a player property of type AVAudioPlayer
var player: AVAudioPlayer?

      guard let player = player else { return }
// Play the audio
player.play()

} catch let error {
print(error.localizedDescription)
}
}

  func stop() {
guard let player = player else { return }
// Stop the audio
player.stop()
}
}

--

--

Senior Software Engineer and Making $45,000/Month

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store