Mac OS X PortAudio Recorder

Share your advanced PureBasic knowledge/code with the community.
chris319
Enthusiast
Enthusiast
Posts: 782
Joined: Mon Oct 24, 2005 1:05 pm

Mac OS X PortAudio Recorder

Post by chris319 »

Here is a simple audio recorder for Mac OS X using PortAudio (http://www.portaudio.com/).

FIrst you need PortAudio. I recommend downloading the latest daily SVN snapshot which has been fixed to compile with Snow Leopard. Here is how to compile PortAudio for OS X:

How to compile portaudio for OS X:

1. Xcode must be installed on the OS X computer.

2. From the PortAudio web site, download pa_snapshot.tgz file and extract using GUI Tar.

3. Open terminal

4. cd portaudio

5. ./configure

6. make

7. sudo make install

There will be a file named libportaudio.dylib in directory /usr/local/lib/

You need PortAudio.pb for OS X, to be located in the same directory as the source code file:

Code: Select all

; /*
;  * $Id: portaudio.h 1083 2006-08-23 07:30:49Z rossb $
;  * PortAudio Portable Real-Time Audio Library
;  * PortAudio API Header File
;  * Latest version available at: http://www.portaudio.com/
;  *
;  * Copyright (c) 1999-2002 Ross Bencina And Phil Burk
;  *
;  * Permission is hereby granted, free of charge, To any person obtaining
;  * a copy of this software And associated documentation files
;  * (the "Software"), To deal in the Software without restriction,
;  * including without limitation the rights To use, copy, modify, merge,
;  * publish, distribute, sublicense, And/Or sell copies of the Software,
;  * And To permit persons To whom the Software is furnished To do so,
;  * subject To the following conditions:
;  *
;  * The above copyright notice And this permission notice shall be
;  * included in all copies Or substantial portions of the Software.
;  *
;  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;  * EXPRESS Or IMPLIED, INCLUDING BUT Not LIMITED To THE WARRANTIES OF
;  * MERCHANTABILITY, FITNESS For A PARTICULAR PURPOSE And NONINFRINGEMENT.
;  * IN NO EVENT SHALL THE AUTHORS Or COPYRIGHT HOLDERS BE LIABLE For
;  * ANY CLAIM, DAMAGES Or OTHER LIABILITY, WHETHER IN AN ACTION OF
;  * CONTRACT, TORT Or OTHERWISE, ARISING FROM, OUT OF Or IN CONNECTION
;  * With THE SOFTWARE Or THE USE Or OTHER DEALINGS IN THE SOFTWARE.
;  */
; 
; /*
;  * The text above constitutes the entire PortAudio license; however, 
;  * the PortAudio community also makes the following non-binding requests:
;  *
;  * Any person wishing To distribute modifications To the Software is
;  * requested To send the modifications To the original developer so that
;  * they can be incorporated into the canonical version. It is also 
;  * requested that these non-binding requests be included along With the 
;  * license above.
;  */


Enumeration ; PaErrorCode
  #paNoError = 0

  #paNotInitialized = -10000
  #paUnanticipatedHostError
  #paInvalidChannelCount
  #paInvalidSampleRate
  #paInvalidDevice
  #paInvalidFlag
  #paSampleFormatNotSupported
  #paBadIODeviceCombination
  #paInsufficientMemory
  #paBufferTooBig
  #paBufferTooSmall
  #paNullCallback
  #paBadStreamPtr
  #paTimedOut
  #paInternalError
  #paDeviceUnavailable
  #paIncompatibleHostApiSpecificStreamInfo
  #paStreamIsStopped
  #paStreamIsNotStopped
  #paInputOverflowed
  #paOutputUnderflowed
  #paHostApiNotFound
  #paInvalidHostApi
  #paCanNotReadFromACallbackStream      ;/**< @todo review error code name */
  #paCanNotWriteToACallbackStream       ;/**< @todo review error code name */
  #paCanNotReadFromAnOutputOnlyStream   ;/**< @todo review error code name */
  #paCanNotWriteToAnInputOnlyStream     ;/**< @todo review error code name */
  #paIncompatibleStreamHostApi
  #paBadBufferPtr
EndEnumeration

#paNoDevice = (-1)
#paUseHostApiSpecificDeviceSpecification = (-2)

Enumeration ; PaHostApiTypeId
  #paInDevelopment = 0 ; /* use while developing support for a new host API */
  #paDirectSound = 1
  #paMME = 2
  #paASIO = 3
  #paSoundManager = 4
  #paCoreAudio = 5
  #paOSS = 7
  #paALSA = 8
  #paAL = 9
  #paBeOS = 10
  #paWDMKS = 11
  #paJACK = 12
  #paWASAPI = 13
	#paAudioScienceHPI = 14
EndEnumeration

#paFloat32        = ($00000001)
#paInt32          = ($00000002)
#paInt24          = ($00000004)
#paInt16          = ($00000008)
#paInt8           = ($00000010)
#paUInt8          = ($00000020)
#paCustomFormat   = ($00010000)
#paNonInterleaved = ($80000000)

#paFormatIsSupported = (0)
#paFramesPerBufferUnspecified = (0)
#paNoFlag          = (0)
#paClipOff         = ($00000001)
#paDitherOff       = ($00000002)
#paNeverDropInput  = ($00000004)
#paPrimeOutputBuffersUsingStreamCallback = ($00000008)
#paPlatformSpecificFlags = ($FFFF0000)

#paInputUnderflow   = ($00000001)
#paInputOverflow    = ($00000002)
#paOutputUnderflow  = ($00000004)
#paOutputOverflow   = ($00000008)
#paPrimingOutput    = ($00000010)

Enumeration ; PaStreamCallbackResult
  #paContinue=0
  #paComplete=1
  #paAbort=2
EndEnumeration

Structure PaHostApiInfo
  structVersion.l
  type.l
 *name.b
  deviceCount.l
  defaultInputDevice.l
  defaultOutputDevice.l
EndStructure

Structure PaHostErrorInfo
  hostApiType.l   
  errorCode.l            
 *errorText.b          
EndStructure

Structure PaDeviceInfo
  structVersion.l
 *name.b
  hostApi.l
  maxInputChannels.l
  maxOutputChannels.l
  defaultLowInputLatency.d
  defaultLowOutputLatency.d
  defaultHighInputLatency.d
  defaultHighOutputLatency.d
  defaultSampleRate.d
EndStructure

Structure PaStreamParameters
  device.l
  channelCount.l
  sampleFormat.l
  suggestedLatency.d
 *hostApiSpecificStreamInfo
EndStructure

Structure PaStreamCallbackTimeInfo
  inputBufferAdcTime.d
  currentTime.d
  outputBufferDacTime.d
EndStructure

Structure PaStreamInfo
  structVersion.l
  inputLatency.d
  outputLatency.d
  sampleRate.d
EndStructure

PrototypeC PaStreamCallback(*input, *output, frameCount, *timeInfo, statusFlags, *userdata)
PrototypeC PaStreamFinishedCallback(*user_data)


#paWinWasapiExclusive                = 1 << 0 ;puts WASAPI into exclusive mode
#paWinWasapiRedirectHostProcessor    = 1 << 1 ;allows To skip internal PA processing completely
#paWinWasapiUseChannelMask           = 1 << 2 ;assigns custom channel mask
#paWinWasapiPolling                  = 1 << 3 ;selects non-Event driven method of
;Data Read/write Note: WASAPI Event driven core is capable of 2ms latency, but Polling method
;can only provide 15-20ms latency.
#paWinWasapiThreadPriority           = 1 << 4 ;forces custom thread priority setting.
; must be used If PaWasapiStreamInfo::threadPriority is set To custom value.

;/* Host processor. Allows To skip internal PA processing completely. 
;   You must set paWinWasapiRedirectHostProcessor flag To PaWasapiStreamInfo::flags member
;   in order To have host processor redirected To your callback.
;   Use With caution! inputFrames And outputFrames depend solely on final device setup (buffer
;   size is just recommendation) but are Not changing during run-time once stream is started.
;*/
;typedef void (*PaWasapiHostProcessorCallback) (void *inputBuffer,  long inputFrames,
;                                               void *outputBuffer, long outputFrames,
;                                               void *userData);

Enumeration ;Device role
    #eRoleRemoteNetworkDevice = 0
    #eRoleSpeakers
    #eRoleLineLevel
    #eRoleHeadphones
    #eRoleMicrophone
    #eRoleHeadset
    #eRoleHandset
    #eRoleUnknownDigitalPassthrough
    #eRoleSPDIF
    #eRoleHDMI
    #eRoleUnknownFormFactor
EndEnumeration

Enumeration ;Thread priority
    #eThreadPriorityNone = 0
    #eThreadPriorityAudio ;Default For Shared mode.
    #eThreadPriorityCapture
    #eThreadPriorityDistribution
    #eThreadPriorityGames
    #eThreadPriorityPlayback
    #eThreadPriorityProAudio ;Default For Exclusive mode.
    #eThreadPriorityWindowManager
EndEnumeration

;Stream descriptor
Structure PaWasapiStreamInfo
  size.l ;= 32 ;SizeOf(PaWasapiStreamInfo)
  hostApiType.l ;#paWASAPI   ;PaHostApiTypeId hostApiType;    ;paWASAPI
  version.l          ;1
  flags.l            ;collection of PaWasapiFlags

;    /* Support For WAVEFORMATEXTENSIBLE channel masks. If flags contains
;       paWinWasapiUseChannelMask this allows you To specify which speakers 
;       To address in a multichannel stream. Constants For channelMask
;       are specified in pa_win_waveformat.h. Will be used only If 
;       paWinWasapiUseChannelMask flag is specified.
;    */
;    PaWinWaveFormatChannelMask channelMask
  channelMask.l

;    /* Delivers raw Data To callback obtained from GetBuffer() methods skipping 
;       internal PortAudio processing inventory completely. userData parameter will 
;       be the same that was passed To Pa_OpenStream method. Will be used only If 
;       paWinWasapiRedirectHostProcessor flag is specified.
;    */
;    PaWasapiHostProcessorCallback hostProcessorOutput
;    PaWasapiHostProcessorCallback hostProcessorInput

    hostProcessorOutput.l
    hostProcessorInput.l

;    /* Specifies thread priority explicitly. Will be used only If paWinWasapiThreadPriority flag
;       is specified.

;       Please note, If Input/Output streams are opened simultaniously (Full-Duplex mode)
;       you shall specify same value For threadPriority Or othervise one of the values will be used
;       To setup thread priority.
;    */
;    PaWasapiThreadPriority threadPriority
    threadPriority.l

EndStructure


;/* Returns Default sound format For device. Format is represented by PaWinWaveFormat Or 
;   WAVEFORMATEXTENSIBLE Structure.

; @param pFormat pointer To PaWinWaveFormat Or WAVEFORMATEXTENSIBLE Structure.
; @param nFormatSize pize of PaWinWaveFormat Or WAVEFORMATEXTENSIBLE Structure in bytes.
; @param nDevice device index.

 ;@return A non-negative value indicating the number of bytes copied into format decriptor
 ;        Or, a PaErrorCode (which are always negative) If PortAudio is Not initialized
 ;        Or an error is encountered.
;*/
;int PaWasapi_GetDeviceDefaultFormat( void *pFormat, unsigned int nFormatSize, PaDeviceIndex nDevice );


;/* Returns device role (PaWasapiDeviceRole enum).

 ;@param nDevice device index.

; @return A non-negative value indicating device role Or, a PaErrorCode (which are always negative)
;         If PortAudio is Not initialized Or an error is encountered.
;*/

;int/*PaWasapiDeviceRole*/ PaWasapi_GetDeviceRole( PaDeviceIndex nDevice );
;int PaWasapi_GetDeviceRole( PaDeviceIndex nDevice )

;/* Boost thread priority of calling thread (MMCSS). Use it For Blocking Interface only For thread
;    which makes calls To Pa_WriteStream/Pa_ReadStream.

; @param hTask a handle To pointer To priority task. Must be used With PaWasapi_RevertThreadPriority
;              method To revert thread priority To initial state.

 ;@param nPriorityClass an Id of thread priority of PaWasapiThreadPriority type. Specifying 
 ;                      eThreadPriorityNone does nothing.

; @return Error code indicating success Or failure.
; @see PaWasapi_RevertThreadPriority
;*/

;PaError PaWasapi_ThreadPriorityBoost( void **hTask, PaWasapiThreadPriority nPriorityClass );

;/** Boost thread priority of calling thread (MMCSS). Use it For Blocking Interface only For
;    thread which makes calls To Pa_WriteStream/Pa_ReadStream.

; @param hTask Task handle obtained by PaWasapi_BoostThreadPriority method.
; @return Error code indicating success Or failure.
; @see PaWasapi_BoostThreadPriority
;*/
;PaError PaWasapi_ThreadPriorityRevert( void *hTask );


;IMPORTANT:

;WASAPI is implemented For Callback And Blocking interfaces. It supports Shared And
;Exclusive share modes. 
    
;    Exclusive Mode:

;        Exclusive mode allows To deliver audio Data directly To hardware bypassing
;        software mixing.
;        Exclusive mode is specified by 'paWinWasapiExclusive' flag.

;    Callback Interface:

;        Provides best audio quality With low latency. Callback Interface is implemented in 
;        two versions:

;        1) Event-Driven:
;        This is the most powerful WASAPI implementation which is capable To provides
;        glitch-free audio at 2ms latency in Exclusive mode. Lowest possible latency For
;        this mode is usually - 2ms For HD Audio class audio chips (including on-board audio,
;        2ms was achieved on Realtek ALC888/S/T). For Shared mode latency can Not go lower
;        than 20ms.

