#import <Foundation/Foundation.h>
@interface ShortMusicPlayTool : NSObject
+ (void)playShortMusicWithFileName:(NSString *)fileName;
+ (void)disposeShortMusicWithFileName:(NSString *)fileName;
@end
ShortMusicPlayTool.m文件
#import "ShortMusicPlayTool.h"
#import <AVFoundation/AVFoundation.h>
@implementation ShortMusicPlayTool
static NSMutableDictionary *_soundIDs;
+ (NSMutableDictionary *)soundIDs
{
if (!_soundIDs) {
_soundIDs = [NSMutableDictionary dictionaryWithCapacity:0];
}
return _soundIDs;
}
// 播放
+ (void)playShortMusicWithFileName:(NSString *)fileName
{
if (fileName == nil) {
return;
}
SystemSoundID soundID = [[self soundIDs][fileName] unsignedIntValue];
if (!soundID) {
NSURL *url = [[NSBundle mainBundle] URLForResource:fileName withExtension:nil];
if (!url) {
return;
}
AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(url), &soundID);
}
AudioServicesPlaySystemSound(soundID);
}
// 销毁
+ (void)disposeShortMusicWithFileName:(NSString *)fileName
{
if (fileName == nil) {
return;
}
SystemSoundID soundID = [[self soundIDs][fileName] unsignedIntValue];
if (soundID) {
return;
}
AudioServicesDisposeSystemSoundID(soundID);
[[self soundIDs] removeObjectForKey:fileName];
}
@end
ViewController.m文件中
随机播放
[ShortMusicPlayTool playShortMusicWithFileName:[NSString stringWithFormat:@"m_%02d.wav",arc4random_uniform(14)+3]];
利用AudioServicesPlaySystemSound播放音乐, 但是注意: 真实开发中不建议使用该函数播放音乐(.aac)
在内存警告中销毁
- (void)didReceiveMemoryWarning
{
[ShortMusicPlayTool disposeAudioWithFilename:@"buyao.wav"];
}
#import <AVFoundation/AVFoundation.h>框架
AVPlayer 音乐播放器
PKPlayerManager.h文件中
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
// 保存播放的类型
typedef NS_ENUM(NSInteger, PlayType) {
// 单曲循环
PlayTypeSingle,
// 列表播放
PlayTypeList,
// 随机播放
PlayTypeRandom
};
@interface PKPlayerManager : NSObject
// 总时间
@property (nonatomic, assign, readonly) NSUInteger finishTime;
// 当前时间
@property (nonatomic, assign, readonly) NSUInteger currentTime;
// 播放类型
@property (nonatomic, assign) PlayType playType;
@property (nonatomic, strong) AVPlayer *avPlayer; //音乐播放器
// 单例
+ (instancetype)sharedManager;
// 播放地址的数组
- (void)setManagerMusicArray:(NSArray *)array;
// 下一首的方法
- (void)nextMusic;
// 上一首的方法
- (void)beforeMusic;
// 播放/暂停
- (void)playAndPause;
// 跳转时间
- (void)seekToTime:(NSUInteger)time;
// 停止
- (void)stop;
// 根据外界传的下标来播放
- (void)playWithIndex:(NSInteger)index;
@end
#import "PKPlayerManager.h"
@interface PKPlayerManager()
@property (nonatomic, strong) NSArray *musicArray; //用来保存音乐地址的数组
@property (nonatomic, assign) NSInteger playIndex;
@end
@implementation PKPlayerManager
- (instancetype)init
{
self = [super init];
if (self) {
_avPlayer = [[AVPlayer alloc] init];
}
return self;
}
+ (instancetype)sharedManager
{
static PKPlayerManager *manager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[PKPlayerManager alloc] init];
});
return manager;
}
// 给音乐器设置播放音乐的地址的数组
- (void)setManagerMusicArray:(NSArray *)array
{
_musicArray = array;
}
// 根据外界传的下标来播放
- (void)playWithIndex:(NSInteger)index
{
_playIndex = index;//保存当前播放第几首歌
NSURL *musiceURL = [NSURL URLWithString:_musicArray[index]];
// 根据传过来的下标选择数组里响应的播放地址
AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:musiceURL];
// 把播放器的播放地址替换成新地址
[_avPlayer replaceCurrentItemWithPlayerItem:item];
[_avPlayer play];
}
// 下一首的方法
- (void)nextMusic
{
_playIndex++;
if (_playIndex == _musicArray.count) {
_playIndex = 0;
}
// 随机播放 随机给一个下标
if (_playType == PlayTypeRandom) {
_playIndex = arc4random() %_musicArray.count;
}
[self playWithIndex:_playIndex];
}
// 上一首的方法
- (void)beforeMusic
{
_playIndex--;
if (_playIndex < 0) {
_playIndex = _musicArray.count - 1;
}
// 随机播放 随机给一个下标
if (_playType == PlayTypeRandom) {
_playIndex = arc4random() %_musicArray.count;
}
[self playWithIndex:_playIndex];
}
// 播放/暂停
- (void)playAndPause
{
// 0.0表示停止播放状态 1.0正在播放
if (_avPlayer.rate == 0.0) {
[_avPlayer play];
}else{
[_avPlayer pause];
}
}
//总时间
- (NSUInteger)finishTime
{
CMTime time = _avPlayer.currentItem.duration;
if (time.timescale == 0) {
return 0;
}
return time.value / time.timescale;
}
// 当前时间
- (NSUInteger)currentTime
{
CMTime time = _avPlayer.currentTime;
if (time.timescale == 0) {
return 0;
}
return time.value / time.timescale;
}
// 跳转时间
- (void)seekToTime:(NSUInteger)time
{
CMTime newTime = _avPlayer.currentTime;
// 秒 = value / 基数
newTime.value = newTime.timescale*time;
[_avPlayer seekToTime:newTime];
}
// 停止
- (void)stop
{
[self seekToTime:0];
[_avPlayer pause];
}
@end
3 下载
协议
<NSURLSessionDelegate,NSURLConnectionDataDelegate>
@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
//开始下载
- (void)beginDownloadRequest:(PKRadioDetailModel *)model
{
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];
self.task = [_session downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:model.playInfo.musicUrl]]];
[self.task resume];
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
//location是已经下载完成的文件的位置
//通过这种方式下载的文件会被保存到一个临时文件夹里,我需要用的话应该放到我们自己的文件夹里,下载好的文件都是tmp后缀的文件
NSLog(@"%@", location);
//创建一个文件管理
NSFileManager *manager = [NSFileManager defaultManager];
NSString *fileName = [location lastPathComponent];
//tmp文件不能播放可以换一个后缀
NSString *newFileName = [fileName stringByReplacingOccurrencesOfString:@"tmp" withString:@"mp3"];
//获取Document路径
NSURL *documentURL = [[manager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
//拼接新文件的储存路径
NSURL *newFilePath = [documentURL URLByAppendingPathComponent:newFileName];
//使用文件管理类,把临时文件夹里的文件拷贝到新创建的Document目录下
[manager copyItemAtURL:location toURL:newFilePath error:nil];
//使用文件管理类手动移除临时文件夹的文件
[manager removeItemAtURL:location error:nil];
NSLog(@"%@", newFilePath);
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
[self setDownProgress:1.0*totalBytesWritten / totalBytesExpectedToWrite];
}
- (void)setDownProgress:(double)progress
{
// 注意:因为下载是在子线程中 需要回到主线程刷新数据
dispatch_async(dispatch_get_main_queue(), ^{
UIProgressView *progressView = (UIProgressView *)[self.view viewWithTag:self.row+900];
progressView.progress = progress;
UILabel *currentPressLabel = (UILabel *)[self.view viewWithTag:self.row+700];
currentPressLabel.text = [@"下载进度:" stringByAppendingFormat:@"%.2f%%",progress*100];
if (progress == 1) {
UIButton *button = (UIButton *)[self.view viewWithTag:self.row+800];
[button setBackgroundImage:[UIImage imageNamed:@"iconfont-xiazaiwancheng.png"] forState:UIControlStateNormal];
}
});
}
后台播放音乐
// http://www.iliunian.com/2831.html
原文:http://www.cnblogs.com/xiaochong1234/p/4960341.html