TweetFollow Us on Twitter


Demonstration Program SoundAndSpeech

Goto Contents

// *******************************************************************************************
// SoundAndSpeech.c                                                         CARBON EVENT MODEL
// *******************************************************************************************
// This program opens a modeless dialog containing five bevel button controls arranged in
// two groups, namely, a synchronous sound group and an asynchronous sound group.  Clicking on
// the bevel buttons causes sound to be played back or recorded as follows:
// o  Synchronous group:
//    o  Play sound resource.
//    o  Record sound resource (Mac OS 8/9 only).
//    o  Speak text string.
// o  Asynchronous group:
//    o  Play sound resource.
//    o  Speak text string.
// The asynchronous sound sections of the program utilise a special library called
// AsyncSoundLibPPC, which must be included in the CodeWarrior project.
// The program utilises the following resources:
// o  A 'plst' resource.
// o  A 'DLOG' resource and associated 'DITL', 'dlgx', and 'dftb' resources (all purgeable).
// o  'CNTL' resources (purgeable) for the controls within the dialog.
// o  Two 'snd ' resources, one for synchronous playback (purgeable) and one for asynchronous
//    playback (purgeable).
// o  Four 'cicn' resources (purgeable).  Two are used to provide an animated display which
//    halts during synchronous playback and continues during asynchronous playback.  The
//    remaining two are used by the bevel button controls.
// o  Two 'STR#' resources containing "speak text" strings and error message strings (all
//    purgeable).
// o  'hrct' and 'hwin' resources (purgeable) for balloon help.
// o  A 'SIZE' resource with the acceptSuspendResumeEvents, canBackground, 
//    doesActivateOnFGSwitch, and isHighLevelEventAware flags set.
// Each time it is invoked, the function doRecordResource creates a new 'snd' resource with a
// unique ID in the resource fork of a file titled "SoundResources".
// *******************************************************************************************

// .................................................................................. includes

#include <Carbon.h>
#include <string.h>

// ................................................................................... defines

#define rDialog                 128
#define  iDone                  1
#define  iPlayResourceSync      4
#define  iRecordResource        5
#define  iSpeakTextSync         6
#define  iPlayResourceASync     7
#define  iSpeakTextAsync        8
#define rPlaySoundResourceSync  8192
#define rPlaySoundResourceASync 8193
#define rSpeechStrings          128
#define rErrorStrings           129
#define  eOpenDialogFail        1
#define  eCannotInitialise      2
#define  eGetResource           3
#define  eMemory                4
#define  eMakeFSSpec            5
#define  eWriteResource         6
#define  eNoChannelsAvailable   7
#define  ePlaySound             8
#define  eSndPlay               9
#define  eSndRecord             10
#define  eSpeakString           11
#define rColourIcon1            128
#define rColourIcon2            129
#define kMaxChannels            8
#define kOutOfChannels          1

// .......................................................................... global variables

Boolean     gRunningOnX = false;
DialogRef   gDialogRef;
CIconHandle gColourIconHdl1;
CIconHandle gColourIconHdl2;

// .............................................................. AsyncSoundLib attention flag

Boolean  gCallAS_CloseChannel = false;

// ....................................................................... function prototypes

void      main                 (void);
void      doPreliminaries      (void);
OSStatus  windowEventHandler   (EventHandlerCallRef,EventRef,void *);
void      doIdle               (void);
void      doInitialiseSoundLib (void);
void      doDialogHit          (SInt16);
void      doPlayResourceSync   (void);
void      doRecordResource     (void);
void      doSpeakStringSync    (void);
void      doPlayResourceASync  (void);
void      doSpeakStringAsync   (void);
void      doSetUpDialog        (void);
void      doErrorAlert         (SInt16);
void      helpTags             (DialogRef);

// ......................................................... AsyncSoundLib function prototypes

OSErr  AS_Initialise   (Boolean *,SInt16);
OSErr  AS_GetChannel   (SInt32,SndChannelPtr *);
OSErr  AS_PlayID       (SInt16, SInt32 *);
OSErr  AS_PlayHandle   (Handle,SInt32 *);
void   AS_CloseChannel (void);
void   AS_CloseDown    (void);

