UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.