ios - 通过 ViewController 导航时声音停止

标签 ios audio uiviewcontroller xcode11 swift5

我目前正在尝试在 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/

相关文章:

ios - 从模拟器中删除应用程序会删除文件吗?

python - Python中3D音频信号的平均RMS值

swift - 当 PageSheet 动画时 UINavigationBar 会渗出其背景

ios - 工具栏+导航栏+分段控件?

ios - iOS 6 上的 AVAssetResourceLoaderDelegate 协议(protocol)

c# - 收听来自多个麦克风的音频

javascript - 使用 javascript 解析并显示 HTML 音频当前时间

iphone - popToRootViewController 时出现奇怪的错误

IOS,从应用程序目录加载文件

ios - 使用 Swift 3.0 编译的模块无法在 Swift 2.3 中导入