Solución:
Debe invocar beginReceivingRemoteControlEvents (); de lo contrario, no funcionará en el dispositivo real.
Swift 3.1
UIApplication.shared.beginReceivingRemoteControlEvents()
Si desea especificar acciones personalizadas para MPRemoteCommandCenter:
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.nextTrackCommand.isEnabled = true
commandCenter.nextTrackCommand.addTarget(self, action:#selector(nextTrackCommandSelector))
Para implementar esta funcionalidad, use las clases MPRemoteCommandCenter y MPNowPlayingInfoCenter del marco de Media Player con AVPlayer.
import MediaPlayer
import AVFoundation
// Configure AVPlayer
var player = AVPlayer()
Configurar los controladores de comandos remotos
Define una variedad de comandos en forma de objetos MPRemoteCommand a los que puede adjuntar controladores de eventos personalizados para controlar la reproducción en su aplicación.
func setupRemoteTransportControls() {
// Get the shared MPRemoteCommandCenter
let commandCenter = MPRemoteCommandCenter.shared()
// Add handler for Play Command
commandCenter.playCommand.addTarget { [unowned self] event in
if self.player.rate == 0.0 {
self.player.play()
return .success
}
return .commandFailed
}
// Add handler for Pause Command
commandCenter.pauseCommand.addTarget { [unowned self] event in
if self.player.rate == 1.0 {
self.player.pause()
return .success
}
return .commandFailed
}
}
Proporcionar metadatos de visualización
Proporcione un diccionario de metadatos utilizando las claves definidas por MPMediaItem y MPNowPlayingInfoCenter y configure ese diccionario en la instancia predeterminada de MPNowPlayingInfoCenter.
func setupNowPlaying() {
// Define Now Playing Info
var nowPlayingInfo = [String : Any]()
nowPlayingInfo[MPMediaItemPropertyTitle] = "My Movie"
if let image = UIImage(named: "lockscreen") {
nowPlayingInfo[MPMediaItemPropertyArtwork] =
MPMediaItemArtwork(boundsSize: image.size) { size in
return image
}
}
nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = playerItem.currentTime().seconds
nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = playerItem.asset.duration.seconds
nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate
// Set the metadata
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
Para obtener más información, consulte la documentación oficial de Apples.
func myplayer(file:String, type:String){
let path = NSBundle.mainBundle().pathForResource(file, ofType: type)!
let url = NSURL(fileURLWithPath: path)
let audioShouldPlay = audioPlaying()
do{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
let audioPlayer:AVAudioPlayer = try AVAudioPlayer(contentsOfURL: url)
audioPlayer.volume = slider.value
audioPlayer.numberOfLoops = -1
audioPlayer.prepareToPlay()
if(audioShouldPlay){
audioPlayer.play()
// let mpic = MPNowPlayingInfoCenter.defaultCenter()
// mpic.nowPlayingInfo = [MPMediaItemPropertyTitle:"title",
MPMediaItemPropertyArtist:"artist"]
}
}
catch{}
}