Как следует из вопроса, мне нужно, чтобы мое приложение воспроизводило музыку в фоновом режиме, как и большинство музыкальных плееров. Я пытался найти что-то в Интернете, но они не работают. Может ли кто-нибудь взглянуть на мою проблему? Я думаю, что Apple автоматически закрывает мое приложение в фоновом режиме, поскольку оно может играть в фоновом режиме пару секунд (вероятно, около 10 секунд).
Более того, я хочу, чтобы музыка воспроизводилась в другом контроллере представления. На данный момент, когда я возвращаюсь к своему корневому контроллеру представления, музыка всегда останавливается.
Вот мой код.
//
// MusicLibraryTableViewController.swift
// WF
//
// Created by Bo Ni on 7/1/18.
// Copyright © 2018 Bo Ni. All rights reserved.
//
import UIKit
import AVFoundation
class MusicLibraryTableViewController: UITableViewController, AVAudioPlayerDelegate{
let songs: [String] = ["After Master"]
let producer: [String] = ["August Wu/Zoro"]
let identifier = "musicIdentifier"
var audioPlayer: AVAudioPlayer?
var isAudioPlayerPlaying = false
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt
indexPath: IndexPath) -> UITableViewCell {
let cell: MusicTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: identifier) as! MusicTableViewCell
cell.producerLabel.text = producer[indexPath.row]
cell.musicNameLabel.text = songs[indexPath.row]
cell.playButton.setImage(UIImage(named:"Play Button")?.withRenderingMode(.alwaysOriginal), for: UIControlState.normal)
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 64.0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return songs.count
}
override func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
let cell: MusicTableViewCell = self.tableView.cellForRow(at: indexPath) as! MusicTableViewCell
let music = NSURL.fileURL(withPath: Bundle.main.path(forResource: songs[indexPath.row], ofType: "mp3")!)
do {
try audioPlayer = AVAudioPlayer(contentsOf: music)
} catch{
print(error.localizedDescription)
}
UIApplication.shared.beginReceivingRemoteControlEvents()
audioPlayer?.delegate = self
audioPlayer?.prepareToPlay()
if isAudioPlayerPlaying == true{
stopAudio()
isAudioPlayerPlaying = false
cell.playButton.setImage(UIImage(named: "Play Button"), for: UIControlState.normal)
}else{
prepareAudio()
playAudio()
isAudioPlayerPlaying = true
cell.playButton.setImage(UIImage(named: "Stop Button"), for: UIControlState.normal)
}
}
func prepareAudio(){
do {
//keep alive audio at background
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch _ {
}
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch _ {
}
}
func playAudio(){
if let player = audioPlayer{
player.play()
}
}
func stopAudio(){
if let player = audioPlayer{
player.stop()
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/511 ... -9-swift-4
Я не могу воспроизводить музыку в фоновом режиме (Xcode 9, Swift 4) ⇐ IOS
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Android: остановить музыку в фоновом режиме и снова включить ее на переднем плане
Anonymous » » в форуме JAVA - 0 Ответы
- 16 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Android: остановить музыку в фоновом режиме и снова включить ее на переднем плане
Anonymous » » в форуме Android - 0 Ответы
- 23 Просмотры
-
Последнее сообщение Anonymous
-