[英]How to perform operations when playing sound in iPhone?
我使用AVAudioPlayer在我的iPhone应用程序中播放MP3; 我需要在某些时间执行某些操作(比如30秒,1分钟); 有没有办法根据mp3播放时间调用回调函数?
我相信最好的解决方案是在启动AVAudioPlayer
播放时启动NSTimer
。 您可以将计时器设置为每半秒左右触发一次。 然后每次计时器触发时,查看音频播放器上的currentTime
属性。
为了按特定时间间隔执行某些操作,我建议您为上次调用计时器回调时的回放时间保留一个实例变量。 然后,如果您已经通过了上次回调和此之间的关键点,请执行您的操作。
所以,在伪代码中,定时器回调:
currentTime
currentTime
是否大于criticalPoint
lastCurrentTime
是否小于criticalPoint
lastCurrentTime
设置为currentTime
如果您能够使用AVPlayer而不是AVAudioPlayer,则可以设置边界或周期时间观察器:
// File URL or URL of a media library item
AVPlayer *player = [[AVPlayer alloc] initWithURL:url];
CMTime time = CMTimeMakeWithSeconds(30.0, 600);
NSArray *times = [NSArray arrayWithObject:[NSValue valueWithCMTime:time]];
id playerObserver = [player addBoundaryTimeObserverForTimes:times queue:NULL usingBlock:^{
NSLog(@"Playback time is 30 seconds");
}];
[player play];
// remove the observer when you're done with the player:
[player removeTimeObserver:playerObserver];
AVPlayer文档: http : //developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVPlayer_Class/Reference/Reference.html
我发现这个链接描述了一个属性属性,它似乎表明你可以获得当前的播放时间。
如果正在播放声音,则currentTime是当前播放位置的偏移量,以声音开始时的秒数为单位进行测量。 如果没有播放声音,则currentTime是在调用播放方法时开始播放的偏移量,以声音开始时的秒数为单位进行测量。
通过设置此属性,您可以搜索声音文件中的特定点或实现音频快进和快退功能。
要检查时间并执行操作,您只需查询它:
if (avAudioPlayerObject.currentTime == 30.0) //You may need a more broad check. Double may not be able to exactly represent 30.0s
{
//Do Something
}
是的,你可以......这很棘手,我希望它适合你,但它对我有用..
1- you play your mp3 file.
2- [self performSelector:@selector(Operation:) withObject:Object afterDelay:30];
那么功能
-(void)Operation:(id)sender;
所谓的; 所以你在30秒的mp3文件后解雇了函数..你可以根据你想要的时间做很多功能..
3-使用定时器还有其他解决方案
[NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(CheckTime:) userInfo:nil repeats:YES];
它将触发名为Check Time的功能
-(void)CheckTime:(id)sender{
if (avAudioPlayerObject.currentTime == 30.0)
{
//Do Something
//Fire and function call such
[self performSelector:@selector(Operation:) withObject:Object]
}
}
然后你可以改变你想要的时间间隔,重复是你控制每5秒钟重复一次这个动作。希望有用..
谢谢
多线程你的目标很简单,只需这样做:
1 : in your main thread create a variable for storing time passed
2 : create new thread like "checkthread" that check each 30-20 sec(as you need)
3 : if the time passed is what you want do the callback
我想,你想在30秒后播放不同的声音文件,然后使用这段代码:
1)将所有声音文件放入Array中,然后从文档目录中检索
2)然后试试这个:
-(IBAction)play_sound
{
BackgroundPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:[Arr_tone_selected objectAtIndex:j]ofType:@"mp3"]]error:NULL];
BackgroundPlayer.delegate=self;
[BackgroundPlayer play];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
[BackgroundPlayer stop];
j++;
[self performSelector:@selector(play_sound) withObject:Object afterDelay:30];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.