// ************************************************************************************** main

void main(void)
  SInt32         response;
  EventTypeSpec  windowEvents[] = { { kEventClassWindow, kEventWindowClose },
                                    { kEventClassMouse,  kEventMouseDown   } };

  // ........................................................................ do preliminaries


  // .......................................... disable Quit item in Mac OS X Application menu


  // ......................................................................... install a timer
                        NewEventLoopTimerUPP((EventLoopTimerProcPtr) doIdle),NULL,

  // .................................................................. open and set up dialog

  if(!(gDialogRef = GetNewDialog(rDialog,NULL,(WindowRef) -1)))


  ChangeWindowAttributes(GetDialogWindow(gDialogRef),kWindowStandardHandlerAttribute |

                            NewEventHandlerUPP((EventHandlerProcPtr) windowEventHandler),

  if(response & gestaltMenuMgrAquaLayoutMask)
    gRunningOnX = true;


  // ................................................................ initialise AsyncSoundLib


  // ........................................................................ get colour icons

  gColourIconHdl1 = GetCIcon(rColourIcon1);
  gColourIconHdl2 = GetCIcon(rColourIcon2);

  // .............................................................. run application event loop


// *************************************************************************** doPreliminaries

void  doPreliminaries(void)

// ************************************************************************ windowEventHandler

OSStatus  windowEventHandler(EventHandlerCallRef eventHandlerCallRef,EventRef eventRef,
                             void* userData)
  OSStatus    result = eventNotHandledErr;
  UInt32      eventClass;
  UInt32      eventKind;
  EventRecord eventRecord;
  SInt16      itemHit;
  eventClass = GetEventClass(eventRef);
  eventKind  = GetEventKind(eventRef);

    case kEventClassWindow:                                               // event class window
        case kEventWindowClose:
          result = noErr;

    case kEventClassMouse:                                                // event class mouse
        case kEventMouseDown:
            result = noErr;

  return result;

// ************************************************************************************ doIdle

void  doIdle(void)
  Rect           theRect, eraseRect;
  UInt32         finalTicks;
  SInt16         fontNum;
  static Boolean flip;



    DrawString("\pAS_CloseChannel called");


  flip = !flip;


// ********************************************************************** doInitialiseSoundLib

void  doInitialiseSoundLib(void)
  if(AS_Initialise(&gCallAS_CloseChannel,kMaxChannels) != noErr)

// ******************************************************************************* doDialogHit

void  doDialogHit(SInt16 item)
    case iDone:

    case iPlayResourceSync:

    case iRecordResource:

    case iSpeakTextSync:

    case iPlayResourceASync:

    case iSpeakTextAsync:

// ************************************************************************ doPlayResourceSync

void  doPlayResourceSync(void)
  SndListHandle sndListHdl;
  SInt16        resErr;
  OSErr         osErr;
  ControlRef    controlRef;

  sndListHdl = (SndListHandle) GetResource('snd ',rPlaySoundResourceSync);
  resErr = ResError();
  if(resErr != noErr)

  if(sndListHdl != NULL)
    HLock((Handle) sndListHdl);
    osErr = SndPlay(NULL,sndListHdl,false);
    if(osErr != noErr)
    HUnlock((Handle) sndListHdl);
    ReleaseResource((Handle) sndListHdl);


// ************************************************************************** doRecordResource

void  doRecordResource(void)
  SInt16     oldResFileRefNum, theResourceID, resErr, tempResFileRefNum;
  BitMap     screenBits;
  Point      topLeft;
  OSErr      memErr, osErr;
  Handle     soundHdl;
  FSSpec     fileSpecTemp;
  ControlRef controlRef;

  oldResFileRefNum = CurResFile();

  topLeft.h = (screenBits.bounds.right / 2) - 156;
  topLeft.v = 150;
  soundHdl = NewHandle(25000);
  memErr = MemError();
  if(memErr != noErr)

  osErr = FSMakeFSSpec(0,0,"\pSoundResources",&fileSpecTemp);
  if(osErr == noErr)
    tempResFileRefNum = FSpOpenResFile(&fileSpecTemp,fsWrPerm);

  if(osErr == noErr)
    osErr = SndRecord(NULL,topLeft,siBetterQuality,&(SndListHandle) soundHdl);
    if(osErr != noErr && osErr != userCanceledErr)
    else if(osErr != userCanceledErr)
        theResourceID = UniqueID('snd ');
      } while(theResourceID <= 8191 && theResourceID >= 0);

      AddResource(soundHdl,'snd ',theResourceID,"\pTest");
      resErr = ResError();
      if(resErr == noErr)
      resErr = ResError();
      if(resErr != noErr)




