AVAdioPlayer方法介紹及相關(guān)知識(shí)介紹
1.導(dǎo)入AVFoundation.framework
2.在頭部導(dǎo)入
#import <AVFoundation/AVFoundation.h>
3.創(chuàng)建一個(gè)繼承AVAudioPlayer的工具類
//MyAVAudioPlayer.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface MyAVAudioPlayer : AVAudioPlayer
@property(nonatomic,strong) AVAudioPlayer *player;
-(instancetype)init;
+(instancetype)sharedAVAudioPlayer;
//通過(guò)傳遞的歌曲名稱進(jìn)行播放
-(void)playMusicWithMusicName:(NSString *)musicName;
//開(kāi)始或暫停
-(void)playOrStopMusic;
@end
//MyAVAudioPlayer.m
#import "MyAVAudioPlayer.h"
@implementation MyAVAudioPlayer
static NSMutableDictionary *_players;
-(instancetype)init{
if (self == [super init]) {
}
return self;
}
#pragma mark 單例模式(避免同時(shí)播放多首歌)
+(instancetype)sharedAVAudioPlayer{
static MyAVAudioPlayer *sharedAccountManagerInstance = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
sharedAccountManagerInstance = [[self alloc] init];
});
return sharedAccountManagerInstance;
}
#pragma mark 通過(guò)音樂(lè)名稱播放音樂(lè)
-(void)playMusicWithMusicName:(NSString *)musicName{
// 2.1.獲取對(duì)應(yīng)音樂(lè)資源
NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:musicName withExtension:@"mp3"];
if (fileUrl == nil) return;
// 2.2.創(chuàng)建對(duì)應(yīng)的播放器
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:nil];
// 2.4.準(zhǔn)備播放
[_player prepareToPlay];
// 3.播放音樂(lè)
[_player play];
}
-(void)playOrStopMusic{
if ([_player isPlaying]) {
[_player pause];
return;
}
[_player play];
}
源碼下載地址:百度網(wǎng)盤(pán)鏈接 - 密碼: 47yx