我是Swift编程语言的新手,我想在歌曲改变时获得输出。代码没有任何错误。
下面是我的代码
import UIKit
导入MediaPlayer
类ViewController:UIViewController {
var trackChangedObserver : AnyObject?
override func viewDidLoad() {
super.viewDidLoad()
trackChangedObserver = NotificationCenter.default
.addObserver(forName: .MPMusicPlayerControllerNowPlayingItemDidChange,
object: nil, queue: OperationQueue.main) { (notification) -> Void in
self.updateTrackInformation()
}
}
deinit {
NotificationCenter.default.removeObserver(trackChangedObserver!)
}
func updateTrackInformation() {
let musicPlayer = MPMusicPlayerController.systemMusicPlayer
musicPlayer.beginGeneratingPlaybackNotifications()
let currentTrack: MPMediaItem? = musicPlayer.nowPlayingItem
let title = currentTrack?.value(forProperty: MPMediaItemPropertyTitle)
as? String ?? "None"
print(title)
let artist = currentTrack?.value(forProperty: MPMediaItemPropertyArtist)
as? String ?? "None"
print(artist)
let album = currentTrack?.value(forProperty: MPMediaItemPropertyAlbumTitle)
as? String ?? "None"
print(album)
}
}
您可以这样做:
let nc = NotificationCenter.default
nc.post(名称:.MPMusicPlayerControllerNowPlayingItemDidChange,对象:nil)
要注册以捕获正在发布的通知,请使用此:
nc.addObserver(self, selector: #selector(updateTrackInformation()), name: .MPMusicPlayerControllerNowPlayingItemDidChange, object: nil)
@objc func updateTrackInformation(notification: NSNotification) {
let musicPlayer = MPMusicPlayerController.systemMusicPlayer
musicPlayer.beginGeneratingPlaybackNotifications()
let currentTrack: MPMediaItem? = musicPlayer.nowPlayingItem
let title = currentTrack?.value(forProperty: MPMediaItemPropertyTitle)
as? String ?? "None"
print(title)
let artist = currentTrack?.value(forProperty: MPMediaItemPropertyArtist)
as? String ?? "None"
print(artist)
let album = currentTrack?.value(forProperty: MPMediaItemPropertyAlbumTitle)
as? String ?? "None"
print(album)
}