ptolemy.actor.lib.javasound
Class AudioWriteBuffer

java.lang.Object
  extended by ptolemy.kernel.util.NamedObj
      extended by ptolemy.kernel.InstantiableNamedObj
          extended by ptolemy.kernel.Entity
              extended by ptolemy.kernel.ComponentEntity
                  extended by ptolemy.actor.AtomicActor
                      extended by ptolemy.actor.TypedAtomicActor
                          extended by ptolemy.actor.lib.javasound.AudioWriteBuffer
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, Actor, Executable, FiringsRecordable, Initializable, TypedActor, Changeable, Debuggable, DebugListener, Derivable, Instantiable, ModelErrorHandler, MoMLExportable, Moveable, Nameable

public class AudioWriteBuffer
extends TypedAtomicActor

This actor writes audio samples to a buffer and saves the buffer to a sound file on wrapup. In each iteration, if there is a token available on the data and address ports, then the data DoubleToken is written to the buffer location specified by the address IntToken. The valid address range is 0 to bufferLength -1. If an invalid address is specified, then the data value will be ignored and no data will be written. The audio samples in the buffer will be written to the sound file specified by the pathName parameter on wrapup.

Any existing file with the same name will be silently overwritten. The data port is of type DoubleToken. Each DoubleToken read from the data port represents one sample of the audio data and should be in the range [-1.0, 1.0]. Any samples that are outside of this range will be hard-clipped to fall within this range before they are written to the sound file. Single channel (mono) audio is supported but stereo is not supported.

The following parameters should be set to specify the format of the file to write. In all cases, an exception is thrown if an illegal parameter value is used. Note that if a parameter is changed while audio writing is active, all data written so far will be saved, and the sound file will be closed. Subsequent audio samples will then be written to a new sound file with the new parameter values.

There are security issues involved with accessing files and audio resources in applets. By default, applets are not allowed to write files. The .java.policy file may be modified to grant applets more privileges.

Note: Requires Java 2 v1.3.0 or later.

FIXME: this should extend AudioWriter

Since:
Ptolemy II 2.0
Version:
$Id: AudioWriteBuffer.java 57040 2010-01-27 20:52:32Z cxh $
Author:
Brian K. Vogel
See Also:
Serialized Form
Accepted Rating:
Red (vogel)
Proposed Rating:
Red (vogel)

Nested Class Summary
 
Nested classes/interfaces inherited from class ptolemy.kernel.Entity
Entity.ContainedObjectsIterator
 
Field Summary
private  double[] _audioBuffer
           
private  double[][] _audioPutArray
           
private  int _channels
           
private  Token[][] _inArray
           
private  int _putSampleSize
           
private  boolean _safeToInitialize
           
private  SoundWriter _soundWriter
           
 TypedIOPort address
          The address port, which is a multiport.
 Parameter bitsPerSample
          The desired number of bits per sample.
 Parameter bufferLength
          The length of the audio buffer to use.
 Parameter channels
          The number of audio channels to use.
 TypedIOPort data
          The data port, which is a multiport.
 Parameter overwrite
          The write mode to use.
 StringAttribute pathName
          The name of the file to write to.
 Parameter sampleRate
          The desired sample rate to use, in Hz.
 
Fields inherited from class ptolemy.actor.AtomicActor
_actorFiringListeners, _initializables, _notifyingActorFiring, _stopRequested
 
Fields inherited from class ptolemy.kernel.util.NamedObj
_changeListeners, _changeLock, _changeRequests, _debugging, _debugListeners, _elementName, _isPersistent, _verbose, _workspace, ATTRIBUTES, CLASSNAME, COMPLETE, CONTENTS, DEEP, FULLNAME, LINKS
 
Fields inherited from interface ptolemy.actor.Executable
COMPLETED, NOT_READY, STOP_ITERATING
 
Constructor Summary
AudioWriteBuffer(CompositeEntity container, java.lang.String name)
          Construct an actor with the given container and name.
 
