OpenStep Programming Reference
只搜寻这本书
以 PDF 格式下载本书

Sound Classes

15

The Sound, SoundMeter, and SoundView classes comprise OpenStep's sound support. These classes are not part of the OpenStep specification.

Sound

Inherits From:NSObject
Declared In:soundkit/Sound.h

Class Description

Sound objects represent and manage sounds. A Sound object's sound can be recorded from a microphone, read from a soundfile or NSBundle resource, retrieved from the pasteboard, or created algorithmically. The Sound class also provides an application-wide name table that lets you identify and locate sounds by name.
Playback and recording are performed by background threads, allowing your application to proceed in parallel. You should only use a Sound object to play and record sounds in applications that have a running NSApp object present.
You can also edit a Sound object by adding and removing samples. To minimize data movement (and thus save time), an edited Sound may become fragmented; in other words, its sound data might become discontiguous in memory. While playback of a fragmented Sound object is transparent, it does incur some overhead. If you perform a number of edits you may want to return the Sound
to a contiguous state by sending it a compactSamples message before you play it. However, a large Sound may take a long time to compact, so a judicious and well-timed use of compactSamples is advised. Fragmented Sounds are automatically compacted before they're copied to a pasteboard (through the writeToPasteboard: method). Also, when you write a Sound to a soundfile, the data in the file will be compact regardless of the state of the object.
A Sound object contains a structure, named SNDSoundStruct, that contains and describes sound data. Here is what it looks like:
typedef struct {
    int magic;          /* Must be equal to SND_MAGIC */
    int dataLocation;   /* Offset or pointer to the raw data */
    int dataSize;       /* Number of raw data bytes */
    int dataFormat;     /* Data format code */
    int samplingRate;   /* Sampling rate */
    int channelCount;   /* Number of channels */
    char info[4];       /* Textual sound information */
} SNDSoundStruct;

This sound data format is also used as the Sound object's file format and pasteboard type.
  • SNDSoundStruct consists of a header and two variable length quantities: textual information (info) and raw data (dataLocation). Here's a description of the contents:
  • magic specifies the magic number used to determine the byte order of the data.
  • dataLocation specifies an offset from the beginning of the SNDSoundStruct to info's end. This raw data always starts where textual info (described below) ends.
  • dataSize is the length of the raw data in bytes.
  • dataFormat specifies what the data actually means (for example, sample data, dsp core structure), and is one of the following constants:
· SND_FORMAT_UNSPECIFIED
· SND_FORMAT_MULAW_8
· SND_FORMAT_LINEAR_8
· SND_FORMAT_LINEAR_16
· SND_FORMAT_LINEAR_24
· SND_FORMAT_LINEAR_32
· SND_FORMAT_FLOAT

· SND_FORMAT_DOUBLE
· SND_FORMAT_INDIRECT
· SND_FORMAT_NESTED
· SND_FORMAT_DSP_CORE
· SND_FORMAT_DSP_DATA_8
· SND_FORMAT_DSP_DATA_16
· SND_FORMAT_DSP_DATA_24
· SND_FORMAT_DSP_DATA_32
· SND_FORMAT_DISPLAY
· SND_FORMAT_MULAW_SQUELCH
· SND_FORMAT_EMPHASIZED
· SND_FORMAT_COMPRESSED
· SND_FORMAT_COMPRESSED_EMPHASIZED
· SND_FORMAT_DSP_COMMANDS
· SND_FORMAT_DSP_COMMANDS_SAMPLES
· SND_FORMAT_ADPCM_G721
· SND_FORMAT_ADPCM_G722
· SND_FORMAT_ADPCM_G723_3
· SND_FORMAT_ADPCM_G723_5
· SND_FORMAT_ALAW_8
· SND_FORMAT_AES
· SND_FORMAT_DELTA_MULAW_8

  • samplingRate, and channelCount further describe the data.
  • info is any null-terminated data that the application may need (for example, copyright information, textual description). The four bytes allocated are a minimum, and may be extended to whatever length is required.
Most of the methods defined in the Sound class are implemented so that you needn't be aware of this structure.

Error Codes

The following list contains the error codes returned by Sound object methods.
  • SND_ERR_NONE
  • SND_ERR_NOT_SOUND
  • SND_ERR_BAD_FORMAT
  • SND_ERR_BAD_RATE
  • SND_ERR_BAD_CHANNEL
  • SND_ERR_BAD_SIZE
  • SND_ERR_BAD_FILENAME
  • SND_ERR_CANNOT_OPEN
  • SND_ERR_CANNOT_WRITE
  • SND_ERR_CANNOT_READ
  • SND_ERR_CANNOT_ALLOC
  • SND_ERR_CANNOT_FREE
  • SND_ERR_CANNOT_COPY
  • SND_ERR_CANNOT_RESERVE
  • SND_ERR_NOT_RESERVED
  • SND_ERR_CANNOT_RECORD
  • SND_ERR_ALREADY_RECORDING
  • SND_ERR_NOT_RECORDING
  • SND_ERR_CANNOT_PLAY
  • SND_ERR_ALREADY_PLAYING
  • SND_ERR_NOT_PLAYING
  • SND_ERR_NOT_IMPLEMENTED
  • SND_ERR_CANNOT_FIND
  • SND_ERR_CANNOT_EDIT
  • SND_ERR_BAD_SPACE
  • SND_ERR_KERNEL
  • SND_ERR_BAD_CONFIGURATION
  • SND_ERR_CANNOT_CONFIGURE
  • SND_ERR_UNDERRUN
  • SND_ERR_ABORTED
  • SND_ERR_BAD_TAG
  • SND_ERR_CANNOT_ACCESS
  • SND_ERR_TIMEOUT
  • SND_ERR_BUSY
  • SND_ERR_CANNOT_ABORT
  • SND_ERR_INFO_TOO_BIG
  • SND_ERR_UNKNOWN
