浏览 ViewController 时声音停止
Posted
技术标签:
【中文标题】浏览 ViewController 时声音停止【英文标题】:Sound stops when navigating through ViewControllers 【发布时间】:2020-01-18 09:10:37 【问题描述】:我目前正在尝试在 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 在您通过导航栏的后退按钮将其关闭后被销毁?感谢您的关注,等待您的答复。
【问题讨论】:
【参考方案1】:当 ViewController 进入后台时,您的播放器实例可能会被释放。
您应该将 AVAudioPlayer 实例放入 AppDelegate。
【讨论】:
以上是关于浏览 ViewController 时声音停止的主要内容,如果未能解决你的问题,请参考以下文章
Android 使用WebView浏览有声音或者视频的网页,关闭WebView之后,声音或者视频不停止的解决办法
离开 ViewController 时停止 AVCaptureSession