我想在导航时播放声音而不被缩短

问题描述 投票:0回答:2

我有一个包含导航链接的主菜单视图。当我按下“播放”时,它会导航到游戏屏幕并播放声音。然而,声音只播放一秒钟,然后在其余的导航过程中停止。我需要帮助才能使声音持续播放到下一个视图。预先感谢您的帮助。

NavigationLink(destination: GameScreenView(), isActive: $presentSound) {
    Button(action: {
//          SoundManager.instance.playSound(sound: .impact)
        DispatchQueue.main.asyncAfter(deadline: .now()) {
            SoundManager.instance.playSound(sound: .impact)
//          self.presentSound = true
    }
    }, label: {
    Text("Play")
    })
}
audio swiftui navigation swiftui-navigationlink swiftui-view
2个回答
0
投票

尝试以下方法,向

NavigationLink
添加额外的手势, 点击链接时会发出声音。

struct ContentView: View {
    
    var body: some View {
        NavigationStack {
            NavigationLink(destination: Text("GameScreenView")) {
                Text("Play")
            }.simultaneousGesture(TapGesture().onEnded {
                AudioServicesPlaySystemSound(1026) // <-- for testing
                // SoundManager.instance.playSound(sound: .impact)
            })
        }
    }
}

0
投票

另一种方法是在下一个屏幕初始化时播放声音,如下所示:

屏幕A:

struct ScreenA: View {
    var body: some View {
        NavigationLink(destination: ScreenB()) {
            Text("Navigate to Screen B")
        }
    }
}

屏幕B:

struct ScreenB: View {
    init() {
        playSoundMethod() // your sound method here
    }

    var body: some View {
        Text("Welcome to Screen B")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.