AVPlayer(网络音频资源)的封装

如果不去封装的话, 当向音乐盒中放了很多资源的时候, 就会出现一系列容易崩溃的地方.下面话不多说,上代码.
  我封装的是一个单例.PlayerSingle
  // 1. 单列老步骤, 初始化.
  // 2. 属性
  (1)设置数据源musicArray, 存放所有音乐数组
  (2)下坐标,音乐存放都是有序的, 想找到对应的数组indexPath才可以 选中
  (3)播放类型,播放状态,写成枚举( 整型, typedef NS_ENUM(NSInterger,family) {zdf,joner}; )
  (4)AVPlayer, 增长生命周期
  (5)float 类型的 currentTime以及总时间
  // 3.方法
  (1)播放
  (2)暂停
  (3)停止
  (4)上一曲
  (5)下一曲
  (6)指定下标进行播放
  (7)指定位置进行播放
  (8)播放后的操作.


代码如下:
#import "PlayerSingle.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "RadioDetailModel.h"
@implementation PlayerSingle
+ (PlayerSingle *)sharePlayer {
    static PlayerSingle *palyer = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        palyer = [[PlayerSingle alloc]init];
    });
    return palyer;
}
// 默认配置
- (instancetype)init {
    if (self = [super init]) {
        //
        self.playType = PlayerTypeList;
        self
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现将网络音频URL存储到本地并播放,可以按照以下步骤进行操作: 1. 首先,使用AVPlayerAVPlayerViewController来播放网络音频。例如: ```swift let url = URL(string: "http://example.com/audio.mp3") let player = AVPlayer(url: url!) let playerViewController = AVPlayerViewController() playerViewController.player = player present(playerViewController, animated: true) { player.play() } ``` 2. 接下来,使用URLSession来下载音频文件并将其保存到本地。例如: ```swift let url = URL(string: "http://example.com/audio.mp3") let task = URLSession.shared.downloadTask(with: url!) { (location, response, error) in guard let location = location else { return } let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let destinationUrl = documentsUrl.appendingPathComponent("audio.mp3") do { try FileManager.default.moveItem(at: location, to: destinationUrl) // 播放本地音频 let player = AVPlayer(url: destinationUrl) let playerViewController = AVPlayerViewController() playerViewController.player = player present(playerViewController, animated: true) { player.play() } } catch { print(error) } } task.resume() ``` 3. 最后,为了节省空间,可以在不需要时删除本地音频文件。例如: ```swift let fileManager = FileManager.default let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first! let destinationUrl = documentsUrl.appendingPathComponent("audio.mp3") do { try fileManager.removeItem(at: destinationUrl) } catch { print(error) } ``` 以上就是实现将网络音频URL存储到本地并播放的步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值