See also the SoundMeter and SoundView classes.
ActivityClass Method
Creating and freeing a Sound
object
+ addName:fromBundle:
+ addName:fromSoundfile:
- dealloc
- initFromPasteboard:
- initFromSoundfile:
ActivityClass Method
Accessing the Sound name
table
+ addName:sound:
+ findSoundFor:
+ removeSoundForName:
Reading and writing sound
data
- dataForSound
- readSoundfile:
- writeSoundfile:
- writeToPasteboard:
Modifying sound data- convertToFormat:samplingRate:channelCount: - convertToFormat:

- setDataSize:dataFormat:samplingRate: channelCount:infoSize:

- setSoundStruct:soundStructSize: - setName:

- name

Querying the object- soundStruct
- soundStructSize
- data
- dataFormat
- dataSize
- channelCount
- samplingRate
- sampleCount
- duration
- info
- infoSize
- isEmpty
- compatibleWith:
- processingError
ActivityClass Method
Recording and playing- pause
- pause:
- isPlayable
- play
- play:
- record
- record:
- resume
- resume:
- stop
- stop:
- samplesProcessed
- status
- soundBeingProcessed
- soundStructBeingProcessed
- waitUntilStopped
Editing sound data- isEditable
- copySamples:at:count:
- copySound:
- deleteSamples
- deleteSamplesAt:count:
- insertSamples:at:
- needsCompacting
- compactSamples
Accessing the delegate- setDelegate:
- delegate
- tellDelegate:
Accessing the sound hardware+ getVolume::
+ setVolume::
+ isMuted
+ setMute:
Methods implemented by the
delegate
- didPlay:
- didRecord:
- hadError:
- willPlay:
- willRecord:

Class Methods

addName:fromBundle:

+ addName:(NSString *)name fromBundle:(NSBundle *)aBundle

Creates a Sound object from the sound resource named name in the NSBundle aBundle, assigns the name name to the object, and places the name on the sound name table. If name is already in use, or if the resource isn't found or can't be read, the Sound isn't created and nil is returned. Otherwise, the new Sound is returned.

addName:fromSoundfile:

+ addName:(NSString *)name fromSoundfile:(NSString *)filename

Creates a Sound object from the soundfile filename, assigns the name name to the object, and adds it to the named Sound table. If name is already in use, or if filename isn't found or can't be read, the Sound isn't created and nil is returned. Otherwise, the new Sound is returned.

addName:sound:

+ addName:(NSString *)name sound:(Sound *)aSound

Assigns the name name to the Sound aSound and adds it to the named Sound table. Returns aSound, or nil if name is already in use.

findSoundFor:

+ findSoundFor:(NSString *)aName

Finds and returns the named Sound object. First the named Sound table is searched; if the sound isn't found, then the method looks for "aName.snd" in the sound segment of the application's executable file. Finally, the file is searched for in the following directories (in order):
  • ~/openstep/Library/Sounds
  • /usr/local/openstep/Library/Sounds
  • /usr/openstep/Library/Sounds
where ~ represents the user's home directory. If the Sound eludes the search, nil is returned.

getVolume::

+ getVolume:(float *)left :(float *)right

Returns, by reference, the stereo output levels as floating-point numbers between 0.0 and 1.0.

isMuted

+ (BOOL)isMuted

Returns YES if the sound output level is currently muted.

removeSoundForName:

+ removeSoundForName:(NSString *)name

Removes the named Sound from the named Sound table. If the Sound isn't found, returns nil; otherwise returns the Sound.

setMute:

+ setMute:(BOOL)aFlag

Mutes and unmutes the sound output level as aFlag is YES or NO, respectively. If successful, returns self; otherwise returns nil.

setVolume::

+ setVolume:(float)left :(float)right

Sets the stereo output levels. These affect the volume of the stereo signals sent to the built-in speaker and headphone jacks. left and right must be floating-point numbers between 0.0 (minimum) and 1.0 (maximum). If successful, returns self; otherwise returns nil.

Instance Methods

channelCount

- (int)channelCount

Returns the number of channels in the Sound.

compactSamples

- (int)compactSamples

The Sound's sampled data is compacted into a contiguous block, undoing the fragmentation that can occur during editing. If the Sound's data isn't fragmented (its format isn't SND_FORMAT_INDIRECT), then this method does nothing. Compacting a large sound can take a long time; keep in mind that when you copy a Sound to a pasteboard, the object is automatically compacted before it's copied. Also, the soundfile representation of a Sound contains contiguous data so there's no need to compact a Sound before writing it to a soundfile simply to ensure that the file representation will be compact. See the class description for a list of error codes returned by this method.

compatibleWith:

- (BOOL)compatibleWith:aSound

Returns YES if the format, sampling rate, and channel count of aSound's sound data is the same as that of the Sound receiving this message. If one (or both) of the Sounds doesn't contain a sound (soundStruct returns nil) then the objects are declared compatible and YES is returned.

convertToFormat:

- (int)convertToFormat:(int)newFormat

This is the same as convertToFormat:samplingRate:channelCount:, except that only the format is changed. See the class description for a list of error codes returned by this method.

convertToFormat:samplingRate:channelCount:

- (int)convertToFormat:(int)newFormat
    samplingRate:(double)newRate
    channelCount:(int)newChannelCount

Convert the Sound's data to the given format, sampling rate, and number of channels. The following conversions are possible:
  • Arbitrary sampling rate conversion.
  • Compression and decompression.
  • Floating-point formats (including double-precision) to and from linear formats.
  • Mono to stereo.
  • Mu-law to and from linear formats.
See the class description for a list of error codes returned by this method.

