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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.