我正在创建一个可以淡入淡出音乐的程序。问题是其他线程/队列可以暂停音乐,这意味着淡入和淡出不仅需要暂停,还需要暂停。我需要能够在 dispatch_after 上暂停“计时器”(因为在音乐开始播放时调用它以告诉它何时开始淡出,如果它被暂停则需要延迟)并暂停队列本身(为了在淡入或淡出时暂停淡入或淡出)
这是代码(fadeIn 和 delayFadeOut 都在程序开始时调用):
- (void) doFadeIn: (float) incriment to: (int) volume with: (AVAudioPlayer*) thisplayer on: (dispatch_queue_t) queue{
dispatch_async(queue, ^{
double delayInSeconds = .1;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, queue, ^(void){
thisplayer.volume = (thisplayer.volume + incriment) < volume ? thisplayer.volume + incriment : volume;
NSLog([[[NSNumber alloc] initWithFloat:thisplayer.volume] stringValue]);
if (thisplayer.volume < volume) {
[self doFadeIn:incriment to:volume with:thisplayer on:queue];
}
});
});
}
-(void) doDelayFadeOut: (float) incriment with: (AVAudioPlayer*) thisplayer on: (dispatch_queue_t) queue
{
dispatch_async(queue, ^{
double delayInSeconds = .1;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, queue, ^(void){
thisplayer.volume = (thisplayer.volume - incriment) > 0 ? thisplayer.volume - incriment : 0;
NSLog([[[NSNumber alloc] initWithFloat:thisplayer.volume] stringValue]);
if (thisplayer.volume > 0.0) {
[self doDelayFadeOut:incriment with:thisplayer on:queue];
}
});
});
}
-(void) fadeIn: (AVAudioPlayer*) dFade {
if (dFade == nil) {
return;
}
dispatch_queue_t queue = dispatch_queue_create("com.cue.MainFade", NULL);
dispatch_async( queue, ^(void){
if(dFade !=nil){
double incriment = ([self relativeVolume] / [self fadeIn]) / 10; //incriment per .1 seconds.
[self doFadeIn: incriment to: [self relativeVolume] with:dFade on:dispatch_queue_create("com.cue.MainFade", 0)];
}
});
}
- (void) delayFadeOut: (AVAudioPlayer*) dFade { //d-fade should be independent of other threads
if (dFade == nil) {
return;
}
int timeRun = self.duration - self.fadeOut;
dispatch_queue_t queue = dispatch_queue_create("com.cue.MainFade", NULL);
dispatch_time_t mainPopTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeRun * NSEC_PER_SEC));
printf("test");
dispatch_after(mainPopTime, queue, ^(void){
if(dFade !=nil){
double incriment = ([dFade volume] / [self fadeOut])/10; //incriment per .1 seconds.
[self doDelayFadeOut:incriment with:dFade on:dispatch_queue_create("com.cue.MainFade", 0)];
}
});
if (self.cueType == 2) {
[self callNext];
}
}