Ios 在ViewController中导航时声音停止
我目前正在尝试在Xcode中制作一个音乐应用程序。它目前有2个ViewController,看起来像这样。 MusicViewController的代码:Ios 在ViewController中导航时声音停止,ios,audio,uiviewcontroller,xcode11,swift5,Ios,Audio,Uiviewcontroller,Xcode11,Swift5,我目前正在尝试在Xcode中制作一个音乐应用程序。它目前有2个ViewController,看起来像这样。 MusicViewController的代码: import UIKit import AVFoundation class MusicViewController: UITableViewController, UINavigationControllerDelegate { let songs = ["Sugar", "Da-i Foale", "Kush"] va
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中导航,但它不起作用。我必须说,目前我没有使用
prepareforsgue()
或其他类似的方法。这是因为通过导航栏上的“后退”按钮关闭ViewController后,ViewController会被销毁?感谢您的关注,等待您的回答。当ViewController进入后台时,您的播放器实例可能会被释放
您应该将AVAudioPlayer实例放置到AppDelegate