Method Summary
private  void _initializeWriter()
          Initialize/Reinitialize audio resources.
 void attributeChanged(Attribute attribute)
          Handle change requests for all parameters.
 void fire()
          If there is a token available on the data and address ports, then the data DoubleToken is written to the buffer location specified by the address IntToken.
 void initialize()
          Open a new audio file for writing.
 boolean postfire()
          Return true.
 void preinitialize()
          Set up the number channels to use.
 void wrapup()
          Close the specified file.
 
Methods inherited from class ptolemy.actor.TypedAtomicActor
_addPort, _fireAt, _fireAt, attributeTypeChanged, clone, newPort, typeConstraintList, typeConstraints
 
Methods inherited from class ptolemy.actor.AtomicActor
_actorFiring, _actorFiring, addActorFiringListener, addInitializable, clone, connectionsChanged, createReceivers, declareDelayDependency, getCausalityInterface, getDirector, getExecutiveDirector, getManager, inputPortList, isFireFunctional, isStrict, iterate, newReceiver, outputPortList, prefire, pruneDependencies, recordFiring, removeActorFiringListener, removeDependency, removeInitializable, setContainer, stop, stopFire, terminate
 
Methods inherited from class ptolemy.kernel.ComponentEntity
_adjustDeferrals, _checkContainer, _getContainedObject, _propagateExistence, getContainer, instantiate, isAtomic, isOpaque, moveDown, moveToFirst, moveToIndex, moveToLast, moveUp, propagateExistence, setName
 
Methods inherited from class ptolemy.kernel.Entity
_description, _exportMoMLContents, _removePort, _validateSettables, connectedPortList, connectedPorts, containedObjectsIterator, getAttribute, getPort, getPorts, linkedRelationList, linkedRelations, portList, removeAllPorts, setClassDefinition, uniqueName
 
Methods inherited from class ptolemy.kernel.InstantiableNamedObj
_setParent, exportMoML, getChildren, getElementName, getParent, getPrototypeList, isClassDefinition, isWithinClassDefinition
 
Methods inherited from class ptolemy.kernel.util.NamedObj
_addAttribute, _adjustOverride, _attachText, _cloneFixAttributeFields, _debug, _debug, _debug, _debug, _debug, _getIndentPrefix, _isMoMLSuppressed, _markContentsDerived, _propagateValue, _recordDecoratedAttributes, _removeAttribute, _splitName, _stripNumericSuffix, addChangeListener, addDebugListener, attributeList, attributeList, deepContains, depthInHierarchy, description, description, event, executeChangeRequests, exportMoML, exportMoML, exportMoML, exportMoML, exportMoMLPlain, getAttribute, getAttributes, getChangeListeners, getClassName, getDecoratorAttribute, getDecoratorAttributes, getDerivedLevel, getDerivedList, getDisplayName, getFullName, getModelErrorHandler, getName, getName, getSource, handleModelError, isDeferringChangeRequests, isOverridden, isPersistent, lazyContainedObjectsIterator, message, propagateValue, propagateValues, removeChangeListener, removeDebugListener, requestChange, setClassName, setDeferringChangeRequests, setDerivedLevel, setDisplayName, setModelErrorHandler, setPersistent, setSource, sortContainedObjects, toplevel, toString, validateSettables, workspace
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface ptolemy.actor.Actor
createReceivers, getCausalityInterface, getDirector, getExecutiveDirector, getManager, inputPortList, newReceiver, outputPortList
 
Methods inherited from interface ptolemy.actor.Executable
isFireFunctional, isStrict, iterate, prefire, stop, stopFire, terminate
 
Methods inherited from interface ptolemy.actor.Initializable
addInitializable, removeInitializable
 
Methods inherited from interface ptolemy.kernel.util.Nameable
description, getContainer, getDisplayName, getFullName, getName, getName, setName
 
Methods inherited from interface ptolemy.kernel.util.Derivable
getDerivedLevel, getDerivedList, propagateValue
 

Field Detail

address

public TypedIOPort address
The address port, which is a multiport.


data

public TypedIOPort data
The data port, which is a multiport.


bufferLength

public Parameter bufferLength
The length of the audio buffer to use. The default value is 8000.


overwrite

