播放音效
#import <AVFoundation/AVFoundation.h>
//1.獲取資源文件的URL
NSURL *url = [[NSBundle mainBundle]URLForResource:@"m_03.wav" withExtension:nil];
//2.創(chuàng)建音效ID,一個音效文件對應(yīng)一個SoundID
SystemSoundID soundID;
AudioServicesCreateSystemSoundID(CFBridgingRetain(url), &soundID);
//播放音效并震動(真機)
// AudioServicesPlayAlertSound(soundID);
//3.播放音效
AudioServicesPlaySystemSound(soundID);
音效工具類
#import "SoundTool.h"
#import <AVFoundation/AVFoundation.h>
@interface SoundTool()
//字典
//@property (nonatomic,strong)NSMutableDictionary *dict;
@end
@implementation SoundTool
static NSMutableDictionary *_dict;
//加載類的時候調(diào)用,只會在第一次使用的時候調(diào)用(導(dǎo)入類就會調(diào)用)
+(void)load {
_dict = [NSMutableDictionary dictionary];
}
//使用類時才會調(diào)用
+(void)initialize{}
+(void)playSoundWithFileName:(NSString *)fileName{
//key:fileName value:soundID
//1.判斷fileName是否有值
if(fileName.length == 0) return;
//2.判斷soundID是否有值
//2.1獲取sundID
SystemSoundID soundID = [_dict[fileName] unsignedIntValue];
//判斷
if(!soundID){
//3.創(chuàng)建soundID
NSURL *url = [[NSBundle mainBundle]URLForResource:fileName withExtension:nil];
AudioServicesCreateSystemSoundID(CFBridgingRetain(url), &soundID);
if(!url) return;
//加入到字典
_dict[fileName] = @(soundID);
}
//4.播放音效
AudioServicesPlaySystemSound(soundID);
}
+(void)disposeSoundIDWithFileName:(NSString *)fileName{
if(fileName.length == 0) return;
//獲取soundID
SystemSoundID soundID = [_dict[fileName] unsignedIntValue];
//判斷是否有值
if(soundID){
AudioServicesDisposeSystemSoundID(soundID);
//從字典移除
[_dict removeObjectForKey:fileName];
}
}
@end
音樂
@property(nonatomic,strong)AVAudioPlayer *audioPlayer;
//0.創(chuàng)建音頻播放的url
NSURL *url = [[NSBundle mainBundle]URLForResource:@"童話.mp3" withExtension:nil];
//1,創(chuàng)建音頻播放對象
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
self.audioPlayer = audioPlayer;
//2.準備播放 開辟內(nèi)存空間,做播放前的準備工作 如果不調(diào)用,默認在播放時調(diào)用
[audioPlayer prepareToPlay];
//3.播放
[audioPlayer play];
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者