这是我的自定义音乐播放器代码。
这是我的单个自定义视图,我将其添加到窗口中,因此每当我进入应用程序时,它都会保留在屏幕上。
我的步骤:
当我第一次调用playCurrentMusic
这个方法时,一切正常,播放器正在打开,正在下载音频文件并进行播放。但是,当我第二次调用此方法时,正在下载文件,但没有music(_ url : URL)
调用此方法。
//MARK: Music player methods
extension MusicPlayerView : AVAudioPlayerDelegate{
func playCurrentMusic(_ index : Int){
player?.stop()
btnPlay.setImage(UIImage(named : "pause"), for: .normal)
downloadFileFromURL(url: URL(string: (totalItems[index].strUrl ?? ""))!)
print(URL(string: (totalItems[index].strUrl ?? ""))!)
currentItemId = index
}
func music(_ url : URL){
do {
if totalItems.count > 0{
DispatchQueue.main.async {
self.loader.stopAnimating()
self.loader.isHidden = true
self.btnPlay.isHidden = false
MPNowPlayingInfoCenter.default().nowPlayingInfo = [MPMediaItemPropertyTitle: self.totalItems[self.currentItemId].title ?? ""]
self.lblTitle.text = self.totalItems[self.currentItemId].title
self.lblDesc.text = self.totalItems[self.currentItemId].desc
self.commandCenter.playCommand.addTarget(handler: { (event) -> MPRemoteCommandHandlerStatus in
self.btnPlay_Click(self.btnPlay)
return .success
})
self.commandCenter.pauseCommand.addTarget(handler: { (event) -> MPRemoteCommandHandlerStatus in
self.btnPlay_Click(self.btnPlay)
return .success
})
}
}
player = try AVAudioPlayer(contentsOf: url)
isPlaying = true
if player?.isPlaying == true {
player?.pause()
}
if totalItems.count > 0{
let asset = AVURLAsset(url: URL(string: (totalItems[currentItemId].strUrl ?? ""))!)
DispatchQueue.main.async {
self.musicSlider.maximumValue = Float(Double(CMTimeGetSeconds(asset.duration)))
self.startTimer()
}
}else{
let asset = AVURLAsset(url: url)
DispatchQueue.main.async {
self.musicSlider.maximumValue = Float(Double(CMTimeGetSeconds(asset.duration)))
self.startTimer()
}
}
player?.delegate = self
player?.prepareToPlay()
player?.play()
} catch let error as NSError {
print(error)
}
}
// Delegate method for AVAudioPlayerDelegate which is called every time when song finished.
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool){
if totalItems.count > 0{
if flag {
if ((currentItemId + 1) == totalItems.count) {
currentItemId = 0
}else{
currentItemId += 1
}
}
downloadFileFromURL(url: URL(string: (totalItems[currentItemId].strUrl ?? ""))!)
}else{
isPlaying = false
btnPlay.setImage(UIImage(named : "playDark"), for: .normal)
}
}
func downloadFileFromURL(url:URL){
var downloadTask:URLSessionDownloadTask
loader.isHidden = false
btnPlay.isHidden = true
loader.startAnimating()
downloadTask = URLSession.shared.downloadTask(with: url, completionHandler: { [weak self](URL, response, error) -> Void in
self?.music(URL!)
})
downloadTask.resume()
}
}
将音乐播放器添加到appdelegate中的代码
func loadMusicPlayer(_ currentItemIndex : Int, items : [PlayerModel]) {
self.window?.rootViewController?.view.endEditing(true)
let player = MusicPlayerView()
player.frame = CGRect(x: 0, y: AppConstants.ScreenSize.SCREEN_HEIGHT - 156, width: AppConstants.ScreenSize.SCREEN_WIDTH, height: 156)
player.currentItemId = currentItemIndex
player.totalItems = items
player.tag = 1111
var isFound = false
for vw in UIApplication.shared.keyWindow!.subviews{
if vw is MusicPlayerView{
isFound = true
}
}
if !isFound{
UIApplication.shared.keyWindow?.addSubview(player)
}
player.playCurrentMusic(currentItemIndex)
}