简单的实现播放背景音乐(淡入淡出效果)

最近在开发幻灯片的需求,首先确认项目里已经加入AudioToolbox.framework。

在此放上背景音乐播放的代码,添加淡入淡出效果,重温一下计时器的知识点。

头文件 QZSoundBoard.h 内容如下

#import 
#import 

@interface QZSoundBoard : NSObject

+ (void)addSoundAtPath:(NSString *)filePath forKey:(id)key;
+ (void)playSoundForKey:(id)key;

+ (void)addAudioAtPath:(NSString *)filePath forKey:(id)key;

+ (void)playAudioForKey:(id)key fadeInInterval:(NSTimeInterval)fadeInInterval;
+ (void)playAudioForKey:(id)key;

+ (void)stopAudioForKey:(id)key fadeOutInterval:(NSTimeInterval)fadeOutInterval;
+ (void)stopAudioForKey:(id)key;

+ (void)pauseAudioForKey:(id)key fadeOutInterval:(NSTimeInterval)fadeOutInterval;
+ (void)pauseAudioForKey:(id)key;

+ (AVAudioPlayer *)audioPlayerForKey:(id)key;

@end

 QZSoundBoard.m 内容如下

#import "QZSoundBoard.h"
#import 

#define QZSOUNDBOARD_AUDIO_FADE_STEPS   30

@implementation QZSoundBoard {
    NSMutableDictionary *_sounds;
    NSMutableDictionary *_audio;
}

+ (QZSoundBoard *)sharedInstance
{
    static id _sharedObject = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedObject = [[self alloc] init];
    });
    return _sharedObject;
}

- (id)init
{
    self = [super init];
    if (self != nil) {
        _sounds = [NSMutableDictionary dictionary];
        _audio = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)addSoundAtPath:(NSString *)filePath forKey:(id)key
{
    NSURL* fileURL = [NSURL fileURLWithPath:filePath];
    SystemSoundID soundId;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)fileURL, &soundId);
    
    [_sounds setObject:[NSNumber numberWithInt:soundId] forKey:key];
}

+ (void)addSoundAtPath:(NSString *)filePath forKey:(id)key
{
    [[self sharedInstance] addSoundAtPath:filePath forKey:key];
}

- (void)playSoundForKey:(id)key
{
    SystemSoundID soundId = [(NSNumber *)[_sounds objectForKey:key] intValue];
    AudioServicesPlaySystemSound(soundId);
}

+ (void)playSoundForKey:(id)key
{
    [[self sharedInstance] playSoundForKey:key];
}

- (void)addAudioAtPath:(NSString *)filePath forKey:(id)key
{
    NSURL* fileURL = [NSURL fileURLWithPath:filePath];
    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:NULL];
    [_audio setObject:player forKey:key];
}

+ (void)addAudioAtPath:(NSString *)filePath forKey:(id)key
{
    [[self sharedInstance] addAudioAtPath:filePath forKey:key];
}

- (void)fadeIn:(NSTimer *)timer
{
    AVAudioPlayer *player = timer.userInfo;
    float volume = player.volume;
    volume = volume + 1.0 / QZSOUNDBOARD_AUDIO_FADE_STEPS;
    volume = volume > 1.0 ? 1.0 : volume;
    player.volume = volume;
    
    if (volume == 1.0) {
        [timer invalidate];
    }
}

- (void)playAudioForKey:(id)key fadeInInterval:(NSTimeInterval)fadeInInterval
{
    AVAudioPlayer *player = [_audio objectForKey:key];
    
    if (fadeInInterval > 0.0) {
        player.volume = 0.0;
        NSTimeInterval interval = fadeInInterval / QZSOUNDBOARD_AUDIO_FADE_STEPS;
        [NSTimer scheduledTimerWithTimeInterval:interval
                                         target:self
                                       selector:@selector(fadeIn:)
                                       userInfo:player
                                        repeats:YES];
    }
    
    [player play];
}

+ (void)playAudioForKey:(id)key fadeInInterval:(NSTimeInterval)fadeInInterval
{
    [[self sharedInstance] playAudioForKey:key fadeInInterval:fadeInInterval];
}

+ (void)playAudioForKey:(id)key
{
    [[self sharedInstance] playAudioForKey:key fadeInInterval:0.0];
}