;        2) Poll-Driven:
;        Polling is another method To operate With WASAPI. It is less efficient than
;        Event-Driven and provides latency at around 12-13ms. Polling must be used To
;        overcome a system bug under Windows Vista x64 when application is WOW64(32-bit)
;        And Event-Driven method simply times out (event handle is never signalled on buffer
;        completion). Please note, such Vista bug does Not exist in Windows 7 x64.
;        Polling is setup by speciying 'paWinWasapiPolling' flag.
;        Thread priority can be boosted by specifying 'paWinWasapiBlockingThreadPriorityPro'
;        flag.

;    Blocking Interface:

;        Blocking Interface is implemented but due To above described Poll-Driven method can
;        Not deliver low latency audio. Specifying too low latency in Shared mode will
;        result in distorted audio although Exclusive mode adds stability.

;    Pa_IsFormatSupported:

;        To check format With correct Share Mode (Exclusive/Shared) you must supply
;        PaWasapiStreamInfo With flags paWinWasapiExclusive set through member of 
;        PaStreamParameters::hostApiSpecificStreamInfo Structure.

;    Pa_OpenStream:

;        To set desired Share Mode (Exclusive/Shared) you must supply
;        PaWasapiStreamInfo With flags paWinWasapiExclusive set through member of 
;        PaStreamParameters::hostApiSpecificStreamInfo Structure.

