TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Playing mp3 files

Forums > SwiftUI

Below is the code I use I use to play an mp3 file , say Bass Drum. I would have thought that after that process I would only have to put self.BDPlayer?.play() or BDPlayer?.play() in my code to play the sounds. As far as I can make out this doesn't work, so I have to recreate the avaudioPlayer and check for errors every time I want to play the sound. This is easy to do by creating a function, but it seems a very inefficient way to things.

Am I correct?

@State var BDPlayer: AVAudioPlayer?


if let BDURL = Bundle.main.url(forResource: "Bass Drum", withExtension: "mp3") {
            do {
                try self.BDPlayer = AVAudioPlayer(contentsOf: BDURL) /// make the audio player
                self.BDPlayer?.volume = 5
                self.BDPlayer?.play()     
            } catch {
            print("Couldn't play audio. Error: \(error)")
            }
                }

3      

I think you would just set currentTime to 0 on the same instance to play it again.

3      

Hi SvenOaks and thanks for replying.

Swift didn't like currentTime. what is it exactly that I would type in.

3      

Setting self.BDPlayer?.currentTime = 0 worked just fine for me.

3      

Hi SvenOaks and thanks for replying.

Swift didn't like currentTime. what is it exactly that I would type in.

3      

****Hi SvenOaks and Rooster Boy and thanks for replying.

Thanks heaps for your help. self.BDPlayer?.currentTime = 0 worked beautifully.

3      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.