copySamples:at:count:

- (int)copySamples:aSound at:(int)startSample
    count:(int)sampleCount

Replaces the Sound's sampled data with a copy of a portion of aSound's data. The copied portion starts at aSound's startSample'th sample (zero-based) and extends over sampleCount samples. The Sound receiving this message must be editable and the two Sounds must be compatible. If the specified portion of aSound is fragmented, the Sound receiving this message will also be fragmented. See the class description for a list of error codes returned by this method.

copySound:

- (int)copySound:aSound

Replaces the Sound's data with a copy of aSound's data. The Sound receiving this message needn't be editable, nor must the two Sounds be compatible. See the class description for a list of error codes returned by this method.

data

- (unsigned char *)data

Returns a pointer to the Sound's sampled data. You can use the pointer to examine, create, and modify the sound data. To intelligently manipulate the data, you need to be aware of its size, format, sampling rate, and the number of channels that it contains (a query method for each of these attributes is provided by the Sound class). The size of the data, in particular, must be respected; it's set when the Sound is created or given a new sound (through readSoundfile:, for example) and can't be changed directly. To resize the data, you should invoke one of the editing methods such as insertSamples:at: or deleteSamplesAt:count:. To start with a new, unfragmented sound with a determinate length, invoke the setDataSize:dataFormat:samplingRate:channelCount:infoSize: method. Keep in mind that the sound data in a fragmented sound is a pointer to a NULL-terminated list of pointers to SNDSoundStructs, one for each fragment. To examine or manipulate the samples in a fragmented sound, you must understand the SNDSoundStruct structure.

dataFormat

- (int)dataFormat

Returns the format of the Sound's data. If the data is fragmented, the format of the samples is returned (in other words, SND_FORMAT_INDIRECT is never returned by this method).

dataForSound

- (NSData *) dataForSound

Returns the Sound object's data enclosed in an NSData object.

dataSize

- (int)dataSize

Return the size (in bytes) of the Sound's data. If you modify the data (through the pointer returned by the data method) you must be careful not to exceed its length. If the sound is fragmented, the value returned by this method is the size of the Sound's SNDSoundStruct and doesn't include the actual data itself.

dealloc

- dealloc

Frees the Sound and deallocates its sound data. The Sound is removed from the named Sound table and its name made eligible for reuse.

delegate

- delegate

Returns the Sound's delegate.

deleteSamples

- (int)deleteSamples

Deletes all the samples in the Sound's data. The Sound must be editable. An error code is returned.

deleteSamplesAt:count:

- (int)deleteSamplesAt:(int)startSample count:(int)sampleCount

Deletes a range of samples from the Sound. sampleCount samples are deleted starting with the startSample'th sample (zero-based). The Sound must be editable and may become fragmented. See the class description for a list of error codes returned by this method.

duration

- (double)duration

Returns the Sound's length in seconds.

info

- (char *)info

Returns textual information about the sound. See the class description for more information.

infoSize

- (int)infoSize

Returns the size (in bytes) of the Sound's info string.

initFromPasteboard:

- initFromPasteboard:(NSPasteboard *)thePboard

Initializes the Sound instance, which must be newly allocated, by copying the sound data from the Pasteboard object thePboard. A pasteboard can have only one sound entry at a time. Returns self (an unnamed Sound) if thePboard currently contains a sound entry; otherwise, frees the newly allocated Sound and returns nil.

initFromSoundfile:

- initFromSoundfile:(NSString *)filename

Initializes the Sound instance, which must be newly allocated, from the soundfile filename. Returns self (an unnamed Sound) if the file was successfully read; otherwise, frees the newly allocated Sound and returns nil.

insertSamples:at:

- (int)insertSamples:aSound at:(int)startSample

Pastes the sound data in aSound into the Sound receiving this message, starting at the receiving Sound's startSample'th sample (zero-based). The receiving Sound doesn't lose any of its original sound data--the samples greater than or equal to startSample are moved to accommodate the inserted sound data. The receiving Sound must be editable and the two Sounds must be compatible (as determined by isCompatible:). If the method is successful, the receiving Sound is fragmented. See the class description for a list of error codes returned by this method.

isEditable

- (BOOL)isEditable

Returns YES if the Sound's format indicates that it can be edited, otherwise returns NO.

isEmpty

- (BOOL)isEmpty

Returns YES if the Sound doesn't contain any sound data, otherwise returns NO. This always returns NO if the Sound isn't editable, as determined by sending it the isEditable message.

isPlayable

- (BOOL)isPlayable

Returns YES if the Sound can be played, otherwise returns NO. Some unplayable Sounds just need to be converted to another format, sampling rate, or number of channels; others are inherently unplayable, such as those whose format is SND_FORMAT_DISPLAY.

name

- (NSString *)name

Returns the Sound's name.

needsCompacting

- (BOOL)needsCompacting

Returns YES if the Sound's data is fragmented. Otherwise returns NO.

pause

- (int)pause

Pauses the Sound during recording or playback. See the class description for a list of error codes returned by this method.

pause:

- pause:sender

Action method that pauses the Sound. Other than the argument and the return type, this is the same as the pause method.

play

- (int)play

Initiates playback of the Sound. The method returns immediately while the playback continues asynchronously in the background. The playback ends when the Sound receives the stop message, or when its data is exhausted.
When playback starts, willPlay: is sent to the Sound's delegate; when it stops, didPlay: is sent. See the class description for a list of error codes returned by this method. For this method to work properly, the main event loop must not be blocked.

play:

- play:sender

Action method that plays the Sound. Other than the argument and the return type, this is the same as the play method.

processingError

- (int)processingError

Returns a constant that represents the last error that was generated. See the class description for a list of error codes returned by this method

readSoundfile:

- (int)readSoundfile:(NSString *)filename

