r/swift•
laxtro

Playing sounds when you tap a button

I'm trying to create a simple app with a button, and I want that button to play a sound when I tap it. Anything obvious I'm doing wrong?

import SwiftUI
import AVFoundation

struct ContentView: View {
    var body: some View {
        VStack {
            Button("Hello world!") {
                self.playSound()
            }
            .padding()
            .border(Color.black)
        }
    }
    
    func playSound() {
            if let url = Bundle.main.url(forResource: "high_c", withExtension: "mp3") {
                do {
                    let player = try AVAudioPlayer(contentsOf: url)
                    player.play()
                } catch {
                    print("Error playing sound: \(error)")
                }
            } else {
                print("Sound file not found")
            }
        }
     
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

​

Posted Mar 12, 2024, 2:02 AM UTC

56
Loading comments…