1.导入AVFoundation.framework
2.在头部导入
#import <AVFoundation/AVFoundation.h>
3.创建一个继承AVAudioPlayer的工具类
//MyAVAudioPlayer.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface MyAVAudioPlayer : AVAudioPlayer
@property(nonatomic,strong) AVAudioPlayer *player;
-(instancetype)init;
+(instancetype)sharedAVAudioPlayer;
//通过传递的歌曲名称进行播放
-(void)playMusicWithMusicName:(NSString *)musicName;
//开始或暂停
-(void)playOrStopMusic;
@end
//MyAVAudioPlayer.m
#import "MyAVAudioPlayer.h"
@implementation MyAVAudioPlayer
static NSMutableDictionary *_players;
-(instancetype)init{
if (self == [super init]) {
}
return self;
}
#pragma mark 单例模式(避免同时播放多首歌)
+(instancetype)sharedAVAudioPlayer{
static MyAVAudioPlayer *sharedAccountManagerInstance = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
sharedAccountManagerInstance = [[self alloc] init];
});
return sharedAccountManagerInstance;
}
#pragma mark 通过音乐名称播放音乐
-(void)playMusicWithMusicName:(NSString *)musicName{
// 2.1.获取对应音乐资源
NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:musicName withExtension:@"mp3"];
if (fileUrl == nil) return;
// 2.2.创建对应的播放器
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:nil];
// 2.4.准备播放
[_player prepareToPlay];
// 3.播放音乐
[_player play];
}
-(void)playOrStopMusic{
if ([_player isPlaying]) {
[_player pause];
return;
}
[_player play];
}
源码下载地址:百度网盘链接 - 密码: 47yx