Replaces the Sound's contents with those of the soundfile filename. The Sound loses its current name, if any. See the class description for a list of error codes returned by this method.

record

- (int)record

Initiate recording into the Sound. The method returns immediately while the recording continues asynchronously in the background. The recording stops when the Sound receives the stop message or when the recording has gone on for the duration of the original sound data. The default recording lasts precisely ten minutes if not stopped. To record for a longer time, first increase the size of the sound data with setSoundStruct:soundStructSize: or setDataSize:dataFormat:samplingRate:channelCount:infoSize:.
When the recording begins, willRecord: is sent to the Sound's delegate; when the recording stops, didRecord: is sent. For this method to work properly, the main event loop must not be blocked. See the class description for a list of error codes returned by this method.

record:

- record:sender

Action method that initiates a recording. Other than the argument and return type, this is the same as the record method.

resume

- (int)resume

Resumes the paused Sound's activity. See the class description for a list of error codes returned by this method.

resume:

- resume:sender

Action method that resumes the paused Sound.

sampleCount

- (int)sampleCount

Returns the number of sample frames, or channel count-independent samples, in the Sound.

samplesProcessed

- (int)samplesProcessed

If the Sound is currently playing or recording, this returns the number of sample frames that have been played or recorded so far. Otherwise, the number of sample frames in the Sound is returned. If the sample frame count can't be determined, -1 is returned.

samplingRate

- (double)samplingRate

Returns the Sound's sampling rate.

setDataSize:dataFormat:samplingRate: channelCount:infoSize:

- (int)setDataSize:(int)newDataSize
    dataFormat:(int)newDataFormat
    samplingRate:(double)newSamplingRate
    channelCount:(int)newChannelCount
    infoSize:(int)newInfoSize

Allocates new, unfragmented sound data for the Sound, as described by the arguments. The Sound's previous data is freed. This method is useful for setting a determinate data length prior to a recording or for creating a scratch pad for algorithmic sound creation. See the class description for a list of error codes returned by this method.

setDelegate:

- setDelegate:anObject

Sets the Sound's delegate to anObject. The delegate may implement the following methods:
  • willPlay:
  • didPlay:
  • willRecord:
  • didRecord:
  • hadError:

setName:

- setName:(NSString *)aName

Sets the Sound's name to aName. If aName is already being used, then the Sound's name isn't set and nil is returned; otherwise returns self.

setSoundStruct:soundStructSize:

- setSoundStruct:(SNDSoundStruct *)aStruct
    soundStructSize:(int)size

Sets the Sound's sound structure to aStruct. The size in bytes of the new structure, including its sound data storage, must be specified by size. This method can be used to set up a large buffer before recording into an existing Sound, by passing the existing SNDSoundStruct in the first argument while making size larger than the current size. (The default buffer holds ten minutes of mulaw sound.) The method is also useful in cases where aStruct already has sound data but isn't encapsulated in a Sound object yet. The Sound's status must be NX_SoundInitialized or NX_SoundStopped for this method to do anything. See the status method's description for a sound status list.

soundBeingProcessed

- soundBeingProcessed

Returns the Sound object that's being performed. The default implementation always returns self.

soundStruct

- (SNDSoundStruct *)soundStruct

Returns a pointer to the Sound's SNDSoundStruct structure that holds the object's sound data.

soundStructBeingProcessed

- (SNDSoundStruct *)soundStructBeingProcessed

Returns a pointer to the SNDSoundStruct structure that's being performed. This may not be the same structure as returned by the soundStruct method--Sound object's contain a private sound structure that may be used for playing recordings. If the Sound isn't currently playing or recording, then this will return the public structure.

soundStructSize

- (int)soundStructSize

Returns the size, in bytes, of the Sound's sound structure (returned by the soundStruct method). Use of this value requires a knowledge of the SNDSoundStruct architecture.

status

- (int)status

Return the Sound's current status, one of the following integer constants:
  • NX_SoundStopped
  • NX_SoundRecording
  • NX_SoundPlaying
  • NX_SoundInitialized
  • NX_SoundRecordingPaused
  • NX_SoundPlayingPaused
  • NX_SoundRecordingPending
  • NX_SoundPlayingPending
  • NX_SoundFreed

stop

- (int)stop

Terminates the Sound's playback or recording. If the Sound was recording, the didRecord: message is sent to the delegate; if playing, didPlay: is sent. See the class description for a list of error codes returned by this method.

stop:

- stop:sender

Action method that stops the Sound's playback or recording. Other than the argument and the return type, this is the same as the stop method.

tellDelegate:

- tellDelegate:(SEL)theMessage

Sends theMessage to the Sound's delegate (only sent if the delegate implements theMessage). You never invoke this method directly; it's invoked automatically as the result of activities such as recording and playing. However, you can use it in designing a subclass of Sound.

waitUntilStopped

- (int)waitUntilStopped

Causes the system to wait until the Sound playback has stopped. Returns SND_ERR_NONE if no error occurred.

writeSoundfile:

- (int)writeSoundfile:(NSString *)filename

Writes the Sound's contents (its SNDSoundStruct and sound data) to the soundfile filename. See the class description for a list of error codes returned by this method.

writeToPasteboard:

- (int)writeToPasteboard:(Pasteboard *)thePboard

Puts a copy of the Sound's contents (its SNDSoundStruct and sound data) on the pasteboard maintained by the Pasteboard object thePboard. If the Sound is fragmented, it's compacted before the copy is created. See the class description for a list of error codes returned by this method.

Methods Implemented by the Delegate

didPlay:

- didPlay:sender

Sent to the delegate when the Sound stops playing.

didRecord:

- didRecord:sender

Sent to the delegate when the Sound stops recording.

hadError:

- hadError:sender