public Parameter overwrite
The write mode to use. If this parameter is set to true, then a write to a buffer element overwrites the old value in the buffer. Otherwise, a write adds the new value to the old value of the buffer element.


pathName

public StringAttribute pathName
The name of the file to write to. The default value of this parameter is "test.wav", which creates a file called test.wav in the current directory and writes samples to this file.

The audio format to use is determined by the file extension. E.g., "outfile.wav" will create a WAV format file. The supported file formats are AU, WAV, and, AIFF.

An exception will be occur if the path references an unsupported sound file.


sampleRate

public Parameter sampleRate
The desired sample rate to use, in Hz. Valid values include: 8000, 11025, 22050, 44100, and 48000. The default value of the sample rate is an IntToken equal to 8000.

An exception will be thrown if an illegal value is used.


bitsPerSample

public Parameter bitsPerSample
The desired number of bits per sample. The default value is an IntToken equal to 16. Supported values are 8 and 16. An exception will be thrown if an illegal value is used.


channels

public Parameter channels
The number of audio channels to use. Supported values are 1 (single channel) and 2 (stereo). The default value is an IntToken equal to 1. An exception will be thrown if an illegal value is used.


_soundWriter

private SoundWriter _soundWriter

_channels

private int _channels

_putSampleSize

private int _putSampleSize

_audioPutArray

private double[][] _audioPutArray

_inArray

private Token[][] _inArray

_safeToInitialize

private boolean _safeToInitialize

_audioBuffer

private double[] _audioBuffer
Constructor Detail

AudioWriteBuffer

public AudioWriteBuffer(CompositeEntity container,
                        java.lang.String name)
                 throws IllegalActionException,
                        NameDuplicationException
Construct an actor with the given container and name.

Parameters:
container - The container.
name - The name of this actor.
Throws:
IllegalActionException - If the actor cannot be contained by the proposed container.
NameDuplicationException - If the container already has an actor with this name.
Method Detail

attributeChanged

public void attributeChanged(Attribute attribute)
                      throws IllegalActionException
Handle change requests for all parameters. An exception is thrown if the requested change is not allowed.

Overrides:
attributeChanged in class NamedObj
Parameters:
attribute - The attribute that changed.
Throws:
IllegalActionException - If the change is not allowed.

initialize

public void initialize()
                throws IllegalActionException
Open a new audio file for writing. Any existing file with the same name will be overwritten.

Specified by:
initialize in interface Initializable
Overrides:
initialize in class AtomicActor
Throws:
IllegalActionException - If the file cannot be opened, or if the parent class throws it.

fire

public void fire()
          throws IllegalActionException
If there is a token available on the data and address ports, then the data DoubleToken is written to the buffer location specified by the address IntToken. The valid address range is 0 to bufferLength -1. If an invalid address is specified, then the data value will be ignored and no data will be written. The audio samples in the buffer will be written to the sound file specified by the pathName parameter on wrapup.

Specified by:
fire in interface Executable
Overrides:
fire in class AtomicActor
Throws:
IllegalActionException - Not thrown in this base class.

postfire

public boolean postfire()
                 throws IllegalActionException
Return true.

Specified by:
postfire in interface Executable
Overrides:
postfire in class AtomicActor
Returns:
True if execution can continue into the next iteration.
Throws:
IllegalActionException - Not thrown in this base class.

preinitialize

public void preinitialize()
                   throws IllegalActionException
Set up the number channels to use. for use in the postfire() method.

Specified by:
preinitialize in interface Initializable
Overrides:
preinitialize in class AtomicActor
Throws:
IllegalActionException - If the parent class throws it.

wrapup

public void wrapup()
            throws IllegalActionException
Close the specified file.

Specified by:
wrapup in interface Initializable
Overrides:
wrapup in class AtomicActor
Throws:
IllegalActionException - If there is a problem closing the file.

_initializeWriter

private void _initializeWriter()
                        throws IllegalActionException
Initialize/Reinitialize audio resources. First close any open sound files. Then reread all parameters, create a new SoundWriter object.

This method is synchronized since it is not safe to call SoundWriter methods while this method is executing.

Throws:
IllegalActionException - If there is a problem initializing the SoundWriter object.