我想創建一個具有啓動/停止功能的音樂播放器。我通過啓動一個while循環來實現這一點,如果布爾值爲true,則會循環。這個while循環包含在一個單獨的線程中。我在viewDidLoad方法開始這個線程:NSThread雖然基於布爾 - 音樂播放器啓動/停止循環 - IOS
[[CoreDataHelper getEditableSong].audioPlayer playOrStopSong];
playOrStopSong看起來是這樣的:
- (void) playOrStopSong {
NSLog(@"%d --- before switch", playing);
if (playing) {
playing = NO;
}
else{
playing = YES;
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
}
NSLog(@"%d --- after switch", playing);
}
我的run方法看起來是這樣的(其中大部分可能是不重要的):
- (void) run {
@autoreleasepool {
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(handleTimer:) userInfo:nil repeats:NO];
xPlayPosition = 0;
NSLog(@"thread started!");
while (playing) {
NSLog(@"lots of playings -- %d", playing);
NSMutableDictionary *notesAtCurrentX = [song.noteDict objectForKey:[NSNumber numberWithInt:xPlayPosition]];
if (notesAtCurrentX != nil) {
NSString *currentTemplate = [song.soundTemplate objectAtIndex:(NSUInteger) (xPlayPosition/NOTES_PER_TEMPLATE)];
[self playColumnWithTemplate:currentTemplate andNotesAtCurrentX:notesAtCurrentX andCurrentX:xPlayPosition];
}
[NSThread sleepForTimeInterval:30/[song.tempo floatValue]];
xPlayPosition += 1;
if (xPlayPosition > [song.length intValue]-1) {
xPlayPosition = 0;
[myComposeViewController performSelectorOnMainThread: @selector(animatePlaybackLine) withObject:nil waitUntilDone:NO];
}
}
NSLog(@"thread stopped!");
[NSThread exit];
}
}
此線程脫離並運行,就像它應該。日誌打印如下:
0 --- before switch
thread started!
1 --- after switch
然後繼續打印「很多playings - 1」一堆次。
但是,當我嘗試再次調用playOrStopSong方法,而不是停止線程,我只是得到一個新的。日誌看起來是這樣的:
lots of playings1 -- 1
lots of playings1 -- 1
0 --- before switch
1 --- after switch
thread started!
lots of playings1 -- 1
after click on stop --- 1
lots of playings1 -- 1
lots of playings1 -- 1
它說,它是打(很多playings1 - 1),但後來它說,它是不是在玩(0 ---開關之前)。這幾乎是肯定的問題所在。我哪裏做錯了?如果它有助於回答這個問題,那麼知道我認爲我在我的項目的早期版本中工作可能會有幫助。 (儘管現在看起來似乎不合情理......)
感謝您的幫助!
這是正確的。我正在初始化兩個audioPlayers。在另一個視圖中,我有一個獲取的結果控制器(與Song實體連接)。此FRC在第一個視圖控制器的viewDidUnload函數中設置爲零。我需要將FRC設置爲零,以便查看將會消失。 – rizzes 2012-08-09 18:02:53