首页 > 解决方案 > 如何使用 NSSound 播放/停止播放歌曲?

问题描述

我正在使用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

标签: objective-cnssound

解决方案


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

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


推荐阅读