Sent to the delegate if an error occurs during recording or playback.

willPlay:

- willPlay:sender

Sent to the delegate when the Sound begins to play.

willRecord:

- willRecord:sender

Sent to the delegate when the Sound begins to record.

SoundMeter

Inherits From:NSView: NSResponder: NSObject
Declared In:soundkit/SoundMeter.h

Class Description

A SoundMeter is a view that displays the amplitude level of a sound as it's being recorded or played back. There are two working parts to the meter: A continuously-updated "running bar" that lengthens ands shrinks to depict the current amplitude level, and a "peak bubble" that displays and holds the greatest amplitude that was detected within the last few samples. An optional bezeled border is drawn around the object's frame.
To use a SoundMeter, you must first associate it with a Sound object, through the setSound: method, and then send the SoundMeter a run: message. To stop the meter's display, you send the object a stop: message. Neither run: nor stop: affect the performance of the meter's sound.
You can retrieve a SoundMeter's running and peak values through the floatValue and peakValue methods. The values that these methods return are valid only while the SoundMeter is running. A SoundMeter also keeps track of the minimum and maximum amplitude over the duration of a run; these can be retrieved through minValue and maxValue. All SoundMeter amplitude levels are normalized to fit between 0.0 (inaudible) and 1.0 (maximum amplitude).

Method Types

ActivityClass Method
Initializing a SoundMeter instance- initWithFrame:
Graphic attributes- setBezeled:
- isBezeled
- setBackgroundGray:
- backgroundGray
- setForegroundGray:
- foregroundGray
- setPeakGray:
- peakGray
Metering attributes- setSound:
- sound
- setFloatValue:
- setHoldTime:
- holdTime
Retrieving meter values- floatValue
- maxValue
- minValue
- peakValue
Operating the object- run:
- isRunning
- stop:
Drawing the object- drawCurrentValue
- drawRect:

Instance Methods

backgroundGray

- (float)backgroundGray

Returns the SoundMeter's background color. The default is dark gray (NSDarkGray).

drawCurrentValue

- drawCurrentValue

Draws the SoundMeter's running bar and peak bubble. You never invoke this method directly; it's invoked automatically while the SoundMeter is running. You can override this method to change the look of the running bar and peak bubble.

drawRect:

- drawRect:(NSRect)rect

Draws all the components of the SoundMeter (frame, running bar, and peak bubble). You never invoke this method directly; however, you can override it in a subclass to change the way the components are displayed.

encodeWithCoder:

- (void)encodeWithCoder:(NSCoder *) aCoder

Encodes the receiving SoundMeter using aCoder. See the Application Kit's NSCoding protocol and NSCoder class documention for more information. See also initWithCoder:.

floatValue

- (float)floatValue

Returns the current running amplitude value as a floating-point number between 0.0 and 1.0. This is the amplitude level that's displayed by the running bar.

foregroundGray

- (float)foregroundGray

Returns the color of the running bar. The default is light gray (NSLightGray).

holdTime

- (float)holdTime

Returns the SoundMeter's hold time--the amount of time during which a peak amplitude is detected and displayed by the peak bubble--in seconds. The default is 0.7 seconds.

initWithCoder:

- initWithCoder: (NSCoder *) aCoder

Initializes and returns a new SoundMeter instance from data in aCoder. See the Application Kit's NSCoding protocol and NSCoder class documention for more information. See also encodeWithCoder:.

initWithFrame:

- initWithFrame:(const NSRect *)frameRect

Initializes the SoundMeter, fitting its graphic components within frameRect. The object's attributes are initialized as follows:
AttributeValue
Peak hold time0.7 seconds
Background grayNSDarkGray
Running bar grayNSLightGray
Peak bubble grayNSWhite
Borderbezeled

isBezeled

- (BOOL)isBezeled

Returns YES (the default) if the SoundMeter has a border; otherwise, returns NO. Note that the SoundMeter class doesn't provide a method to change the type of border--it can display a bezeled border or none at all.

isRunning

- (BOOL)isRunning

Returns YES if the SoundMeter is currently running; otherwise, returns NO. The SoundMeter's status doesn't depend on the activity of its Sound object.

maxValue

- (float)maxValue

Returns the maximum running value so far. You can invoke this method after you stop this SoundMeter to retrieve the overall maximum value for the previous performance. The maximum value is cleared when you restart the SoundMeter.

minValue

- (float)minValue

Returns the minimum running value so far. You can invoke this method after you stop this SoundMeter to retrieve the overall minimum value for the previous performance. The minimum value is cleared when you restart the SoundMeter.

peakGray

- (float)peakGray

Returns the SoundMeter's peak bubble gray. The default is white (NSWhite).

peakValue

- (float)peakValue

Returns the most recently detected peak value as a floating-point number between 0.0 and 1.0. This is the amplitude level that's displayed by the peak bubble.

run:

- run:sender

Starts the SoundMeter running. The object SoundMeter must have a Sound object associated with it for this method to have an effect. Note that this method only affects the state of the SoundMeter--it doesn't trigger any activity in the Sound.

setBackgroundGray:

- setBackgroundGray:(float)aValue

Sets the SoundMeter's background color. The default is dark gray (NSDarkGray).

setBezeled:

- setBezeled:(BOOL)aFlag

If aFlag is YES, a bezeled border is drawn around the SoundMeter. If aFlag is NO and the SoundMeter has a frame, the frame is removed.

setFloatValue:

- setFloatValue:(float)aValue

Sets the current running value to aValue. You never invoke this method directly; it's invoked automatically when the SoundMeter is running. However, you can reimplement this method in a subclass of SoundMeter.

setForegroundGray:

- setForegroundGray:(float)aValue

Sets the SoundMeter's running bar color. The default is light gray (NSLightGray).

