0

我正在使用NSSound从我的 FTP 服务器播放歌曲。

我的问题:

第一首歌不会停止,这样第二首歌就会重叠。

在这里我粘贴完整的代码。这是当我单击一首歌曲时的行为NSTableView

-(void)tableViewSelectionDidChange:(NSNotification *)notification{

   NSInteger row = [[notification object] selectedRow];
   NSString *URL = [NSString stringWithFormat:@"ftp://user:pass@IP/Public/Music/%@",[TableContents objectAtIndex:row]];

   NSSound *song = [[NSSound alloc]initWithContentsOfURL:[NSURL URLWithString:URL] byReference:NO];

   NSLog(@"is playing before %hhd", song.isPlaying);

      if(song.isPlaying){
        [song stop];
        NSLog(@"is playing IF if %hhd", song.isPlaying);

      }else{
        [song play];
        NSLog(@"is playing ELSE %hhd", song.isPlaying);
      }

}

输出:

当我点击第一首歌时:

2018-10-06 23:51:08.488690+0200 AIOMediaCenter[4294:492923] is playing before 0
2018-10-06 23:51:08.489099+0200 AIOMediaCenter[4294:492923] is playing ELSE 1

当我点击第二首歌时:

2018-10-06 23:51:12.022284+0200 AIOMediaCenter[4294:492923] is playing before 0
2018-10-06 23:51:12.022375+0200 AIOMediaCenter[4294:492923] is playing ELSE 1
4

1 回答 1

0

每次单击它时,都会创建一个新song对象。song当您创建一个新对象时,您需要在某处存储指向该对象的指针,然后检查 1)该对象是否存在,2)isPlaying是否TRUE为了停止它。这将需要您进行更多计划。这超出了问题的范围。

song(分配后你也永远不会释放它,这会泄漏内存。)

于 2018-10-07T16:11:49.217 回答