How To Make A MP3 Player With Swift? (With Code Samples)
Here mp3 player codes in Swift:
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()
}
}
The AVFoundation framework is imported to provide access to classes that allow you to play audio. The MP3Player class is a simple class with a single property, player, which is an optional AVAudioPlayer object.
import AVFoundation
class MP3Player {
// Declare a player property of type AVAudioPlayer
var player: AVAudioPlayer?
The play function takes a single parameter, fileName, which is the name of the MP3 file to be played. The file is assumed to be located in the main bundle of the app and have the .mp3 file extension. The url(forResource:withExtension:) method of Bundle is used to get the URL of the file. The guard statement is used to exit the function early if the URL could not be obtained.
The AVAudioSession class is used to configure the audio session of the app. The setCategory method is used to set the category of the audio session to playback, and the setActive method is used to activate the audio session.
The AVAudioPlayer class is used to play the audio file. An instance of AVAudioPlayer is created with the contentsOf initializer, which takes the URL of the audio file and a file type hint as arguments. The file type hint is used to help the system determine how to interpret the audio data.
The play method of AVAudioPlayer is called to start playing the audio. If any errors are thrown during the setup of the player or the playback of the audio, they are caught and their localized descriptions are printed to the console.
guard let player = player else { return }
// Play the audio
player.play()
} catch let error {
print(error.localizedDescription)
}
}
The stop function stops the audio by calling the stop method of the player. It is similar to the play function in that it uses a guard statement to exit the function early if the player is nil.
func stop() {
guard let player = player else { return }
// Stop the audio
player.stop()
}
}
I hope this helps! Let me know if you have any questions about the Swift code.