setHoldTime:

- setHoldTime:(float)seconds

Sets the SoundMeter's peak value hold time in seconds. This is the amount of time during which peak amplitudes are detected and held by the peak bubble.

setPeakGray:

- setPeakGray:(float)aValue

Sets the SoundMeter's peak bubble color. The default is white (NSWhite).

setSound:

- setSound:aSound

Sets the SoundMeter's Sound object.

sound

- sound

Returns the Sound object that the SoundMeter is metering.

stop:

- stop:sender

Stops the SoundMeter's metering activity. Note that this method only affects the state of the SoundMeter--it doesn't trigger any activity in the Sound.

SoundView

Inherits From:NSView: NSResponder: NSObject
Declared In:soundkit/SoundView.h

Class Description

A SoundView object provides a graphical representation of sound data. This data is taken from an associated Sound object. In addition to displaying a Sound object's data, a SoundView provides methods that let you play and record into the Sound object, and peform simple cut, copy, and paste editing of its data. A cursor into the display is provided, allowing the user to set the insertion point and to create a selection over the sound data.

Sound Display

Sounds are displayed on a two-dimensional graph. The amplitudes of individual samples are measured vertically and plotted against time, which proceeds left to right along the horizontal axis. A SoundView's coordinate system is scaled and translated (vertically) so full amplitude fits within the bounds rectangle with 0.0 amplitude running through the center of the view.
For many sounds, the length of the sound data in samples is greater than the horizontal measure of the bounds rectangle. A SoundView employs a reduction factor to determine the ratio of samples to display units and plots the minimum and maximum amplitude values of the samples within that ratio. For example, a reduction factor of 10.0 means that the minimum and maximum values among the first ten samples are plotted in the first display unit, the minimum and maximum values of the next ten samples are displayed in the second display unit and so on.
Lines are drawn between the chosen values to yield a continuous shape. Two drawing modes are provided:
  • In NX_SOUNDVIEW_WAVE mode, the drawing is rendered in an oscilloscopic fashion.
  • In NX_SOUNDVIEW_MINMAX mode, two lines are drawn, one to connect the maximum values, and one to connect the minimum values.
As you zoom in (as the reduction factor decreases), the two drawing modes become indistinguishable.

Autoscaling the Display

When a SoundView's sound data changes (due to editing or recording), the manner in which the SoundView is redisplayed depends on its autoscale flag. With autoscaling disabled, the SoundView's frame grows or shrinks (horizontally) to fit the new sound data and the reduction factor is unchanged. If autoscaling is enabled, the reduction factor is automatically recomputed to maintain a constant frame size. By default, autoscaling is disabled; this is to accommodate the use of a SoundView object as the document of an NSScrollView.

Method Types

ActivityClass Method
Initializing a SoundView object- initWithFrame:
Freeing a SoundView instance- dealloc
Modifying the object- scaleToFit
- setBackgroundGray:
- setBezeled:
- setContinuous:
- setDelegate:
- setDisplayMode:
- setEnabled:
- setForegroundGray:
- setOptimizedForSpeed:
- setSound:
- sizeToFit
Querying the object- backgroundGray
- delegate
- displayMode
- foregroundGray
- getSelection:size:
- isAutoScale
- isBezeled
- isContinuous
- isEnabled
- isOptimizedForSpeed
- reductionFactor
- sound
Selecting and editing the sound
data
- copy:
- cut:
- delete:
- mouseDown:
- paste:
- selectAll:
- setSelection:size:
- isEditable
- setEditable:
ActivityClass Method
Pasteboard and Services support- pasteboard:provideDataForType: - readSelectionFromPasteboard: - validRequestorForSendType:andReturnType: - writeSelectionToPasteboard:types:
Modifying the display coordinates- setAutoscale:
- setReductionFactor:
Drawing the object- drawRect:
- drawSamplesFrom:to:
- hideCursor
- showCursor
Responding to events- acceptsFirstResponder
- becomeFirstResponder
- resignFirstResponder
Performing the sound data- pause:
- isPlayable
- play:
- record:
- resume:
- soundBeingProcessed
- stop:
Communicating with the delegate- tellDelegate:
Methods Implemented by the
delegate
- didPlay:
- didRecord:
- hadError:
- selectionDidChange:
- soundDidChange:
- willPlay:
- willRecord:

Instance Methods

acceptsFirstResponder

- (BOOL)acceptsFirstResponder

If the SoundView is enabled, this returns YES, allowing the SoundView to become the first responder. Otherwise, it returns NO. This method is automatically invoked by objects defined by the Application Kit. You should never need to invoke it directly.

backgroundGray

- (float)backgroundGray

Returns the SoundView's background gray value (NSWhite by default).

becomeFirstResponder

- becomeFirstResponder

Promotes the SoundView to first responder. You never invoke this method directly.

copy:

- copy:sender

Copies the current selection to the pasteboard.

cut:

- cut:sender

Deletes the current selection from the SoundView, copies it to the pasteboard, and sends a soundDidChange: message to the delegate. The insertion point is positioned to where the selection used to start.

dealloc

- dealloc

Frees the SoundView but not its Sound object nor its delegate. The willFree: message is sent to the delegate.

delegate

- delegate

Returns the SoundView's delegate object.

delete:

- delete:sender

Deletes the current selection from the SoundView's Sound and sends the soundDidChange: message to the delegate. The deletion isn't placed on the pasteboard.

didPlay:

- didPlay:sender

Used to redirect delegate messages from the SoundView's Sound object; you never invoke this method directly.

didRecord:

- didRecord:sender

Used to redirect delegate messages from the SoundView's Sound object; you never invoke this method directly.

displayMode

- (int)displayMode

