[英]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.