音效 音乐

播放音效

#import 
//1.获取资源文件的URL
    NSURL *url = [[NSBundle mainBundle]URLForResource:@"m_03.wav" withExtension:nil];
    
    //2.创建音效ID,一个音效文件对应一个SoundID
    SystemSoundID soundID;
    AudioServicesCreateSystemSoundID(CFBridgingRetain(url), &soundID);
    
    //播放音效并震动(真机)
    //    AudioServicesPlayAlertSound(soundID);
    //3.播放音效
    AudioServicesPlaySystemSound(soundID);

音效工具类

#import "SoundTool.h"
#import 
@interface SoundTool()
//字典
//@property (nonatomic,strong)NSMutableDictionary *dict;
@end

@implementation SoundTool
static NSMutableDictionary *_dict;
//加载类的时候调用,只会在第一次使用的时候调用(导入类就会调用)
+(void)load {
    _dict = [NSMutableDictionary dictionary];
}
//使用类时才会调用
+(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.创建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.创建音频播放的url
    NSURL *url = [[NSBundle mainBundle]URLForResource:@"童话.mp3" withExtension:nil];
    //1,创建音频播放对象
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    self.audioPlayer = audioPlayer;
    //2.准备播放 开辟内存空间,做播放前的准备工作 如果不调用,默认在播放时调用
    [audioPlayer prepareToPlay];
    //3.播放
    [audioPlayer play];

你可能感兴趣的:(音效 音乐)