切换视图控制器时连续播放音乐-Swift 4.2

时间:2019-02-26 21:22:48

标签: ios swift

我试图将背景音乐实现到我用Xcode制作的应用程序中,但是我找不到适合我当前使用的Swift版本(4.2)的解决方案。 目前,当我从一个视图控制器切换到另一个视图控制器时,音乐将重新开始,但是当我关闭视图控制器时,不会发生这种情况。

我将发布到目前为止正在使用的代码:

ViewController.swift

import UIKit
import AVFoundation

class ViewController: UIViewController {

var audioPlayer : AVAudioPlayer?
var selectedSoundFileName : String = ""
let phonicSoundArray = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "ai", "ar", "ch", "ck", "ee", "ie", "ng", "oa", "oi", "oo", "or", "ou", "ph", "qu", "sh", "ss", "th", "ue"]

override func viewDidLoad() {
    super.viewDidLoad()
    MusicHelper.sharedHelper.playBackgroundMusic()
}


@IBAction func dismissCurrentView(_ sender: Any) {
    self.dismiss(animated: true, completion: nil)
}

//== Phonic audio playback =================
@IBAction func phonicPracticeButtonPressed(_ sender: AnyObject) {

    selectedSoundFileName = phonicSoundArray[sender.tag - 1]+".mp3"

    let path = Bundle.main.path(forResource: selectedSoundFileName, ofType:nil)!
    let url = URL(fileURLWithPath: path)

    do {
        audioPlayer = try AVAudioPlayer(contentsOf: url)
        audioPlayer?.play()
    } catch {
        print("Couldn't load audio")
    }
}
}

BGMSingleton.swift

import Foundation
import AVFoundation

class MusicHelper {
static let sharedHelper = MusicHelper()
var audioPlayer: AVAudioPlayer?

func playBackgroundMusic() {
    let aSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "BGM", ofType: "mp3")!)
    do {
        audioPlayer = try AVAudioPlayer(contentsOf:aSound as URL)
        audioPlayer!.numberOfLoops = -1
        audioPlayer!.prepareToPlay()
        audioPlayer!.play()
    }
    catch {
        print("Cannot play the file")
    }
}
}

1 个答案:

答案 0 :(得分:0)

假设您正在发布的两个相同的VC之间进行筛选...

每当您通过以下方式选择VC时 MusicHelper.sharedHelper.playBackgroundMusic()在其viewDidLoad中,您的音乐将重新开始。

viewDidLoad在每个VC生命周期中发生一次。退出VC时,您没有调用它的viewDidLoad,这就是音乐没有重新启动的原因。

有关VC生命周期的更多信息

https://developer.apple.com/documentation/uikit/uiviewcontroller

Looking to understand the iOS UIViewController lifecycle