[英]Add fading effect in songs playlist using AVAudioPlayer and MPMusicPlayerController in ios
I need to add fade in/out feature in songs playlist (playlist songs are retrive from ipod library). 我需要在歌曲播放列表中添加淡入/淡出功能(播放列表中的歌曲是从ipod库中检索的)。 When one song end i need to fade out effect and next song start i need to fade in effect and one other think during fading system or media VOLUME should not changed.
当一首歌曲结束时,我需要淡出效果,而下一首歌曲开始时,我需要淡出效果,而另一首则认为在衰落系统或媒体期间,音量不应该改变。
I am using MPMusicPlayerController for play song. 我正在使用MPMusicPlayerController播放歌曲。
Here is an extension to AVAudioPlayer that I wrote (pre-ARC) that does exactly what you want. 这是我编写的AVAudioPlayer扩展(ARC以前的版本),可以完全满足您的需求。
The header AVAudioPlayer+FadeControl.h
: 头文件
AVAudioPlayer+FadeControl.h
:
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
@interface AVAudioPlayer (FadeControl)
-(void)fadeOutWithDuration:(NSTimeInterval)inFadeOutTime;
@end
And the source AVAudioPlayer+FadeControl.m
: 以及源
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
It should be trivial to ad an playWithFadeInDuration:
method. 广告
playWithFadeInDuration:
方法应该很简单。 To use in an ARC project, just add -fno-objc-arc
to the file's compile flags. 要在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];
}
}
And can use the opposite approach for fading out the volume. 并可以使用相反的方法淡出音量。 Hope this helps.
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.