NSSound isPlaying returning null on Mac

In my AppDelegate I have this method which will run when the play button is clicked:

- (IBAction)actionPlayTrack:(id)sender {
    NSSound *currentSong = [[NSSound alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"03 Bazel" ofType:@"mp3"] byReference:YES];
    if([currentSong isPlaying] == NO){
        [currentSong play];
    } else {
        [currentSong stop];
        [currentSong release];
    }
}

However the if statement to check if the song is currently playing will not work and will always play regardless if there is already a sound playing. Any idea's on why it would be doing this? Perhaps the currentSong object is being reset every time the button is clicked would be my first guess...

[currentSong isPlaying] 

Will always return null.

Answers


I believe the problem is that you are creating a new NSSound instance every time you call this method. So the old NSSound instance may be playing, but this one is not. This probably results in a memory leak because you allocate a new instance, but never release the old one.

To overcome this issue, you may want to add a NSSound *currentSong to your class, and then you can use that NSSound object when you want to check if its playing. Then when you switch track you may want to stop the existing NSSound object and release it before making a new NSSound instance.

So your code should look something like:

- (IBAction)actionPlayTrack:(id)sender {
    if (!currentSong) {
        currentSong = [[NSSound alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"03 Bazel" ofType:@"mp3"] byReference:YES];
    }

    if ([currentSong isPlaying]){
        [currentSong stop];
        [currentSong release];
        currentSong = nil;
    } else {
        [currentSong play];
    }
}

- (void)dealloc {
    [currentSong release];
    currentSong = nil;
}

Then add NSSound* currentSong to your header.


Need Your Help

How to direct web traffic via php throuh a specific interface?

php curl routing

How would I direct specific traffic to an interface? For example each interface is assigned a different ip-address, I would like to call http traffic via php to eth0 for some traffic and eth1 for o...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.