gpt4 book ai didi

SwiftUI 出现 AVAudioPlayer 播放多次

转载 作者:行者123 更新时间:2023-12-04 07:25:02 30 4
gpt4 key购买 nike

我试图在我的应用程序上为背景音乐添加一个 AVAudioPlayer,我正在主屏幕上启动播放器,尝试在应用程序打开时开始播放但出现意外行为...
它播放并立即不断创建新玩家并播放这些玩家,因此同时播放数十个相同的声音

音乐的启动和播放功能

if let path = Bundle.main.path(forResource: sound, ofType: type) {
do {
backgroundPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
backgroundPlayer?.play()
} catch {
print("BACKGROUND MUSIC ERROR")
}
}

出现对函数的调用
.onAppear {
audioController.backgroundMusic(sound: "bg", type: "wav")
}

编辑:示例代码...
import SwiftUI
import AVKit

struct ContentView: View {
@ObservedObject var audioController = AudioController()

var body: some View {
Text("Hello, world!")
.onAppear {
audioController.playBackgroundMusic(sound: "bg", type: "wav")
}
}
}

class AudioController: ObservableObject {
var player: AVAudioPlayer?

func playBackgroundMusic(sound: String, type: String) {
if let path = Bundle.main.path(forResource: sound, ofType: type) {
do {
player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
player?.play()
} catch {
print("BACKGROUND MUSIC ERROR")
}
}
}
}

最佳答案

你可以尝试这样的事情:

func playBackgroundMusic(sound: String, type: String) {
if !(player?.isPlaying ?? false) {
if let path = Bundle.main.path(forResource: sound, ofType: type) {
do {
player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
player?.play()
} catch {
print("BACKGROUND MUSIC ERROR")
}
}
}
}

关于SwiftUI 出现 AVAudioPlayer 播放多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68263249/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com