Автоматически воспроизводить звук при отображении экрана SwiftUI - PullRequest
0 голосов
/ 25 января 2020

Я хотел бы показать входящий экран, как показано ниже. Показывая этот экран, я хотел воспроизвести файл ринга (mp3). Я добавил Sound.playSounds(soundfile: "ringing.mp3") строку прямо перед объектом окна. Но файл mp3 не воспроизводится, а функция воспроизведения звучит.

    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()
    }

Звуковой файл выглядит следующим образом

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 >>>>>>>>>>>>>>>>>>>>>>>>")
            }
        }
    }
}

1 Ответ

0 голосов
/ 26 января 2020

Использовать при появлении метода

SomeView()
    .onAppear{ Sound.playAudio }
...