Managing Sound Playback

This article describes how to manage the playback of a sound using the NSSound class.

Starting, Pausing, Resuming, and Canceling Sound Playback

Playing audio data using the NSSound class is very simple; instance methods provide transport control. Listing 1 shows several action methods that control the playback of a sound.

Listing 1  Controlling sound playback

- (IBAction) playSound:(id)sender
{
    if (loaded && ![sound isPlaying]) {
        [sound play];
        [infoTextField setStringValue:@"Playback in progress"];
    }
}
 
- (IBAction) pauseSound:(id)sender
{
    [sound pause];
    [infoTextField setStringValue:@"Playback paused"];
}
 
- (IBAction) resumeSound:(id)sender
{
    [sound resume];
    [infoTextField setStringValue:@"Playback resumed"];
}
 
- (IBAction) stopSound:(id)sender
{
    [sound stop]
    [infoTextField setStringValue:@"Playback canceled"];
}

Finding Out Whether a Sound Is Playing

The isPlaying method tells you whether a sound is playing, as shown in Listing 2.

Listing 2  Determining whether a sound is playing

- (IBAction) isSoundPlaying:(id)sender
{
    if ([sound isPlaying])
        [infoTextField setStringValue:@"The sound is playing"];
    else
        [infoTextField setStringValue:@"The sound is not playing"];
}

Finding Out When a Sound Has Finished Playing

Listing 3 shows an example implementation of the sound:didFinishPlaying: delegate method, which is called when a sound finishes playing.

Listing 3  Performing an action when a sound finishes playing

- (void) sound:(NSSound *)sound didFinishPlaying:(BOOL)playbackSuccessful
{
    if (playbackSuccessful) {
        [infoTextField setStringValue:@"Playback ended successfully"];
    }
    else {
        [infoTextField setStringValue:@"Playback ended abnormally"];
    }
}