ImportC "/usr/local/lib/libportaudio.dylib"
  Pa_GetVersion()
  Pa_GetVersionText()
  Pa_GetErrorText(errorCode)
  Pa_Initialize()
  Pa_Terminate()
  Pa_GetHostApiCount()
  Pa_GetDefaultHostApi()
  Pa_GetHostApiInfo(hostApi)
  Pa_HostApiTypeIdToHostApiIndex(type)
  Pa_HostApiDeviceIndexToDeviceIndex(hostApi, hostApiDeviceIndex)
  Pa_GetLastHostErrorInfo()
  Pa_GetDeviceCount()
  Pa_GetDefaultInputDevice()
  Pa_GetDefaultOutputDevice()
  Pa_GetDeviceInfo(device)
  Pa_IsFormatSupported(*inputParameters, *outputParameters, sampleRate.d)
  Pa_OpenStream(*stream.l, *inputParameters, *outputParameters, sampleRate.d, framesPerBuffer, streamFlags, *streamCallback, *user_data)
  Pa_OpenDefaultStream(*stream.l, numInputChannels, numOutputChannels, sampleFormat, sampleRate.d, framesPerBuffer, *streamCallback, *user_data)
  Pa_CloseStream(*stream)
  Pa_SetStreamFinishedCallback(*stream, *streamFinishedCallback)
  Pa_StartStream(*stream)
  Pa_StopStream(*stream)
  Pa_AbortStream(*stream)
  Pa_IsStreamStopped(*stream)
  Pa_IsStreamActive(*stream)
  Pa_GetStreamInfo(*stream)
  Pa_GetStreamTime.d(*stream)
  Pa_GetStreamCpuLoad.d(*stream)
  Pa_ReadStream(*stream, *buffer, frames)
  Pa_WriteStream(*stream, *buffer, frames)
  Pa_GetStreamReadAvailable(*stream)
  Pa_GetStreamWriteAvailable(*stream)
  Pa_GetSampleSize(format)
  Pa_Sleep(msec)
  
  PaWasapi_GetDeviceDefaultFormat(*pFormat, nFormatSize.l, nDevice.l)
  PaWasapi_GetDeviceRole(nDevice.l)
  PaWasapi_ThreadPriorityBoost(*hTask.l, nPriorityClass.l)
  PaWasapi_ThreadPriorityRevert(*hTask.l)