Returns the SoundView's display mode, one of NX_SOUNDVIEW_WAVE (oscilloscopic display) or NX_SOUNDVIEW_MINMAX (minimum/maximum display; this is the default).

drawSamplesFrom:to:

- drawSamplesFrom:(int)first to:(int)last

Redisplays the given range of samples.

drawRect:

- drawRect(NSRect)rect

Displays the SoundView's sound data. The selection is highlighted and the cursor is drawn (if it isn't currently hidden). Do not send this message directly to a SoundView object. To cause a SoundView to draw itself, send it one of the display messages defined by the NSView class.

foregroundGray

- (float)foregroundGray

Returns the SoundView's foreground gray value (NSBlack by default).

getSelection:size:

- getSelection:(int *)firstSample size:(int *)sampleCount

Returns the selection by reference. The index of the selection's first sample (counting from 0) is returned in firstSample. The size of the selection in samples is returned in sampleCount. The method itself returns self.

hadError:

- hadError:sender

Used to redirect delegate messages from the SoundView's Sound object; you never invoke this method directly.

hideCursor

- hideCursor

Hides the SoundView's cursor. This is usually handled automatically.

initWithFrame:

- initWithFrame:(NSRect)frameRect

Initializes the SoundView, fitting the object within the rectangle pointing to by frameRect. The initialized SoundView doesn't contain any sound data.

isAutoScale

- (BOOL)isAutoScale

Returns YES if the SoundView is in autoscaling mode, otherwise returns NO.

isBezeled

- (BOOL)isBezeled

Returns YES if the SoundView has a bezeled border, otherwise returns NO (the default).

isContinuous

- (BOOL)isContinuous

Returns YES if the SoundView responds to mouse-dragged events (as set through setContinuous:). The default is NO.

isEditable

- (BOOL)isEditable

Returns YES if the SoundView's sound data can be edited.

isEnabled

- (BOOL)isEnabled

Returns YES if the SoundView is enabled, otherwise returns NO. The mouse has no effect in a disabled SoundView. By default, a SoundView is enabled.

isOptimizedForSpeed

- (BOOL)isOptimizedForSpeed

Returns YES if the SoundView is optimized for speedy display. SoundViews are optimized by default.

isPlayable

- (BOOL)isPlayable

Returns YES if the SoundView's sound data can be played without first being converted.

mouseDown:

- mouseDown:(NSEvent *)theEvent

Allows a selection to be defined by clicking and dragging the mouse. This method takes control until a mouse-up occurs. While dragging, the selected region is highlighted. On mouse up, the delegate is sent the selectionDidChange: message. If isContinuous is YES, selectionDidChange: messages are also sent while the mouse is being dragged. You never invoke this method; it's invoked automatically in response to the user's actions.

paste:

- paste:sender

Replaces the current selection with a copy of the sound data currently on the pasteboard. If there is no selection the pasteboard data is inserted at the cursor position. The pasteboard data must be compatible with the SoundView's data, as determined by the Sound method compatibleWith:. If the paste is successful, the soundDidChange: message is sent to the delegate.

pasteboard:provideDataForType:

- pasteboard:(NSPasteboard *) pboard
    provideDataForType:(NSString *)pboardType

Places the SoundView's entire sound on the given pasteboard. Currently, the pboardType argument must be "NSSoundPboardType", the pasteboard type that represents sound data.

pause:

- pause:sender

Pauses the current playback or recording session by invoking Sound's pause: method. If no sound is being processed, returns nil; otherwise, returns self.

play:

- play:sender

Play the current selection by invoking Sound's play: method. If there is no selection, the SoundView's entire Sound is played. The willPlay: message is sent to the delegate before the selection is played; didPlay: is sent when the selection is done playing.

readSelectionFromPasteboard:

- readSelectionFromPasteboard:(NSPasteboard *)pboard

Replaces the SoundView's current selection with the sound data on the given pasteboard. The pasteboard data is converted to the format of the data in the SoundView (if possible). If the SoundView has no selection, the pasteboard data is inserted at the cursor position. Sets the current error code for the SoundView's Sound object (which you can retrieve by sending processingError to the Sound) and returns self.

record:

- record:sender

Replaces the SoundView's current selection with newly recorded material. If there is no selection, the recording is inserted at the cursor. The willRecord: message is sent to the delegate before the recording is started; didRecord: is sent after the recording has completed. Recorded data is always taken from the CODEC microphone input.

reductionFactor

- (float)reductionFactor

Returns the SoundView's reduction factor, computed as
reductionFactor = sampleCount / displayUnits

resignFirstResponder

- resignFirstResponder

Resigns the position of first responder.

resume:

- resume:sender

Resumes the current playback or recording session by invoking Sound's resume: method. If no sound is being processed, returns nil; otherwise, returns self.

scaleToFit

- scaleToFit

Recomputes the SoundView's reduction factor to fit the sound data (horizontally) within the current frame. Invoked automatically when the SoundView's data changes and the SoundView is in autoscale mode. If the SoundView isn't in autoscale mode, sizeToFit is invoked when the data changes. You never invoke this method directly; a subclass can reimplement this method to provide specialized behavior.

selectAll:

- selectAll:sender

Creates a selection over the SoundView's entire Sound.

setAutoscale:

- setAutoscale:(BOOL)aFlag

Sets the SoundView's automatic scaling mode, used to determine how the SoundView is redisplayed when its data changes. With autoscaling enabled (aFlag is YES), the SoundView's reduction factor is recomputed so the sound data fits within the view frame. If it's disabled (aFlag is NO), the frame is resized and the reduction factor is unchanged. If the SoundView is in a ScrollingView, autoScaling should be disabled (autoscaling is disabled by default).

setBackgroundGray:

- setBackgroundGray:(float)aGray

Sets the SoundView's background gray value to aGray; the default is NSWhite.

