iOS开发--音乐文件播放工具类的封装(包含了音效的封装)

时间:2022-07-28 19:47:42

iOS开发--音乐文件播放工具类的封装(包含了音效的封装)

一.头文件

 1 #import <Foundation/Foundation.h>
2 #import <AVFoundation/AVFoundation.h>
3
4 @interface ChaosAudioTool : NSObject
5
6 #pragma mark - 播放音乐
7 // 播放音乐 musicName : 音乐的名称
8 + (AVAudioPlayer *)playMusicWithMusicName:(NSString *)musicName;
9 // 暂停音乐 musicName : 音乐的名称
10 + (void)pauseMusicWithMusicName:(NSString *)musicName;
11 // 停止音乐 musicName : 音乐的名称
12 + (void)stopMusicWithMusicName:(NSString *)musicName;
13
14 #pragma mark - 音效播放
15 // 播放声音文件soundName : 音效文件的名称
16 + (void)playSoundWithSoundname:(NSString *)soundname;
17
18 @end

二..m文件方法的实现

 1 #import "ChaosAudioTool.h"
2
3 @implementation ChaosAudioTool
4
5 static NSMutableDictionary *_soundIDs;
6 static NSMutableDictionary *_players;
7
8 + (void)initialize
9 {
10 _soundIDs = [NSMutableDictionary dictionary];
11 _players = [NSMutableDictionary dictionary];
12 }
13
14 + (AVAudioPlayer *)playMusicWithMusicName:(NSString *)musicName
15 {
16 assert(musicName);
17
18 // 1.定义播放器
19 AVAudioPlayer *player = nil;
20
21 // 2.从字典中取player,如果取出出来是空,则对应创建对应的播放器
22 player = _players[musicName];
23 if (player == nil) {
24 // 2.1.获取对应音乐资源
25 NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:musicName withExtension:nil];
26
27 if (fileUrl == nil) return nil;
28
29 // 2.2.创建对应的播放器
30 player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:nil];
31
32 // 2.3.将player存入字典中
33 [_players setObject:player forKey:musicName];
34
35 // 2.4.准备播放
36 [player prepareToPlay];
37 }
38
39 // 3.播放音乐
40 [player play];
41
42 return player;
43 }
44
45 + (void)pauseMusicWithMusicName:(NSString *)musicName
46 {
47 assert(musicName);
48
49 // 1.取出对应的播放
50 AVAudioPlayer *player = _players[musicName];
51
52 // 2.判断player是否nil
53 if (player) {
54 [player pause];
55 }
56 }
57
58 + (void)stopMusicWithMusicName:(NSString *)musicName
59 {
60 assert(musicName);
61
62 // 1.取出对应的播放
63 AVAudioPlayer *player = _players[musicName];
64
65 // 2.判断player是否nil
66 if (player) {
67 [player stop];
68 [_players removeObjectForKey:musicName];
69 player = nil;
70 }
71 }
72
73 #pragma mark - 音效的播放
74 + (void)playSoundWithSoundname:(NSString *)soundname
75 {
76 // 1.定义SystemSoundID
77 SystemSoundID soundID = 0;
78
79 // 2.从字典中取出对应soundID,如果取出是nil,表示之前没有存放在字典
80 soundID = [_soundIDs[soundname] unsignedIntValue];
81 if (soundID == 0) {
82 CFURLRef url = (__bridge CFURLRef)[[NSBundle mainBundle] URLForResource:soundname withExtension:nil];
83
84 if (url == NULL) return;
85
86 AudioServicesCreateSystemSoundID(url, &soundID);
87
88 // 将soundID存入字典
89 [_soundIDs setObject:@(soundID) forKey:soundname];
90 }
91
92 // 3.播放音效
93 AudioServicesPlaySystemSound(soundID);
94 }
95
96 @end