EndImport
Note on line 363: ImportC "/usr/local/lib/libportaudio.dylib". This is the PortAudio library file we just compiled.

The dylib file is a dynamic library roughly equivalent to a dll.

Now here is the code for the simple recorder. Please report here any bugs or issues you may encounter. I leave it to the creative members of this board to implement metering and to snazzy it up:

Code: Select all

;MAC RECORDER DEMO.PB

;UPDATED ON 6/12/10

XIncludeFile "PortAudio.pb"
      
#MENU_MARGIN = 22: #TEXT_Y = 230
Global sampleRate.d = 44100
Global bufferSize = 44100

Global framesPerBuffer, fc, inputbox, outputbox, dBFS.f = 20 * Log10(32767)
Global *recordBuffer, *playBuffer
Global source_device, dest_device
Global in_streamparms.PaStreamParameters
Global out_streamparms.PaStreamParameters
Global *my_stream, file_length, offset, CallbackFlag, *TempBuffer
Global Dim device$(100)

Global scale.f, sample.w, dBFS.f, float_sample.f, min.f, bar_height.l, buf_addr.l
Global window_width.l, window_height.l, bar_y.l, headroom.f, rec_end.l, fullscale.w, File.s

Global chunksize.l, subchunk1id.l, subchunk1size.l, audioformat.w
Global byterate.l, blockalign.w, bitspersample.w, subchunk2size.l, ct.l, tempword.w
Global gain.f, clip_flag.l, max_sample.f, pml.f
Global peak_hold.l, peak_hold_flag.l, peak_hold_level.f, peak_hold_color.l
Global elapsed_seconds.l, remaining_seconds.l
Global hours.s, minutes.s, seconds.s, time_string.s
Global tick1.f, tick2.f, tick3.f, tick4.f
Global green_hold.l, green_hold_flag.l, green_hold_level.f, hottest_green.l, servct = 0

