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

The best GIF making apps
Animated GIFs have exploded in popularity recently which is likely thanks to a combination of Tumblr, our shorter attention spans, and the simple fact they’re a lot of fun. [Read more] | Read more »
The best remote desktop apps for iOS
We've been sifting through the App Store to find the best ways to do computer tasks on a tablet. That gave us a thought - what if we could just do computer tasks from our tablets? Here's a list of the best remote desktop apps to help you use your... | Read more »
Warhammer 40,000: Freeblade guide - How...
Warhammer 40,000: Freebladejust launched in the App Store and it lets you live your childhood dream of blowing up and slashing a bunch of enemies as a massive, hulking Space Marine. It's not easy being a Space Marine though - and particularly if... | Read more »
Gopogo guide - How to bounce like the be...
Nitrome just launched a new game and, as to be expected, it's a lot of addictive fun. It's called Gopogo, and it challenges you to hoparound a bunch of platforms, avoiding enemies and picking up shiny stuff. It's not easy though - just like the... | Read more »
Sago Mini Superhero (Education)
Sago Mini Superhero 1.0 Device: iOS Universal Category: Education Price: $2.99, Version: 1.0 (iTunes) Description: KAPOW! Jack the rabbit bursts into the sky as the Sago Mini Superhero! Fly with Jack as he lifts impossible weights,... | Read more »
Star Wars: Galaxy of Heroes guide - How...
Star Wars: Galaxy of Heroes is all about collecting heroes, powering them up, and using them together to defeat your foes. It's pretty straightforward stuff for the most part, but increasing your characters' stats can be a bit confusing because it... | Read more »
The best cooking apps (just in time for...
It’s that time of year again, where you’ll be gathering around the dinner table with your family and a huge feast in front of you. [Read more] | Read more »
Square Rave guide - How to grab those te...
Square Rave is an awesome little music-oriented puzzle game that smacks of games like Lumines, but with its own unique sense of gameplay. To help wrap your head around the game, keep the following tips and tricks in mind. [Read more] | Read more »
Snowboard Party 2 (Games)
Snowboard Party 2 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Crowned the best snowboarding game available on the market, Snowboard Party is back to fulfill all your adrenaline needs in... | Read more »
One Button Travel (Games)
One Button Travel 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: “To cut a long story short, If you like interactive fiction, just go buy this one.” - “Oozes the polish that... | Read more »

Price Scanner via

Holiday weekend Mac sales roundup: B&H Ph...
B&H Photo continues to have all new Macs on sale for up to $500 off MSRP as part of their Black Friday/Holiday weekend sale. Shipping is free, and B&H charges NY tax only: - 15″ 2.2GHz Retina... Read more
iMobie Releases its Ace iOS Cleaner PhoneClea...
iMobie Inc. has announced the new update of PhoneClean 4, its iOS cleaner designed to reclaim wasted space on iPhone/iPad for use and keep the device fast. Alongside, iMobie hosts a 3-day giveaway of... Read more
U.S. Cellular Offering iPad Pro
U.S. Cellular today announced that it is offering the new iPad Pro with Wi-Fi + Cellular, featuring a 12.9-inch Retina display with 5.6 million pixels — the most ever in an iOS device. U.S. Cellular... Read more
Newegg Canada Unveils Black Friday Deals for...
Newegg Canada is offering more than 1,000 deep discounts to Canadian customers this Black Friday, available now through Cyber Monday, with new deals posted throughout the week. “Black Friday is... Read more
Black Friday: Macs on sale for up to $500 off...
BLACK FRIDAY B&H Photo has all new Macs on sale for up to $500 off MSRP as part of their early Black Friday sale including free shipping plus NY sales tax only: - 15″ 2.2GHz Retina MacBook Pro: $... Read more
Black Friday: Up to $125 off iPad Air 2s at B...
BLACK FRIDAY Walmart has the 16GB iPad Air 2 WiFi on sale for $100 off MSRP on their online store. Choose free shipping or free local store pickup (if available): - 16GB iPad Air 2 WiFi: $399, save $... Read more
Black Friday: iPad mini 4s on sale for $100 o...
BLACK FRIDAY Best Buy has iPad mini 4s on sale for $100 off MSRP on their online store for Black Friday. Choose free shipping or free local store pickup (if available): - 16GB iPad mini 4 WiFi: $299.... Read more
Black Friday: Apple Watch for up to $100 off...
BLACK FRIDAY Apple resellers are offering discounts and bundles with the purchase of an Apple Watch this Black Friday. Below is a roundup of the deals being offered by authorized Watch resellers:... Read more
Black Friday: Target offers 6th Generation iP...
BLACK FRIDAY Save $40 to $60 on a 6th generation iPod touch at Target with free shipping or free local store pickup (if available). Sale prices for online orders only, in-store prices may vary: -... Read more
Black Friday: Walmart and Target offer iPod n...
BLACK FRIDAY Walmart has the 16GB iPod nano (various colors) on sale for $119.20 on their online store for a limited time. That’s $30 off MSRP. Choose free shipping or free local store pickup (if... Read more

Jobs Board

*Apple* Site Security Manager - Apple (Unite...
# Apple Site Security Manager Job Number: 42975010 Culver City, Califo ia, United States Posted: Oct. 2, 2015 Weekly Hours: 40.00 **Job Summary** The Apple Site Read more
WiSE *Apple* Pay Quality Engineer - Apple (...
# WiSE Apple Pay Quality Engineer Job Number: 44313381 Santa Clara Valley, Califo ia, United States Posted: Nov. 13, 2015 Weekly Hours: 40.00 **Job Summary** Join our Read more
Holiday Retail Associate with *Apple* Knowl...
…and assertive.Someone who can troubleshoot iOS devices (iPhone and iPad) and Apple Mail issues.Someone who can offer solutions.Someone who can work weekends.Someone with Read more
*Apple* Systems Engineer (Mclean, VA and NYC...
Summary:Assist in providing strategic direction and technical leadership within the Apple portfolio, including desktops, laptops, and printing environment. This person Read more
Simply Mac *Apple* Specialist- Service Repa...
Simply Mac is the largest premier retailer of Apple products in the nation. In order to support our growing customer base, we are currently looking for a driven Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.