作品链接:
http://www.jianshu.com/users/1e0f5e6f73f6/top_articles
1.导入框架
#import <AVFoundation/AVFoundation.h>
2.初始化字典
static NSMutableDictionary *_players;
+ (void)initialize
{
_players = [NSMutableDictionary dictionary];
}
3.点击事件的处理
// 开始播放
- (IBAction)start {
[PHAudioTool playMusicWithSoundName:@"播放文件名称"];
}
//暂停播放
- (IBAction)pause {
[PHAudioTool pauseMusicWithSoundName:@"播放文件名称"];
}
//停止播放
- (IBAction)stop {
[PHAudioTool stopMusicWithSoundName:@"播放文件名称"];
}
4.播放音乐
+ (void)playMusicWithSoundName:(NSString *)fileName
{
// 1.创建空播放器
AVAudioPlayer *player = nil;
// 2.从字典中取出播放器
player = _players[fileName];
// 3.判断字典是否为空
if (player == nil) {
// 4.生成对应的音乐文件
NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:fileName withExtension:nil];
// 5.创建对应的播放器
player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:nil];
// 6.保存到字典中
[_players setObject:player forKey:fileName];
// 7.准备播放
[player prepareToPlay];
}
// 8.开始播放
[player play];
}
5.暂停音乐
+ (void)pauseMusicWithSoundName:(NSString *)fileName
{
// 1.从字典中取出播放器
AVAudioPlayer *player = _players[fileName];
// 2.暂停音乐
if (player) {
[player pause];
}
}
6.停止音乐
+ (void)stopMusicWithSoundName:(NSString *)fileName
{
// 1.从字典中取出播放器
AVAudioPlayer *player = _players[fileName];
// 2.停止音乐
if (player) {
[player stop];
[_players removeObjectForKey:fileName];
player = nil;
}
```
注意:AVAudioPlayer播放值适用于本地文件
```