// ************************************************************************* doSpeakStringSync

void  doSpeakStringSync(void)
  SInt16     activeChannels;
  Str255     theString;
  OSErr      resErr, osErr;
  ControlRef controlRef;

  activeChannels = SpeechBusy();

  resErr = ResError();
  if(resErr != noErr)

  osErr = SpeakString(theString);
  if(osErr != noErr)

  while(SpeechBusy() != activeChannels)


// *********************************************************************** doPlayResourceASync

void  doPlayResourceASync(void)
  SInt16 error;

  error = AS_PlayID(rPlaySoundResourceASync,NULL);
  if(error == kOutOfChannels)
    if(error != noErr)

// ************************************************************************ doSpeakStringAsync

void  doSpeakStringAsync(void)
  Str255 theString;
  OSErr  resErr, osErr;

  resErr = ResError();
  if(resErr != noErr)

  osErr = SpeakString(theString);
  if(osErr != noErr)

// ***************************************************************************** doSetUpDialog

void  doSetUpDialog(void)
  SInt16                        a;
  Point                         offset;
  ControlRef                    controlRef;
  ControlButtonGraphicAlignment alignConstant = kControlBevelButtonAlignLeft;
  ControlButtonTextPlacement    placeConstant = kControlBevelButtonPlaceToRightOfGraphic;

  offset.v = 1;
  offset.h = 5;



// ****************************************************************************** doErrorAlert

void  doErrorAlert(SInt16 errorStringIndex)
  Str255 errorString;
  SInt16 itemHit;



// ********************************************************************************** helpTags

void  helpTags(DialogRef dialogRef)
  HMHelpContentRec helpContent;
  SInt16           a;
  ControlRef       controlRef;


  helpContent.version = kMacHelpVersion;
  helpContent.tagSide = kHMOutsideTopCenterAligned;
  helpContent.content[kHMMinimumContentIndex].contentType = kHMStringResContent;
  helpContent.content[kHMMinimumContentIndex].u.tagStringRes.hmmResID = 130;

  for(a = 1;a <= 5; a++)
    if(a == 2)
    helpContent.content[kHMMinimumContentIndex].u.tagStringRes.hmmIndex = a;
    GetDialogItemAsControl(dialogRef,a + 3,&controlRef);

// *******************************************************************************************

Demonstration Program SoundAndSpeech Comments

When this program is run, the user should click on the various buttons in the dialog to play
back and record (Mac OS 8/9 only) sound resources and to play back the provided "speak text"
strings.  The user should observe the effects of asynchronous and synchronous playback on the
"working man" icon in the image well in the dialog.  The user should also observe that the text
"AS_CloseChannel called" appears briefly in the secondary group box to the right of the
"working man" icon when AsynchSoundLib sets the application's "attention" flag to true, thus
causing the application to call the AsynchSoundLib function AS_CloseChannel.

Note that the doRecordResource function saves recorded sounds as 'snd ' resources with unique
IDs in the resource fork of the file titled "SoundResources".

On Mac OS 9, ensure that the Speech Manager extension is activated before running this program.


kMaxChannels will be used to specify the maximum number of sound channels that AsynchSoundLib
is to open.  kOutOfChannels will be used to determine whether the AsynchSoundLib function
AS_PlayID returns a "no channels available" error.


A timer is installed and set to fire repeatedly every 10 ticks.  When the timer fires, the
function doIdle is called.

doInitialiseSoundLib is called to initialise the AsynchSoundLib library.


doIdle is called every time the timer fires.

