2

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

2 回答 2

2

你可以尝试这样的事情:

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")
            }
        }
    }
}
于 2021-07-06T00:59:27.880 回答
0

发现它实际上只是一个“模拟器”错误,当从 xcode 构建打开应用程序时,它会一遍又一遍地播放声音......但在关闭并重新打开应用程序后,声音会按预期播放。

于 2021-07-06T01:16:38.190 回答