我目前正在尝试在 Xcode 中制作一个充当音乐应用程序的应用程序。它目前有 2 个 ViewController,看起来像这样。 ViewControllers MusicViewController 的代码:
import UIKit
import AVFoundation
class MusicViewController: UITableViewController, UINavigationControllerDelegate {
let songs = ["Sugar", "Da-i Foale", "Kush"]
var player = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
navigationController?.navigationBar.isHidden = false
}
//MARK: - Data Delegate Methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return songs.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SongCell", for: indexPath)
cell.textLabel?.text = songs[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let path = Bundle.main.path(forResource: songs[indexPath.row], ofType: "mp3")!
let url = URL(fileURLWithPath: path)
do {
player = try AVAudioPlayer(contentsOf: url)
try AVAudioSession.sharedInstance().setCategory(.playback)
player.play()
} catch {
print(error)
}
}
}
这个想法是在音乐不停止的情况下浏览其他 ViewController,但它不起作用。我不得不说,目前我没有使用 prepareForSegue()
或其他类似的方法。这是因为 ViewController 在通过导航栏的后退按钮关闭后被销毁了?感谢您的关注,等待您的答复。
最佳答案
当 ViewController 进入后台时,您的播放器实例可能会被释放。
您应该将 AVAudioPlayer 实例放入 AppDelegate。
关于ios - 通过 ViewController 导航时声音停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59799057/