|
|
|
@ -48,8 +48,14 @@ public class MusicService: NSObject { |
|
|
|
// MARK: - 音频会话设置 |
|
|
|
private func setupAudioSession() { |
|
|
|
do { |
|
|
|
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.allowAirPlay, .allowBluetooth]) |
|
|
|
try AVAudioSession.sharedInstance().setActive(true) |
|
|
|
let audioSession = AVAudioSession.sharedInstance() |
|
|
|
try audioSession.setCategory(.playback, mode: .default, options: [.allowAirPlay, .allowBluetooth, .allowBluetoothA2DP]) |
|
|
|
try audioSession.setActive(true) |
|
|
|
|
|
|
|
// 确保媒体控制中心可以接收到我们的应用 |
|
|
|
setupRemoteCommandCenter() |
|
|
|
|
|
|
|
print("音频会话和媒体控制设置成功") |
|
|
|
} catch { |
|
|
|
print("设置音频会话失败: \(error)") |
|
|
|
} |
|
|
|
@ -380,6 +386,12 @@ public class MusicService: NSObject { |
|
|
|
currentVolume = 1.0 |
|
|
|
player?.volume = currentVolume |
|
|
|
|
|
|
|
// 立即设置媒体信息,即使播放器还未准备就绪 |
|
|
|
updateNowPlayingInfo(song: song) |
|
|
|
|
|
|
|
// 确保远程控制中心已设置 |
|
|
|
setupRemoteCommandCenter() |
|
|
|
|
|
|
|
print("播放器已创建,等待加载完成...") |
|
|
|
} |
|
|
|
|
|
|
|
@ -574,20 +586,39 @@ public class MusicService: NSObject { |
|
|
|
|
|
|
|
// 异步加载封面图片 |
|
|
|
if !coverUrl.isEmpty, let url = URL(string: coverUrl) { |
|
|
|
print("开始加载封面图片: \(coverUrl)") |
|
|
|
|
|
|
|
DispatchQueue.global(qos: .background).async { |
|
|
|
if let data = try? Data(contentsOf: url), |
|
|
|
let image = UIImage(data: data) { |
|
|
|
// 创建带超时的URLRequest |
|
|
|
var request = URLRequest(url: url) |
|
|
|
request.timeoutInterval = 10.0 |
|
|
|
|
|
|
|
URLSession.shared.dataTask(with: request) { data, response, error in |
|
|
|
if let error = error { |
|
|
|
print("图片加载失败: \(error.localizedDescription)") |
|
|
|
DispatchQueue.main.async { |
|
|
|
nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in image } |
|
|
|
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo |
|
|
|
} |
|
|
|
} else { |
|
|
|
return |
|
|
|
} |
|
|
|
|
|
|
|
guard let data = data, let image = UIImage(data: data) else { |
|
|
|
print("图片数据无效或格式不支持") |
|
|
|
DispatchQueue.main.async { |
|
|
|
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo |
|
|
|
} |
|
|
|
return |
|
|
|
} |
|
|
|
|
|
|
|
print("图片加载成功") |
|
|
|
DispatchQueue.main.async { |
|
|
|
nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in image } |
|
|
|
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo |
|
|
|
} |
|
|
|
}.resume() |
|
|
|
} |
|
|
|
} else { |
|
|
|
print("封面图片URL为空") |
|
|
|
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo |
|
|
|
} |
|
|
|
} |
|
|
|
|