Playing MP3 Files With Swift

Yello! Today we’re going to learn how to play MP3 files with Swift. Let’s get started!

We’ll need Foundation & AVFoundation to get started, so import those, and let’s make a new class, MusicPlayer.

Now, let’s create a new function to play our MP3 files, playFile.

Next, let’s access our MP3 file.

Now, let’s create an AVAudioPlayer. We’ll also have to make MusicPlayer an ObservableObject.

Then we’ll load the audioPlayer with our MP3 file and then play it.

That’s it! Now all you have to do is run these lines of code to play your MP3 file!

Also, if you need to pause audio playback, call this function on audioPlayer.

Thanks for reading! Make sure to follow me for more helpful articles, and clap if you found this helpful!

An eleven-year old designer and coder!

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

I’ve Been Using iPhones For a While & This Is Not Good

What Is the Value-Binding Pattern in Swift?

iOS 16 Allowing Us To Unsend iMessages?

SwiftUI: @State vs @StateObject vs @ObservedObject vs @EnvironmentObject

How To Build Sign in With Apple Into Your App

New Swift 5 Features while iOS App Development

NS for iOS Devs — View Lifecycle

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
Mr. SwiftUI

Mr. SwiftUI

An eleven-year old designer and coder!

More from Medium

Basic Operators in Swift

Introduction to Swift UI

From ObjC → Swift → ObjC: Part 2

Swift | MutltiformData | Upload Videos to Server as a Multipart form data Using Alamofire