简体   繁体   中英

Automatically Play audio while showing SwiftUI screen

I would like to show incoming screen like as below. While showing this screen, i wanted to play ring file (mp3). I have added Sound.playSounds(soundfile: "ringing.mp3") line just before window object. But the mp3 file is not playing but the function playsounds is executing.

    DispatchQueue.main.async{
        Sound.playSounds(soundfile: "ringing.mp3")

        let window = UIApplication.shared.windows.first
        let contentView = IncomingCallView(viewNavigator: ViewNavigator())
        window?.rootViewController = UIHostingController(rootView:contentView )
        window?.makeKeyAndVisible()
    }

The sound file is looking like below

import AVFoundation

class Sound {

    static var player:AVAudioPlayer?

    static func playaudio(soundfile: String) {

        if let path = Bundle.main.path(forResource: soundfile, ofType: nil){
            print("<<<<<<<<<<<<<<<<<<<<<PATH >>>>>>>>>>>>>>>>>>>>>>>>>",path)
            do{

                player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
                player?.prepareToPlay()
                player?.play()

            }catch {
                print("<<<<<<<<<<<<<<<<<<<<<Error >>>>>>>>>>>>>>>>>>>>>>>>")
            }
        }
    }
}

Use on appear method

SomeView()
    .onAppear{ Sound.playAudio }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM