How can I play/stop a song from playing using NSSound?

92 views Asked by At

I am using NSSound to play a song from my FTP server.

My problem:

The 1st song won't stop, overlapping in this way the 2nd second song.

Here I paste the full code. This is the behavior when I click on a song in a 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);
      }

}

Output:

When I click on the 1st song:

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

When I click on the 2nd song:

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
1

There are 1 answers

0
Cinder Biscuits On

Every time you click it, you're creating a new song object. You need to store a pointer to the song object somewhere when you create a new one, and then check if 1) the object exists, 2) isPlaying is TRUE in order to stop it. That's going to take more planning out on your part. It is outside the scope of the question.

(You're also never releasing song after allocating it, which will leak memory.)