简体   繁体   English

如何同步背景音乐和按钮?

[英]How do I synchronize background music and buttons?

An application writes.一个应用程序写入。 Music plays on the background of the application.音乐在应用程序的背景上播放。 And I want to stop and resume this music from every page of the application我想从应用程序的每一页停止并恢复这些音乐

But after pressing the music stop button on one page, the buttons on the other pages do not change.但是按下一页上的音乐停止按钮后,其他页面上的按钮没有变化。

And when I go back to the first page, the music starts all over again.当我回到第一页时,音乐又重新开始。

import Foundation
import AVFoundation

class Music {

    static var audioPlayer : AVAudioPlayer?
    enum SoundEffect {
        case background
    }

    static func playSound(effect : SoundEffect) {

        var soundFileName = ""
        switch effect {
            case.background:
                soundFileName = "background"
        }

        let bundlePath = Bundle.main.path(forResource: soundFileName, ofType: "wav")
        guard bundlePath != nil else {
            print("Couldn't find sound file \(soundFileName) in the bundle")
            return
        }

        do {
            let soudURL = URL(fileURLWithPath: bundlePath!)

            audioPlayer = try AVAudioPlayer(contentsOf: soudURL)
            audioPlayer!.numberOfLoops = -1
            audioPlayer?.prepareToPlay()
            audioPlayer?.play()
        } catch {

        }
    }
}

Al first check AVAudioPlayer is already initialize or not and after that check player is playing or stop.首先检查 AVAudioPlayer 是否已经初始化,然后检查播放器是否正在播放或停止。

if let audioPlayer = Music.audioPlayer, audioPlayer.playing {
    audioPlayer.stop()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM