Home > AI > IOS > AVFoundation >

AVAudioPlayer

import SwiftUI
import AVFoundation


struct ContentView: View {
    @State var audioPlayer: AVAudioPlayer?
    
    var body: some View {
       
        Text("good")
            .onAppear(perform: {
                playSound(sound: "a", type: "mp3")
                audioPlayer?.numberOfLoops = 100
            })
    }
    
    
    
    func playSound(sound: String, type: String) {
        if let path = Bundle.main.path(forResource: sound, ofType: type) {
            do {
                audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
                audioPlayer?.play()
            } catch {
                print("ERROR")
            }
        }
    }
}

Leave a Reply