- (void)fadeOutAndStop:(NSTimer *)timer
{
    AVAudioPlayer *player = timer.userInfo;
    float volume = player.volume;
    volume = volume - 1.0 / QZSOUNDBOARD_AUDIO_FADE_STEPS;
    volume = volume < 0.0 ? 0.0 : volume;
    player.volume = volume;
    
    if (volume == 0.0) {
        [timer invalidate];
        [player stop];
    }
}

- (void)stopAudioForKey:(id)key fadeOutInterval:(NSTimeInterval)fadeOutInterval
{
    AVAudioPlayer *player = [_audio objectForKey:key];
    
    if (fadeOutInterval > 0) {
        NSTimeInterval interval = fadeOutInterval / QZSOUNDBOARD_AUDIO_FADE_STEPS;
        [NSTimer scheduledTimerWithTimeInterval:interval
                                         target:self
                                       selector:@selector(fadeOutAndStop:)
                                       userInfo:player
                                        repeats:YES];
    } else {
        [player stop];
    }
}

+ (void)stopAudioForKey:(id)key fadeOutInterval:(NSTimeInterval)fadeOutInterval
{
    [[self sharedInstance] stopAudioForKey:key fadeOutInterval:fadeOutInterval];
}

+ (void)stopAudioForKey:(id)key
{
    [[self sharedInstance] stopAudioForKey:key fadeOutInterval:0.0];
}


- (void)fadeOutAndPause:(NSTimer *)timer
{
    AVAudioPlayer *player = timer.userInfo;
    float volume = player.volume;
    volume = volume - 1.0 / QZSOUNDBOARD_AUDIO_FADE_STEPS;
    volume = volume < 0.0 ? 0.0 : volume;
    player.volume = volume;
    
    if (volume == 0.0) {
        [timer invalidate];
        [player pause];
    }
}

- (void)pauseAudioForKey:(id)key fadeOutInterval:(NSTimeInterval)fadeOutInterval
{
    AVAudioPlayer *player = [_audio objectForKey:key];
    
    if (fadeOutInterval > 0) {
        NSTimeInterval interval = fadeOutInterval / QZSOUNDBOARD_AUDIO_FADE_STEPS;
        [NSTimer scheduledTimerWithTimeInterval:interval
                                         target:self
                                       selector:@selector(fadeOutAndPause:)
                                       userInfo:player
                                        repeats:YES];
    } else {
        [player pause];
    }
}


+ (void)pauseAudioForKey:(id)key fadeOutInterval:(NSTimeInterval)fadeOutInterval
{
    [[self sharedInstance] pauseAudioForKey:key fadeOutInterval:fadeOutInterval];
}

+ (void)pauseAudioForKey:(id)key
{
    [[self sharedInstance] pauseAudioForKey:key fadeOutInterval:0.0];
}


- (AVAudioPlayer *)audioPlayerForKey:(id)key
{
    return [_audio objectForKey:key];
}

+ (AVAudioPlayer *)audioPlayerForKey:(id)key
{
    return [[self sharedInstance] audioPlayerForKey:key];
}

@end

总结:使用函数AudioServicesCreateSystemSoundID 和AudioServicePlaySystemSound 来创建和播放声音

还需要声明一个类型为SystemSoundID的变量表示我们要用的声音

-(IBAction)doSound:(id)sender

{

SystemSoundID soundID;

NSString *soundFile=[[NSBundle mainbundle]pathForResource:@"soundeffect" ofType:@"wav"];

AudioServicesCreateSystemSoundId((CFURLRef)[NSURL fileURLWithPath:soundFile],&soundId);

//确定声音文件的路径后,使用函数AudioSerivcesCreatesystemsoundid来创建一个代表该文件的systemid供实际播放声音的函数使用,这个函数有两个参数,一个是指向文件位置的CFURLRef和一个指向声音文件systemsoundid的指针。我们将nsurl强转成函数要求的CFURLRef类型。

AudioServicesPlaySystemSound(soundID)//播放声音只需将变量soundid传递给此函数就可以了

}

我们还可以播放警告声音和振动我们只需复制以上代码,使用函数AudioServicesPlayAlertSound即可。

振动iphone的方法也很简单只需AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)即可

你可能感兴趣的:(ios修炼之旅)