The "attention" flag (gAS_CloseChannel) required by AsynchSoundLib is checked.  If
AsynchSoundLib has set it to true, the AsynchSoundLib function AS_CloseChannel is called to
free up the relevant ASStructure, close the relevant sound channel, and clear the "attention"
flag.  In addition, some text is drawn in the group box to the right of the "working man" icon
to indicate to the user that AS_CloseChannel has just been called.

The next block draws one or other of the two "working man" icons, following which the interior
of the group box is erased.


doInitialiseSoundLib initialises the AsynchSoundLib library.  More specifically, it calls the
AsynchSoundLib function AS_Initialise and passes to AsynchSoundLib the address of the
application's "attention" flag (gAS_CloseChannel), together with the requested number of

If AS_Initialise returns a non-zero value, an error alert is displayed and the program


doPlayResourceSync is the first of the synchronous playback functions.  It uses SndPlay to play
a specified 'snd ' resource.

GetResource attempts to load the resource.  If the subsequent call to ResError indicates an
error, an error alert is presented.

If the load was successful, the sound handle is locked prior to a call to SndPlay.  Since NULL
is passed in the first parameter of the SndPlay call, SndPlay automatically allocates a sound
channel to play the sound and deallocates the channel when the playback is complete.  false
passed in the third parameter specifies that the playback is to be synchronous.

Note: The 39940-byte 'snd ' resource being used contains one command only (bufferCmd).  The
compressed sound header indicates MACE 3:1 compression.  The sound length is 119568 frames. 
The 8-bit mono sound was sampled at 22kHz.
SndPlay causes all commands and data contained in the sound handle to be sent to the channel. Since there is a bufferCmd command in the 'snd ' resource, the sound is played. If SndPlay returns an error, an error alert is presented. When SndPlay returns, HUnlock unlocks the sound handle and ReleaseResource releases the resource.


On Mac OS 8/9 only, doRecordResource uses SndRecord to record a sound synchronously and then
saves the sound in a 'snd ' resource.  The 'snd ' resource will be saved to the resource fork
of the file "SoundResources".

The first line saves the file reference number of the current resource file.  The next three
lines establish the location for the top left corner of the sound recording dialog.