setBezeled:

- setBezeled:(BOOL)aFlag

If aFlag is YES, the display is given a bezeled border. By default, the border of a SoundView display isn't bezeled. If autodisplaying is enabled, the Sound is automatically redisplayed.

setContinuous:

- setContinuous:(BOOL)aFlag

Sets the state of continuous action messages. If aFlag is YES, selectionDidChange: messages are sent to the delegate as the mouse is being dragged. If NO, the message is sent only on mouse up. The default is NO.

setDelegate:

- setDelegate:anObject

Sets the SoundView's delegate to anObject. The delegate is sent messages when the user changes or acts on the selection.

setDisplayMode:

- setDisplayMode:(int)aMode

Sets the SoundView's display mode, either NX_SOUNDVIEW_WAVE or NX_SOUNDVIEW_MINMAX (the default). If autodisplaying is enabled, the Sound is automatically redisplayed.

setEditable:

- setEditable:(BOOL)aFlag

Enables or disables editing in the SoundView as aFlag is YES or NO. By default, a SoundView is editable.

setEnabled:

- setEnabled:(BOOL)aFlag

Enables or disables the SoundView as aFlag is YES or NO. The mouse has no effect in a disabled SoundView. By default, a SoundView is enabled.

setForegroundGray:

- setForegroundGray:(float)aGray

Sets the SoundView's foreground gray value to aGray. The default is NSWhite.

setOptimizedForSpeed:

- setOptimizedForSpeed:(BOOL)flag

Sets the SoundView to optimize its display mechanism. Optimization greatly increases the speed with which data can be drawn, particularly for large sounds. It does so at the loss of some precision in representing the sound data; however, these inaccuracies are corrected as you zoom in on the data. All SoundView's are optimized by default.

setReductionFactor:

- setReductionFactor:(float)reductionFactor

Recomputes the size of the SoundView's frame, if autoscaling is disabled. The frame's size (in display units) is set according to the formula
displayUnits = sampleCount / reductionFactor

Increasing the reduction factor zooms out, decreasing zooms in on the data. If autodisplaying is enabled, the Sound is automatically redisplayed.
If the SoundView is in autoscaling mode, or reductionFactor is less than 1.0, the method avoids computing the frame size and returns nil. (In autoscaling mode, the reduction factor is automatically recomputed when the sound data changes--see scaleToFit:.) Otherwise, the method returns self. If reductionFactor is the same as the current reduction factor, the method returns immediately without recomputing the frame size.

setSelection:size:

- setSelection:(int)firstSample size:(int)sampleCount

Sets the selection to be sampleCount samples wide, starting with sample firstSample (samples are counted from 0).

setSound:

- setSound:aSound

Sets the SoundView's Sound object to aSound. If autoscaling is enabled, the drawing coordinate system is adjusted so aSound's data fits within the current frame. Otherwise, the frame is resized to accommodate the length of the data. If autodisplaying is enabled, the SoundView is automatically redisplayed.

showCursor

- showCursor

Displays the SoundView's cursor. This is usually handled automatically.

sizeToFit

- sizeToFit

Resizes the SoundView's frame (horizontally) to maintain a constant reduction factor. This method is invoked automatically when the SoundView's data changes and the SoundView isn't in autoscale mode. If the SoundView is in autoscale mode, scaleToFit is invoked when the data changes. You never invoke this method directly; a subclass can reimplement this method to provide specialized behavior.

sound

- sound

Returns a pointer to the SoundView's Sound object.

soundBeingProcessed

- soundBeingProcessed

Returns the Sound object that's currently being played or recorded into. Note that the actual Sound object that's being performed isn't necessarily the SoundView's sound (the object returned by the sound method); for efficiency,
SoundView creates a private performance Sound object. While this is generally an implementation detail, this method is supplied in case the SoundView's delegate needs to know exactly which object will be (or was) performed.

stop:

- stop:sender

Stops the SoundView's current recording or playback.

tellDelegate:

- tellDelegate:(SEL)theMessage

Sends theMessage to the SoundView's delegate with the SoundView as the argument. If the delegate doesn't respond to the message, then it isn't sent. You normally never invoke this method; it's invoked automatically when an action, such as playing or editing, is performed. However, you can invoke it in the design of a SoundView subclass.

validRequestorForSendType:andReturnType:

- validRequestorForSendType:(NSString)sendType
    andReturnType:(NSString)returnType

You never invoke this method; it's implemented to support services that act on sound data.

willPlay:

- willPlay:sender

Used to redirect delegate messages from the SoundView's Sound object; you never invoke this method directly.

willRecord:

- willRecord:sender

Used to redirect delegate messages from the SoundView's Sound object; you never invoke this method directly.

writeSelectionToPasteboard:types:

- writeSelectionToPasteboard:(NSPasteboard *)pboard
    types:(NSArray *)types;

Places a copy of the SoundView's current selection on the given pasteboard. The types argument is currently ignored.

Methods Implemented by the Delegate

didPlay:

- didPlay:sender

Sent to the delegate just after the SoundView's sound is played.

didRecord:

- didRecord:sender

Sent to the delegate just after the SoundView's sound is recorded into.

hadError:

- hadError:sender

Sent to the delegate if an error is encountered during recording or playback of the SoundView's sound.

selectionDidChange:

- selectionDidChange:sender

Sent to the delegate when the SoundView's selection changes.

soundDidChange:

- soundDidChange:sender

Sent to the delegate when the SoundView's sound data is edited.

willFree:

- willFree:sender

Sent to the delegate when the SoundView is freed.

willPlay:

- willPlay:sender

Sent to the delegate just before the SoundView's sound is played.

willRecord:

- willRecord:sender

Sent to the delegate just before the SoundView's sound is recorded into.