Global QuitRec.l, program_running.l

Global scale.f, sample.w, dBFS.f, float_sample.f, min.f, bar_height.l, buf_addr.l, bytesPerFrame
Global window_width.l, window_height.l, bar_y.l, headroom.f, rec_end.l, fullscale.w, File.s

Global subchunk1id.l, audioformat.w, buffersize, record_minutes.f,avail_time.q, avail_mem.q
Global ct.l, dB, stream_open, old_seconds.l, record_seconds.l, old_dB_left, old_dB_right
Global normalize_flag.l, gain.f, clip_flag.l, max_sample.f, pml.f, buffer_time.d
Global peak_hold.l
Global elapsed_seconds.l, remaining_seconds.l, recording_now, right_offset
Global hours.s, minutes.s, seconds.s, time_string.s, DeviceName.s, stop_button_pressed
Global tick1.f, tick2.f, tick3.f, tick4.f, draw_bkgd.l, leftY, rightY, device_count, device_offset
Global green_hold.l, green_hold_flag.l, green_hold_level.f, hottest_green.l, thread 

Global recordedFrames, format, sampleformat

Global channels.w, bitDepth, SampleRate.d

Dim GUID.c(16)
;Global GUID$ = Chr(1)+Chr(0)+Chr(0)+Chr(0)+Chr(0)+Chr(0)+Chr(16)+Chr(0)+Chr(128)+Chr(0)+Chr(0)+Chr(170)+Chr(0)+Chr(56)+Chr(155)+Chr(113)

Structure WAVEFORMATEX
  wFormatTag.w
  nChannels.w
  nSamplesPerSec.l
  nAvgBytesPerSec.l
  nBlockAlign.w
  wBitsPerSample.w
  cbSize.w
EndStructure

Structure WAVEFORMATEXTENSIBLE
  format.WAVEFORMATEX ; Capturing WaveFormatEx 
  Samples.w
  dwChannelMask.l
  ;SubFormat.GUID
EndStructure

Global my_WFE.WAVEFORMATEXTENSIBLE
;Global my_TimeInfo.PaStreamCallbackTimeInfo

#WAVE_FORMAT_PCM        = $0001 ;PCM <= 16 BITS

#MONO = 1
#STEREO = 2

#SUGGESTED_LATENCY = 0.05

