我试图在我的应用程序上添加背景音乐的 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")
}
}
}
}