首先包含头文件
#import <AVFoundation/AVFoundation.h>
代理
AVAudioPlayerDelegate
创建播放器
NSURL * url = [[NSURL alloc]initFileURLWithPath:[[NSBundle mainBundle] pathForResource:@"歌曲名"] ofType:@"mp3"]];
play = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
play.delegate = self;
play.volume 播放音量
//准备播放
[play prepareToPlay];
//播放
[play play];
//结束播放
代理方法 判断一首歌播放完成后是否下一曲播放
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
//解析当前文件的信息 可解析mp3格式
AVURLAsset * asset = [AVURLAsset URLAssetWithURL:url options:nil];
// NSArray * array = [asset metadataForFormat:@"org.id3"];
NSArray * metadata = [asset commonMetadata];
for (AVMetadataItem * item in metadata) {
//NSLog(@"%@",(NSString*)item.value);
if ([item.commonKey isEqualToString:@"title"]) {
self.musicLabel.text = (NSString*)item.value;
}
if ([item.commonKey isEqualToString:@"artist"]) {
// NSLog(@"%@",(NSString*)item.value);
}
if ([item.commonKey isEqualToString:@"artwork"]) {
NSData * data = (NSData*)item.value;
UIImage * image = [UIImage imageWithData:data];
self.musicBackImage.image = image;
}
if ([item.commonKey isEqualToString:@"albumName"]) {
//NSLog(@"专辑名%@",item.value);
}
}
如果工程里面自带的有语音播放功能,一般创建一个单例类的语音播放
<平遥项目>
1.首先建立一个继承于NSObjet的类 添加头文件
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
@interface PlayManager : NSObject{
}
//控制播放器的单例
+(instancetype)shareManager;
@property(nonatomic,strong)AVAudioPlayer*player;
2.添加播放功能
//初始化播放器
-(void)returnPlayer:(NSString*)url;
//准备播放
- (void)preparePlay;
//播放
- (void)play;
//停止播放
- (void)stop;
//是否播放
-(BOOL)isPlay;
@end
#import "PlayManager.h"
static PlayManager* play;
static NSString * lastUrl;
@implementation PlayManager
+(instancetype)shareManager{
在工程中输入关键字dispatch_once_t即可出现提示
//GCD 也就是线程 而且全部是block 苹果主力推荐
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
play = [[PlayManager alloc]init];
});
return play;
}
-(void)returnPlayer:(NSString*)url{
if ([lastUrl isEqualToString:url]) {
return;
}
lastUrl = url;
[play.player stop];
play.player = nil;
play.player = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:url] error:nil];
}
//准备播放
- (void)preparePlay{
[play.player prepareToPlay];
}
//播放
- (void)play{
[play.player play];
}
//停止播放
- (void)stop{
[play.player stop];
}
//是否播放
-(BOOL)isPlay{
return play.player.isPlaying;
}
@end