NewHandle creates a relocatable block.  The address of the handle will be passed as the fourth
parameter of the SndRecord call.  The size of this block determines the recording time
available.  (If NULL is passed as the fourth parameter of a SndRecord call, the Sound Manager
allocates the largest block possible in the application's heap.)  If NewHandle cannot allocate
the block, an error alert is presented and the function returns.

The next block opens the resource fork of the file "SoundResources" and makes it the current
resource file.

SndRecord opens the sound recording dialog and handles all user interaction until the user
clicks the Cancel or Save button.  Note that the second parameter of the SndRecord call
establishes the location for the top left corner of the sound recording dialog and that the
third parameter specifies 22kHz, mono, 3:1 compression.

When the user clicks the Save button, the handle is resized automatically.  If the user clicks
the Cancel button, SndRecord returns userCanceledErr.  If SndRecord returns an error other than
userCanceledErr, an error alert is presented and the function returns after closing the
resource fork of the file, disposing of the relocatable block, and restoring the saved resource
file reference number.

The relocatable block allocated by NewHandle, and resized as appropriate by SndPlay, has the
structure of a 'snd ' resource, but its handle is not a handle to an existing resource.  To
save the recorded sound as a 'snd ' resource in the resource fork of the current resource file,
the do/while loop first finds an acceptable unique resource ID for the resource.  (For the
System file, resource IDs for 'snd ' resources in the range 0 to 8191 are reserved for use by
Apple Computer, Inc.  Avoiding those IDs in this demonstration is not strictly necessary, since
there is no intention to move those resources to the System file.)

The call to AddResource causes the Resource Manager to regard the relocatable block containing
the sound as a 'snd ' resource.  If the call is successful, UpdateResFile writes the changed
resource map and the 'snd ' resource to disk.  If an error occurs, an error alert is presented.

The relocatable block is then disposed of, the resource fork of the file "SoundResources" is
closed, and the saved resource file reference number is restored.


doSpeakStringSync uses SpeakString to speak a specified string resource and takes measures to
cause the speech to be generated in a psuedo-synchronous manner.

The speech that SpeakString generates is asynchronous, that is, control returns to the
application before SpeakString finishes speaking the string.  In this function, SpeechBusy is
used to cause the speech activity to be synchronous so far as the function as a whole is
concerned.  That is, doSpeakStringSync will not return until the speech activity is complete.

As a first step, the first line saves the number of speech channels that are active immediately
before the call to SpeakString.

GetIndString loads the first string from the specified 'STR#' resource.  If an error occurs, an
error alert is presented and the function returns.

SpeakString, which automatically allocates a speech channel, is called to speak the string.  If
SpeakString returns an error, an error alert is presented.

Although SpeakString returns control to the application immediately it starts generating the
speech, the speech channel it opens remains open until the speech concludes.  While the speech
continues, the number of speech channels open will be one more that the number saved at the
first line.  Accordingly, the while loop continues until the number of open speech channels is
equal to the number saved at the first line.  Then, and only then, does doSpeakStringSync exit.


doPlayResourceASync uses the AsynchSoundLib function AS_PlayID to play a 'snd ' resource

Note: The 24194-byte 'snd ' resource being used contains one command only (bufferCmd).  The
compressed sound header indicates no compression.  The sound length is 24195 frames.  The 8-bit
mono sound was sampled at 5kHz.

AS_PlayID is called to play the 'snd ' resource specified in the first parameter. Since no further control over the playback is required, NULL is passed in the second parameter. (Recall that, if you pass a pointer to a variable in the second parameter, AS_PlayID returns a reference number in that parameter. That reference number may be used to gain more control over the playback process. If you simply want to trigger a sound and let it to run to completion, you pass NULL in the second parameter, in which case a reference number is not returned by AS_PlayID.) If AS_PlayID returns the "no channels currently available" error, an error alert is presented advising of that specific condition. If any other error is returned, a more generalised error message is presented. When the sound has finished playing, ASynchSoundLib advises the application by setting the application's "attention" flag to true. Recall that this will cause the AsynchSoundLib function AS_CloseChannel to be called to free up the relevant ASStructure, close the relevant sound channel, clear the "attention" flag, and draw some text in the group box to the right of the image well to indicate to the user that AS_CloseChannel has just been called.


doSpeakStringAsync is identical to the function doSpeakStringSync except that, in this
function, SpeechBusy is not used to delay the function returning until the speech activity
spawned by SpeakString has run its course.


Within doSetUpDialog, the Record Sound Resource bevel button is disabled if the program is
running on OS X.

Community Search:
MacTech Search:

Software Updates via MacUpdate

A beginner's guide to Spellbinders
Spellbinderslooks a heck of a lot like Clash Royale, but has an entirely different pace to it. As such, it can be difficult to adjust to. Just in case you've been playing way too much Clash Royale (and who hasn't), we've put together a bunch of... | Read more »
Camping With Grandpa (Education)
Camping With Grandpa 1.0 Device: iOS Universal Category: Education Price: $2.99, Version: 1.0 (iTunes) Description: | Read more »
Black Hole Joyrider (Games)
Black Hole Joyrider 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: Guide your spacecraft through the gravity well of a powerful black hole using only your retro-thrusters and dwindling fuel... | Read more »
My Koi (Games)
My Koi 1.0 Device: iOS iPhone Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: My Koi is a beautiful and relaxing fish pond app. Customise and name each fish. Feed them daily. Watch them grow. Collect new fish.... | Read more »
Never Gone (Games)
Never Gone 1.0.2 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0.2 (iTunes) Description: ###IMPPORTANT### Never Gone's HD art resources require devices with more than 1GB RAM, so please note that iPhone 4/4s, iPad 2/... | Read more »
INKS. (Games)
INKS. 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: From the makers of BAFTA-winning Lumino City comes INKS. INKS updates pinball for a new generation. It combines the joy of pinball with... | Read more »
How to maximise your profits in Bakery B...
Running a bakery can be an expensive venture. You’ll need to continuously upgrade your oven, your kitchen supplies, and even your ingredients to keep customers happy. Most of these renovations in Bakery Blitz cost a pretty penny, but we have a few... | Read more »
How to manage your time in Bakery Blitz
It can be tricky, especially when you risk burning your kitchen to the ground if you forget a cake in the oven, so make sure to use these time management tricks to keep your bakery running smoothly. Don’t collect the money right away [Read more] | Read more »
Model 15 (Music)
Model 15 1.0 Device: iOS iPhone Category: Music Price: $29.99, Version: 1.0 (iTunes) Description: The Moog Model 15 App is the first Moog modular synthesizer and synthesis educational tool created exclusively for iPad, iPhone and... | Read more »
How to deal with wind in Angry Birds Act...
Angry Birds Action! is a physics-based puzzler in which you're tasked with dragging and launching birds around an obstacle-littered field to achieve a set objective. It's simple enough at first, but when wind gets introduced things can get pretty... | Read more »

