簡體   English   中英

在iOS中使用AVAudioPlayer和MPMusicPlayerController在歌曲播放列表中添加漸變效果

[英]Add fading effect in songs playlist using AVAudioPlayer and MPMusicPlayerController in ios

我需要在歌曲播放列表中添加淡入/淡出功能(播放列表中的歌曲是從ipod庫中檢索的)。 當一首歌曲結束時,我需要淡出效果,而下一首歌曲開始時,我需要淡出效果,而另一首則認為在衰落系統或媒體期間,音量不應該改變。

我正在使用MPMusicPlayerController播放歌曲。

這是我編寫的AVAudioPlayer擴展(ARC以前的版本),可以完全滿足您的需求。

頭文件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添加到文件的編譯標志即可。

-(void)doFadeInVolume { 

//play
[audioPlayerMain play];

if (audioPlayerMain.volume < 1.0) {
audioPlayerMain.volume = audioPlayerMain.volume + 0.1;
[self performSelector:@selector(doVolumeFadeMainIn) withObject:nil afterDelay:0.2];
} 
}

並可以使用相反的方法淡出音量。 希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM