iphone - 在 ios 中使用 AVAudioPlayer 和 MPMusicPlayerController 在歌曲播放列表中添加淡入淡出效果

标签 iphone ios

我需要在歌曲播放列表中添加淡入/淡出功能(播放列表歌曲是从 ipod 库中检索的)。 当一首歌结束时我需要淡出效果而下一首歌曲开始时我需要淡入效果 另一个认为在衰落期间系统或媒体 VOLUME 不应更改。

我正在使用 MPMusicPlayerController 来播放歌曲。

最佳答案

这是我编写的(ARC 之前的)AVAudioPlayer 的扩展,它完全符合您的要求。

header AVAudioPlayer+FadeControl.h:

#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>


@interface AVAudioPlayer (FadeControl)

-(void)fadeOutWithDuration:(NSTimeInterval)inFadeOutTime;

@end

和源代码AVAudioPlayer+FadeControl.m:

#import "AVAudioPlayer+FadeControl.h"

#define     kFadeSteps  20.0

@implementation AVAudioPlayer (FadeControl)

-(void)fadeOutWithDuration:(NSTimeInterval)inFadeOutTime
{
    NSTimeInterval fireInterval = inFadeOutTime/kFadeSteps;
    float volumeDecrement = 1.0/kFadeSteps;
    float originalVolume = self.volume;

    self.volume = originalVolume - volumeDecrement;

    [self retain];
    [NSTimer scheduledTimerWithTimeInterval:fireInterval target:self selector:@selector(fadeOutTimerMethod:) userInfo:[NSNumber numberWithFloat:originalVolume] repeats:YES];

}

- (void)fadeOutTimerMethod:(NSTimer*)theTimer   
{
    float volumeDecrement = 1.0/kFadeSteps;

    if (self.volume > volumeDecrement)
    {
        self.volume = self.volume - volumeDecrement;
    }
    else if ( [theTimer isValid] )
    {
        [self stop];

        NSNumber* originalVolume = [theTimer userInfo];
        self.volume = [originalVolume floatValue];

        [theTimer invalidate];
    }
    else 
    {
        [self stop];
        [self release];
    }


}

@end

添加一个 playWithFadeInDuration: 方法应该很简单。要在 ARC 项目中使用,只需将 -fno-objc-arc 添加到文件的编译标志中即可。

关于iphone - 在 ios 中使用 AVAudioPlayer 和 MPMusicPlayerController 在歌曲播放列表中添加淡入淡出效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13872707/

相关文章:

iphone - 我们应该使用哪些 iOS 设备来进行合理的功能和性能测试?

iphone - 右栏按钮动画不正确

iphone - iOS5 AVFoundation 图片转视频

ios - SIGABRT线程错误运行简单的iOS应用程序

ios - 向 UIScrollView 中的标准 Pan Gesture Recognizer 添加功能

ios - 在 Swift 中以编程方式添加时,UIScrollView 根本不滚动吗?

iOS paypal API - 苹果拒绝

iphone - iOS。应用程序更新后保护设置不被重置?

iphone - 显示 NSArray 中的每个对象 2 秒

ios - MapBox iOS 不同的标记图像?