2012-08-09 57 views
0

我想创建一个具有启动/停止功能的音乐播放器。我通过启动一个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 ---开关之前)。这几乎是肯定的问题所在。我哪里做错了?如果它有助于回答这个问题,那么知道我认为我在我的项目的早期版本中工作可能会有帮助。 (尽管现在看起来似乎不合情理......)

感谢您的帮助!

回答

0

跟踪显示的是旧线程永不停止,但新线程开始。这表明您在新创建的(未运行的)audioPlayer上调用playOrStopSong,而不是您之前实际启动的那个。

我无法从问题中的代码中看到audioPlayer的生命周期(或意图是),但在audioPlayer的初始化程序中放置trace语句很可能表明您当你实际上没有打算创造一个新的。

+0

这是正确的。我正在初始化两个audioPlayers。在另一个视图中,我有一个获取的结果控制器(与Song实体连接)。此FRC在第一个视图控制器的viewDidUnload函数中设置为零。我需要将FRC设置为零,以便查看将会消失。 – rizzes 2012-08-09 18:02:53