方式一
import AVFoundation
class MusicTools: NSObject {
fileprivate static var player : AVAudioPlayer?
}
// MARK: - 对歌曲的控制
extension MusicTools: AVAudioPlayerDelegate{
/// 播放本地音乐
class func playLocationMusic(_ musicName : String){
//1 获取资源的URL
guard let url = Bundle.main.url(forResource: musicName, withExtension: nil) else { return }
//0 判断和暂停/停止的对象是否同一首歌曲(继续播放的时候不会切歌)
if player?.url == url{
player?.play()
return
}
//2 根据URL创建AVAudioPlayer对象
guard let audioPlayer = try? AVAudioPlayer(contentsOf: url) else { return }
self.player = audioPlayer
//3 播放音乐
audioPlayer.play()
}
/// 播放网络音乐
class func playNetworkMusic(_ urlString : String){
//1 获取资源的URL
guard let url = urlString.toUrl() else { return }
//0 判断和暂停/停止的对象是否同一首歌曲(继续播放的时候不会切歌)
if player?.url == url{
player?.play()
return
}
guard let urlData = try? Data(contentsOf: url) else { return }
//2 根据URL创建AVAudioPlayer对象
guard let audioPlayer = try? AVAudioPlayer(data: urlData) else { return }
self.player = audioPlayer
//3 播放音乐
audioPlayer.play()
}
class func pauseMusic() {
player?.pause()
}
class func stopMusic(){
player?.stop()
player?.currentTime = 0
}
}
// MARK: - 对其他的控制(音量/时间/代理设置)
extension MusicTools{
class func changeVolume(volume : Float){
player?.volume = volume
}
class func setCurrentTime(_ currentTime : TimeInterval) {
player?.currentTime = currentTime
}
class func getCurrentTime() -> TimeInterval{
return player?.currentTime ?? 0
}
class func getDuration() -> TimeInterval{
return player?.duration ?? 0
}
class func setPlayerDelegate(_ delegate : AVAudioPlayerDelegate){
player?.delegate = delegate
}
}
方式二
import AVFoundation
class MusicTools: NSObject {
fileprivate static var player : AVPlayer?
}
// MARK: - 对歌曲的控制
extension MusicTools{
/// 播放网络音乐
class func playNetworkMusic(_ urlString : String){
//获取资源的URL
guard let url = urlString.toUrl() else { return }
// 缓存
let session = AVAudioSession.sharedInstance()
// 创建音/视频资源
let playerItem = AVPlayerItem(url: url)
// 将音/视频资源赋值给视频播放对象
let avplayer = AVPlayer(playerItem: playerItem)
// //初始化视频显示layer
// let playerLayer = AVPlayerLayer(player: avplayer)
try? session.setCategory(.playback)
try? session.setActive(true, options: [])
self.player = avplayer
avplayer.play()
}
class func getPlayer() -> AVPlayer? {
return player
}
/// 暂停
class func pauseMusic() {
player?.pause()
}
/// 播放
class func playMusic() {
player?.play()
}
/// 总时长
class func duration() -> Float64? {
if let d = MusicTools.player?.currentItem?.duration {
return CMTimeGetSeconds(d)
}
return nil
}
/// 返回当前时长
class func currentTime() -> Float64? {
if let d = MusicTools.player?.currentTime() {
return CMTimeGetSeconds(d)
}
return nil
}
}
网友评论