作品鏈接:
http://www.itdecent.cn/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.創(chuàng)建空播放器
AVAudioPlayer *player = nil;
// 2.從字典中取出播放器
player = _players[fileName];
// 3.判斷字典是否為空
if (player == nil) {
// 4.生成對應的音樂文件
NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:fileName withExtension:nil];
// 5.創(chuàng)建對應的播放器
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播放值適用于本地文件
```