Price Scanner via

Hybrid Tablets Meet Rising Demand for a Singl...
Rising demand for a new breed of hybrid tablets — 2 in 1 devices that function as either a laptop or a tablet — is shaking up the tablet market and contributing to a shift in the way owners are... Read more
Bausch + Lomb and IBM Collaborate on iPhone...
Global eye health company Bausch + Lomb, and IBM on Thursday announced a collaboration to develop the first app of its kind for iPhone and iPad for surgeons who perform cataract surgery. The... Read more
Apple & SAP Partner to Deliver New iOS Ap...
Apple and Walldorf, Germany based SAP have announced a partnership to revolutionize the mobile work experience for enterprise customers of all sizes, combining powerful native apps for iPhone and... Read more
New 12-inch 1.1GHz Rose Gold Retina MacBook o...
B&H Photo has the new 2016 12″ 1.1GHz/256GB Rose Gold Retina MacBook (sku MMGL2LL/A) on sale for $1199 including free shipping plus NY tax only. Their price is $100 off MSRP, and it’s the lowest... Read more
12-inch 128GB iPad Pros on sale for up to $10...
B&H Photo has 12″ 128GB WiFi iPad Pros on sale for up to $100 off MSRP, each including free shipping. B&H charges sales tax in NY only: - 12″ Space Gray 128GB WiFi iPad Pro: $899 $50 off MSRP... Read more
Global Tablet Sales Slump Continues, iPad’s F...
Another miserable showing for the global slate tablet category in calendar Q1/16, with global tablet shipments falling another 1ten percent to 46.5 million units during the according to Strategy... Read more
Revel Systems to Showcase iPad POS Platform w...
Revel Systems, specialists in iPad Point of Sale management solution for brick-and-mortar retail, food businesses and more, today announced that it will showcase its innovative iPad Point of Sale... Read more
13-inch 2.5GHz MacBook Pro on sale for $999,...
B&H Photo has the 13″ 2.5GHz MacBook Pro on sale for $999 including free shipping plus NY sales tax only. Their price is $100 off MSRP. Read more
Apple refurbished 2015 iMacs available for up...
Apple now has a full line of Certified Refurbished 2015 21″ & 27″ iMacs available for up to $350 off MSRP. Apple’s one-year warranty is standard, and shipping is free. The following models are... Read more
Indian Smartphone Market Grows Annually by 12...
India’s smartphone market grew by 12 percent year-over-year, with 24.4 million units shipping in Q1 2016. The top five vendors stayed the same, with Samsung in the lead, followed by Micromax, Intex... Read more

Jobs Board

*Apple* Support Technician II - Worldventure...
…global, fast growing member based travel company, is currently sourcing for an Apple Support Technician II to be based in our Plano headquarters. WorldVentures is Read more
*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
Restaurant Manager (Neighborhood Captain) - A...
…in every aspect of daily operation. WHY YOU'LL LIKE IT: You'll be the Big Apple . You'll solve problems. You'll get to show your ability to handle the stress and Read more
Automotive Sales Consultant - Apple Ford Linc...
…you. The best candidates are smart, technologically savvy and are customer focused. Apple Ford Lincoln Apple Valley is different, because: $30,000 annual salary Read more
Restaurant Manager (Neighborhood Captain) - A...
…in every aspect of daily operation. WHY YOU'LL LIKE IT: You'll be the Big Apple . You'll solve problems. You'll get to show your ability to handle the stress and Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.