#NUM_API = 15
Dim api$(#NUM_API)

Enumeration 0 ;GADGETS
  #gadStart
  #gadStop
  #gadFile
  #gadChannels
  #gadBitDepth
  #gadSampleRate
  #gadDevice
  #gadRecord
  #gadSave
  #gadHeadroom
  #gadOK
  #gadGreen1
  #gadGreen2
  #gadYellow1
  #gadYellow2
  #gadText1
  #gadText2
  #gadText3
  #gadText4
  #gadText5
EndEnumeration

;==============================================================================

Procedure.s DeviceString(*dev.PaDeviceInfo)
  ProcedureReturn PeekS(*dev\name) + " " ; + Pa_PaHostApiIndexToString(*dev\hostApi)
EndProcedure

Procedure GetDevices()
Global Dim *Devices.PaDeviceInfo(0)

DeviceCount.i
DefaultOutputIndex.i
DefaultInputIndex.i

;Enumerate devices
DeviceCount = Pa_GetDeviceCount()
Global Dim *Devices(DeviceCount)
Global Dim api_source$(DeviceCount)
Global Dim api_dest$(DeviceCount)

For I = 0 To DeviceCount - 1
  *Devices(I) = Pa_GetDeviceInfo(I)
Next

K = 0
For I = 0 To DeviceCount-1
;Add input devices
  If *Devices(I)\maxInputChannels > 0
;    AddGadgetItem(#gadDevice, -1, Str(I) + " " + DeviceString(*Devices(I)))
    AddGadgetItem(#gadDevice, -1, DeviceString(*Devices(I)))
    SetGadgetItemData(#gadDevice, K, I)
    Device$(I) = DeviceString(*Devices(I))
;    If I = DefaultInputIndex
;      SetGadgetState(#gadDevice, K)
;    EndIf
    K + 1
  EndIf
  
Next

EndProcedure  

Procedure GetSettings()
OpenWindow(2, 0, 0, 440, 260, "Recorder Control Panel", #PB_Window_ScreenCentered|#PB_Window_SystemMenu)
ComboBoxGadget(#gadChannels, 20, 50, 85, 20) 
ComboBoxGadget(#gadBitDepth, 115, 50, 90, 20) 
ComboBoxGadget(#gadSampleRate, 215, 50, 110, 20) 
ComboBoxGadget(#gadDevice, 20, 130, 400, 20)
getDevices()  
ComboBoxGadget(#gadHeadroom, 335, 50, 80, 20)
ButtonGadget(#gadOK, 180, 195, 60, 30, "OK", #PB_Button_Default)
TextGadget(#gadText1, 34, 25,85,20, "Channels")
TextGadget(#gadText2, 131, 25,85,20, "Bit Depth")
TextGadget(#gadText3, 230, 25,85,20, "Sample Rate")
TextGadget(#gadText5, 342, 25,85,20, "Headroom")
TextGadget(#gadText4, 194, 105, 75,20, "Device")

  AddGadgetItem(#gadChannels, -1, "Mono")
  AddGadgetItem(#gadChannels, -1, "Stereo")
  SetGadgetState(#gadChannels, 1)
  channels = #STEREO
  
  AddGadgetItem(#gadBitDepth,-1,"16 bits") 
  AddGadgetItem(#gadBitDepth,-1,"24 bits") 
  SetGadgetState(#gadBitDepth, 1)
  bitDepth = 24
  
  AddGadgetItem(#gadSampleRate,-1,"6000 Hz") 
  AddGadgetItem(#gadSampleRate,-1,"7333 Hz") 
  AddGadgetItem(#gadSampleRate,-1,"8000 Hz") 
  AddGadgetItem(#gadSampleRate,-1,"11025 Hz") 
  AddGadgetItem(#gadSampleRate,-1,"12000 Hz") 
  AddGadgetItem(#gadSampleRate,-1,"16000 Hz") 
  AddGadgetItem(#gadSampleRate,-1,"22050 Hz") 
  AddGadgetItem(#gadSampleRate,-1,"24000 Hz") 
  AddGadgetItem(#gadSampleRate,-1,"32000 Hz") 
  AddGadgetItem(#gadSampleRate,-1,"44100 Hz") 
  AddGadgetItem(#gadSampleRate,-1,"48000 Hz") 
  AddGadgetItem(#gadSampleRate,-1,"88200 Hz") 
  AddGadgetItem(#gadSampleRate,-1,"96000 Hz") 
  AddGadgetItem(#gadSampleRate,-1,"192000 Hz") 
  SetGadgetState(#gadSampleRate, 9)
  sampleRate = 44100

SetGadgetState(#gadDevice, 0)

Repeat

Event = WaitWindowEvent()

If Event = #PB_Event_Gadget

Select EventGadget()
      
Case #gadDevice    
  source_device = GetGadgetItemData(#gadDevice, GetGadgetState(#gadDevice))
  
Case #gadSampleRate
  temp = GetGadgetState(#gadSampleRate)
  Select temp 
    Case 0 : samplerate =  6000 
    Case 1 : samplerate =  7333 
    Case 2 : samplerate =  8000 
    Case 3 : samplerate = 11025 
    Case 4 : samplerate = 12000 
    Case 5 : samplerate = 16000 
    Case 6 : samplerate = 22050 
    Case 7 : samplerate = 24000 
    Case 8 : samplerate = 32000 
    Case 9 : samplerate = 44100 
    Case 10 : samplerate = 48000 
    Case 11 : samplerate = 88200 
    Case 12 : samplerate = 96000 
    Case 13 : samplerate = 192000 
  EndSelect 

Case #gadChannels
  temp = GetGadgetState(#gadChannels)
  Select temp 
    Case 0 : channels = #MONO 
    Case 1 : channels = #STEREO
  EndSelect

Case #gadBitDepth
  Select GetGadgetState(#gadBitDepth)
    Case 0 : bitDepth = 16 
    Case 1 : bitDepth = 24 
  EndSelect
  
EndSelect

EndIf

Until Event = #PB_Event_CloseWindow Or EventGadget() = #gadOK

CloseWindow(2)

peak_hold = 0

Global Dim *Devices.PaDeviceInfo(0)
DeviceCount.i
DefaultOutputIndex.i
DefaultInputIndex.i

Select bitDepth
Case 16
  ;Format = #SF_FORMAT_PCM_16
  SampleFormat = #paInt16
Case 24
  ;Format = #SF_FORMAT_PCM_24
  SampleFormat = #paInt24
EndSelect

bytesPerFrame = (bitdepth / 8) * channels
right_offset = bitdepth / 8

in_streamparms\device = source_device ;: Debug "device: " + Str(in_streamparms\device)
in_streamparms\channelCount = channels ;: Debug "channels: " + Str(in_streamparms\channelCount)
in_streamparms\sampleFormat = sampleFormat ;: Debug "sample format: " + Str(in_streamparms\sampleFormat)
in_streamparms\suggestedLatency = #SUGGESTED_LATENCY
in_streamparms\hostApiSpecificStreamInfo = 0

EndProcedure

Procedure FILE_Save()
DisableGadget(#gadRecord, 1)
DisableGadget(#gadStop, 1)
DisableGadget(#gadSave, 1)

file_name$ = SaveFileRequester("Select a file...", ".\", ".wav|*.wav", 0 )
If Right(file_name$,4) <> ".wav": file_name$ = file_name$ + ".wav": EndIf

If FileSize(file_name$) <> -1 
  MessageRequester("Overwrite file?", GetFilePart(file_name$) + " already exists." + Chr(13) + Chr(13) + "Do you want to overwrite this file?", #PB_MessageRequester_YesNoCancel)
EndIf

If CreateFile(2, file_name$) = 0
  ;MessageRequester("Error", "Unable to create file.", #MB_ICONERROR)
  DisableGadget(#gadRecord, 0)
  DisableGadget(#gadSave, 0)
  ProcedureReturn
EndIf

;subchunk1size.l = SizeOf(WAVEFORMATEXTENSIBLE)
subchunk1size.l = SizeOf(WAVEFORMATEX)
subchunk2size.l = recordedFrames * bytesPerFrame
chunksize = 4 + (8 + SizeOf(WAVEFORMATEX)) + (8 + subchunk2size)

samprate.l = samplerate
byterate.l = samprate * BytesPerFrame
blockalign.w = channels * (Abs(bitdepth) / 8)
bitspersample.w = Abs(bitdepth)

;my_WFE\Samples = bitspersample
;my_WFE\format\cbSize = SizeOf(WAVEFORMATEXTENSIBLE) - SizeOf(WAVEFORMATEX)
my_WFE\format\cbSize = 0
chunksize = chunksize + my_WFE\format\cbSize

my_WFE\format\wFormatTag = #WAVE_FORMAT_PCM ;#WAVE_FORMAT_EXTENSIBLE
my_WFE\format\nChannels = channels 
my_WFE\format\nSamplesPerSec = samprate
my_WFE\format\nAvgBytesPerSec = samplerate * BytesPerFrame
my_WFE\format\nBlockAlign = channels * (bitspersample / 8)
my_WFE\format\wBitsPerSample = bitspersample

If channels = 2
  my_WFE\dwChannelMask = 3
Else
  my_WFE\dwChannelMask = 1
EndIf

;WRITE WAV HEADER
WriteString(2, "RIFF") ; 4 bytes
WriteLong(2, chunksize) ; 4 bytes
WriteString(2, "WAVE") ; 4 bytes
WriteString(2, "fmt ") ; 4 bytes
WriteLong(2, subchunk1size) ; 4 bytes

;WriteData(1, my_WFE, SizeOf(WAVEFORMATEXTENSIBLE) - 16)
WriteData(2, my_WFE, SizeOf(WAVEFORMATEX))

;END OF WAVEFORMATEX STRUCTURE

Goto skip_guid

If bitdepth <> -32
  ;WRITE GUID
  WriteByte(1, 1)
  WriteByte(1, 0)
  WriteByte(1, 0)
  WriteByte(1, 0)
  WriteByte(1, 0)
  WriteByte(1, 0)
  WriteByte(1, 16)
  WriteByte(1, 0)
  WriteByte(1, 128)
  WriteByte(1, 0)
  WriteByte(1, 0)
  WriteByte(1, 170)
  WriteByte(1, 0)
  WriteByte(1, 56)
  WriteByte(1, 155)
  WriteByte(1, 113)
EndIf

skip_guid:

WriteString(2, "data", #PB_Ascii) ; 4 bytes
WriteLong(2, subchunk2size) ; 4 bytes
;END OF FILE HEADER

;WRITE AUDIO DATA AFTER WAV HEADER
ReadFile(1, "temp.snd")
;While Not Eof(1)
For ct = 1 To subchunk2size
  WriteWord(2, ReadWord(1))
;Wend
Next
CloseFile(2)
CloseFile(1)

DisableGadget(#gadRecord, 0)
DisableGadget(#gadStop, 1)
DisableGadget(#gadSave, 0)

EndProcedure

ProcedureC PaStreamCallback(*recordBuffer, *playBuffer, frameCount, *timeInfo.PaStreamCallbackTimeInfo, statusFlags, *userdata)
If recording_now <> 0  
  WriteData(1, *recordBuffer, frameCount * bytesPerFrame)
  recordedFrames + frameCount
EndIf

ProcedureReturn #paContinue
EndProcedure

Procedure RECORD_Stop()
Pa_StopStream(*my_stream)
recording_now = 0

DisableGadget(#gadRecord, 0)
DisableGadget(#gadStop, 1)       
DisableGadget(#gadSave, 0)       

CloseFile(1)

EndProcedure

;==============================================================================

Procedure RECORD_Start()
;CREATE TEMPORARY RAW SOUND FILE
file_name$ = "temp.snd"
If CreateFile(1, file_name$) = 0
  MessageRequester("Error", "Unable to create file.")
  End
EndIf
  
DisableGadget(#gadRecord, 1)       
DisableGadget(#gadStop, 0)       
DisableGadget(#gadSave, 1)       

old_seconds = 0
elapsed_seconds = 0
remaining_seconds = buffersize / samplerate
record_seconds = remaining_seconds

recording_now = -1
stop_button_pressed = 0
recordedFrames = 0

EndProcedure

Procedure STREAM_Start()
result = Pa_IsFormatSupported(@in_streamparms, 0, sampleRate)
If result <> paFormatIsSupported
  MessageRequester("Error", "Source format not supported.")
  End
EndIf

If Pa_OpenStream(@*my_stream, @in_streamparms, 0, sampleRate, paFramesPerBufferUnspecified, 0, @PaStreamCallback(), in_streamparms\hostApiSpecificStreamInfo) <> #paNoError
  MessageRequester("Error", "Unable To open stream.")
  End  
EndIf

If Pa_StartStream(*my_stream) <> #paNoError
  MessageRequester("Error", "Unable To start stream.")
  End
EndIf
  
EndProcedure

;***********************************************************************************
;- START OF PROGRAM
;***********************************************************************************

Pa_Initialize()

getSettings()

OpenWindow(1, 0, #MENU_MARGIN, 640, 400, "Recorder")

TextGadget(#gadText1, 50, #TEXT_Y, 320, 20, "Device: " + device$(source_device))
If channels = #MONO: chan$ = "Mono": Else: chan$ = "Stereo": EndIf
TextGadget(#gadText2, 50, #TEXT_Y + 20, 320, 20, "Channels: "+ chan$)
TextGadget(#gadText3, 50, #TEXT_Y + 40, 320, 20, "Bit Depth: " + Str(bitDepth))
TextGadget(#gadText4, 50, #TEXT_Y + 60, 320, 20, "Sample Rate: " + StrF(sampleRate, 0))

ButtonGadget(#gadRecord, 20, 20, 80, 40, "Record")
ButtonGadget(#gadStop, 120, 20, 80, 40, "Stop")
ButtonGadget(#gadSave, 220, 20, 80, 40, "Save")
DisableGadget(#gadStop, 1)
DisableGadget(#gadSave, 1)

STREAM_Start()

Repeat ;MAIN EVENT LOOP
  
event = WindowEvent()

Select event

Case #PB_Event_Gadget
  event_gadget = EventGadget()
  Select event_gadget
      
Case #gadRecord
  RECORD_Start()  
      
Case #gadStop
  RECORD_Stop()
  
Case #gadSave
  FILE_Save()
  
EndSelect ;event gadget

Case #PB_Event_CloseWindow
    
Pa_StopStream(*my_stream)
Pa_CloseStream(*my_stream)
Pa_Terminate()
CloseWindow(1)
End

EndSelect

ForEver
chris319
Enthusiast
Enthusiast
Posts: 782
Joined: Mon Oct 24, 2005 1:05 pm

Re: Mac OS X PortAudio Recorder

Post by chris319 »

NOTE:

If you use this program, please replace WindowEvent() with WaitWindowEvent().
Post Reply