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

标签 ios swift

应用程序写入。音乐在应用程序的背景上播放。我想从应用程序的每个页面停止和恢复此音乐

但是在一个页面按下音乐停止按钮后,其他页面的按钮没有变化。

当我回到第一页时,音乐又重新开始了。

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 {

        }
    }
}

最佳答案

首先检查 AVAudioPlayer 是否已经初始化,然后检查播放器正在播放或停止。

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

关于ios - 如何同步背景音乐和按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59376052/

相关文章:

iOS/swift : Dynamic UITableViewCell row height with embedded UITableView not working

ios - Apollo Client 生成一个空的 API.swift 文件

ios - 更改 UICollectionView 中单元格的文本时应用程序崩溃

ios - 为什么我的 subview 没有添加到我的 ScrollView 中?

ios - Swift 中的 UITableView - 单元格出队

ios - 使用 swift 将 JSON 检索到的 int32 解析为核心数据类

iphone - 如何将以下行添加到我的 plist 文件中?

ios - 如何在返回语句之前等待委托(delegate)方法执行?

ios - 如何使用 UIScrollView 内的自动布局将 UIImage View 缩放为正方形

ios - 为什么我的 UIViewController 没有正确发布?