PortAudio for PB

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

Re: PortAudio for PB

Post by chris319 »

Please see the final post in this thread for the latest version of portaudio.pb.
Last edited by chris319 on Sun Jun 18, 2017 7:04 am, edited 3 times in total.
chris319
Enthusiast
Enthusiast
Posts: 782
Joined: Mon Oct 24, 2005 1:05 pm

Re: PortAudio for PB

Post by chris319 »

Here is yet another update of portaudio.pb.
Tested with PureBasic 5.44 LTS (x86) under Windows 10

Code: Select all

;PortAudio.pb
;XIncludeFile for PureBasic version of PortAudio

;Updated for pa_stable_v190600_20161030 (October 30, 2016)
;Updated on 6/19/2017

;https://msdn.microsoft.com/en-us/library/windows/desktop/ms685100(v=vs.85).aspx


;  * $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.s
  deviceCount.l
  defaultInputDevice.l
  defaultOutputDevice.l
EndStructure

Structure PaHostErrorInfo
  hostApiType.l   
  errorCode.l            
  errorText.s
EndStructure

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

Structure PaStreamParameters ;line 538 in portaudio.h
device.l ; 4 bytes
channelCount.l ; 4 bytes
sampleFormat.l ; 4 bytes
suggestedLatency.d ; 8 bytes
;pad1.l
*hostApiSpecificStreamInfo
;pad2.l
;PORTAUDIO ***MUST*** BE COMPILED WITH STRUCTURE ALIGNMENT = 4
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.l, *timeInfo, statusFlags, *userdata)
PrototypeC PaStreamFinishedCallback(*user_data)

;Setup flags
#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
#paWinWasapiThreadPriority           = 1 << 4 ;forces custom thread priority setting.

;Data Read/write Note: WASAPI Event driven core is capable of 2ms latency, but Polling method
;can only provide 15-20ms latency.
;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)

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

;Jack connection type
;PaWasapiJackConnectionType.l ;???
Enumeration PaWasapiJackConnectionType
#eJackConnTypeUnknown
#eJackConnType3Point5mm
#eJackConnTypeQuarter
#eJackConnTypeAtapiInternal
#eJackConnTypeRCA
#eJackConnTypeOptical
#eJackConnTypeOtherDigital
#eJackConnTypeOtherAnalog
#eJackConnTypeMultichannelAnalogDIN
#eJackConnTypeXlrProfessional
#eJackConnTypeRJ11Modem
#eJackConnTypeCombination
EndEnumeration

;Jack geometric location
;PaWasapiJackGeoLocation.l ;???
Enumeration PaWasapiJackGeoLocation
#eJackGeoLocUnk = 0
#eJackGeoLocRear = 1 ;matches EPcxGeoLocation::eGeoLocRear */
#eJackGeoLocFront
#eJackGeoLocLeft
#eJackGeoLocRight
#eJackGeoLocTop
#eJackGeoLocBottom
#eJackGeoLocRearPanel
#eJackGeoLocRiser
#eJackGeoLocInsideMobileLid
#eJackGeoLocDrivebay
#eJackGeoLocHDMI
#eJackGeoLocOutsideMobileLid
#eJackGeoLocATAPI
#eJackGeoLocReserved5
#eJackGeoLocReserved6
EndEnumeration

;Jack general location
;PaWasapiJackGenLocation.l ;???
Enumeration PaWasapiJackGenLocation
#eJackGenLocPrimaryBox = 0
#eJackGenLocInternal
#eJackGenLocSeparate
#eJackGenLocOther
EndEnumeration

;Jack type of port
;PaWasapiJackPortConnection.l ;???
Enumeration PaWasapiJackPortConnection
#eJackPortConnJack = 0
#eJackPortConnIntegratedDevice
#eJackPortConnBothIntegratedAndJack
#eJackPortConnUnknown
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 ;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
streamCategory.l
streamOption.l
EndStructure ;End of Structure PaWasapiStreamInfo

Enumeration PaWasapiStreamCategory
#eAudioCategoryOther           = 0
#eAudioCategoryCommunications  = 3
#eAudioCategoryAlerts          = 4
#eAudioCategorySoundEffects    = 5
#eAudioCategoryGameEffects     = 6
#eAudioCategoryGameMedia       = 7
#eAudioCategoryGameChat        = 8
#eAudioCategorySpeech          = 9
#eAudioCategoryMovie           = 10
#eAudioCategoryMedia           = 11
EndEnumeration

Enumeration ;PaWasapiStreamOption
#eStreamOptionNone        = 0 ;default
#eStreamOptionRaw         = 1 ;bypass WASAPI Audio Engine DSP effects, supported since Windows 8.1
#eStreamOptionMatchFormat = 2 ;force WASAPI Audio Engine into a stream format, supported since Windows 10
EndEnumeration

;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 );
;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 provide
;        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.



;Added fields
;PaWasapiDeviceRole.l ;???
;PaWasapiJackConnectionType.l ;???
;PaWasapiJackGeoLocation.l ;???
;PaWasapiJackGenLocation.l ;???
;PaWasapiJackPortConnection.l ;???

;Stream descriptor
Structure PaWasapiJackDescription
channelMapping.l
color.l ;derived from macro: #define RGB(r,g,b) ((COLORREF)(((BYTE)(r)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(b))<<16))) */
connectionType.l
geoLocation.l
genLocation.l
portConnection.l
isConnected.l
EndStructure

ImportC "portaudio_x86.lib"
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, *inputParameters, *outputParameters, sampleRate.d, framesPerBuffer, streamFlags, *streamCallback, *user_data)
Pa_OpenDefaultStream(*stream, 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, nPriorityClass.l)
PaWasapi_ThreadPriorityRevert(*hTask)
PaWasapi_GetFramesPerHostBuffer(*pStream, *nInput, *nOutput)
PaWasapi_GetJackCount(nDevice.l, *jcount);
PaWasapi_GetJackDescription(nDevice.l, jindex.l, *pJackDescription)

EndImport
SeregaZ
Enthusiast
Enthusiast
Posts: 628
Joined: Fri Feb 20, 2009 9:24 am
Location: Almaty (Kazakhstan. not Borat, but Triple G)
Contact:

Re: PortAudio for PB

Post by SeregaZ »

i have some problem with format audio. how to know sure what it is? i am unpack Mortal Combat 3 for sega mega drive and it have some samples. most of samples for GEMS audio driver is wav PCM mono 8bit 5200kbs (lowest) to 10400 (higher). but this MK3 have something other. i know GEMS can have 4bit, and i try to test it - no sound at all. and i try to import it into another sound editors - they all have 8bit as minimem - no one have 4bit, or even 1bit. i try to use sndPlaySound_ winaoi, but no result.

88 is most format. A8 only once, B8 probably damaged sample, becouse it have more 65k samples size. it cant be. and marker of size is FIRST =$04AF, but it must be FIRST =$FFFF for this 65k case.

now i am start think it is wrong unpack software...
Last edited by SeregaZ on Sat Jul 01, 2017 11:10 pm, edited 1 time in total.
wilbert
PureBasic Expert
PureBasic Expert
Posts: 3942
Joined: Sun Aug 08, 2004 5:21 am
Location: Netherlands

Re: PortAudio for PB

Post by wilbert »

4 bit is probably ADPCM which is a delta encoding.
I suppose you have to convert it to PCM yourself.
Windows (x64)
Raspberry Pi OS (Arm64)
SeregaZ
Enthusiast
Enthusiast
Posts: 628
Joined: Fri Feb 20, 2009 9:24 am
Location: Almaty (Kazakhstan. not Borat, but Triple G)
Contact:

Re: PortAudio for PB

Post by SeregaZ »

if i know wich programm can import this without head file :) CoolEdit2 want import as PCM.
wilbert
PureBasic Expert
PureBasic Expert
Posts: 3942
Joined: Sun Aug 08, 2004 5:21 am
Location: Netherlands

Re: PortAudio for PB

Post by wilbert »

SeregaZ wrote:if i know wich programm can import this without head file :) CoolEdit2 want import as PCM.
I haven't tried but when I googled, the these two came up.
http://sox.sourceforge.net/sox.html
http://www.wave-editor.com
Maybe one of them works for you.
Windows (x64)
Raspberry Pi OS (Arm64)
SeregaZ
Enthusiast
Enthusiast
Posts: 628
Joined: Fri Feb 20, 2009 9:24 am
Location: Almaty (Kazakhstan. not Borat, but Triple G)
Contact:

Re: PortAudio for PB

Post by SeregaZ »

sox convert with gaps. will try second one.
SeregaZ
Enthusiast
Enthusiast
Posts: 628
Joined: Fri Feb 20, 2009 9:24 am
Location: Almaty (Kazakhstan. not Borat, but Triple G)
Contact:

Re: PortAudio for PB

Post by SeregaZ »

now i have answer :)))
2017-07-02 00:01:13 ValleyBell in GEMS, 4-bit samples are 1 sample per nibble (hex-digit)
2017-07-02 00:01:33 ValleyBell the low nibble is played first, then the high nibble is played
2017-07-02 00:01:42 ValleyBell then the next byte is processed
2017-07-02 00:02:31 SeregaZ it is not ADPCM? sox.exe is convert DAC bank with gaps.
2017-07-02 00:02:42 ValleyBell not ADPCM - uncompressed PCM
2017-07-02 00:02:45 ValleyBell but 4 bits
2017-07-02 00:03:30 ValleyBell You can convert 4 bit -> 8 bit by multiplying the sample with 0x10.
2017-07-02 00:05:15 SeregaZ so for example first byte is 240 1111 0000.
2017-07-02 00:05:53 anosci hey valleybell do you have some notes on how each of the files from ripped GEMS games is stored?
2017-07-02 00:05:59 SeregaZ i need to take %0000 * 16 and take it as 1 byte for new file, then %1111 * 16 = 2 byte?
2017-07-02 00:06:27 ValleyBell yes
will try this way.
SeregaZ
Enthusiast
Enthusiast
Posts: 628
Joined: Fri Feb 20, 2009 9:24 am
Location: Almaty (Kazakhstan. not Borat, but Triple G)
Contact:

Re: PortAudio for PB

Post by SeregaZ »

no gaps, but too many hiss.
chris319
Enthusiast
Enthusiast
Posts: 782
Joined: Mon Oct 24, 2005 1:05 pm

Re: PortAudio for PB

Post by chris319 »

PortAudio does not support 4-bit audio.

Audio bit depths start at 8 but the quality is poor.

16 bits is quite listenable. Some people prefer 24 bits and some applications use 32-bit floats.
SeregaZ
Enthusiast
Enthusiast
Posts: 628
Joined: Fri Feb 20, 2009 9:24 am
Location: Almaty (Kazakhstan. not Borat, but Triple G)
Contact:

Re: PortAudio for PB

Post by SeregaZ »

that is why i try to convert it for my player. but no success... i think i get wrong type of variables. some byte is negative, right? but my case - all values is positive...

samples pack all in one file: https://www.dropbox.com/s/io7cwsptj7q9h ... s.bin?dl=1 i think old one was too short.

convert code is:

Code: Select all

;{
Macro SetBit(Var, Bit)
  Var | (Bit)
EndMacro 
Macro ClearBit(Var, Bit)
  Var & (~(Bit))
EndMacro 
Macro TestBit(Var, Bit)
  Bool(Var & (Bit))
EndMacro
Macro NumToBit(Num) 
  (1<<(Num))
EndMacro
Macro GetBits(Var, StartPos, EndPos)
  ((Var>>(StartPos))&(NumToBit((EndPos)-(StartPos)+1)-1))
EndMacro
;}

Procedure WavHeaderCreation(*memst)
  
 ;RIFF
 PokeB(*memst, $52):PokeB(*memst+1, $49):PokeB(*memst+2,$46):PokeB(*memst+3, $46)
    
 ;WAVE
 PokeB(*memst+8, $57):PokeB(*memst+9, $41):PokeB(*memst+10,$56):PokeB(*memst+11, $45)
    
 ;fmt
 PokeB(*memst+12, $66):PokeB(*memst+13, $6d):PokeB(*memst+14,$74):PokeB(*memst+15, $20) 
    
 ;header size
 PokeB(*memst+16, $10)
    
 ;PCM 01
 PokeB(*memst+20, $01)
    
 ;mono stereo
 PokeB(*memst+22, $01)
    
 ;1
 PokeB(*memst+32, $01)
    
 ;bit
 PokeB(*memst+34, $08)
        
 ;data    
 PokeB(*memst+36, $64)
 PokeB(*memst+37, $61)
 PokeB(*memst+38, $74)
 PokeB(*memst+39, $61)
  
EndProcedure

inpval.b

If ReadFile(0, "D:\Samples.bin")
  length = Lof(0)
  *sndsource = AllocateMemory(length)
  If *sndsource
    ReadData(0, *sndsource, length)
  EndIf
  CloseFile(0)
EndIf

If *sndsource
  *snddest = AllocateMemory(length*2+44)
  If *snddest
    WavHeaderCreation(*snddest)
    
    ;size
    PokeL(*snddest +  4, length*2+40)
    PokeL(*snddest + 40, length*2)
    ;kbs
    PokeL(*snddest + 24, 6500)
    PokeL(*snddest + 28, 6500)
    
    For i = 0 To length
      inpval = PeekB(*sndsource+i)
      
      first  = GetBits(inpval, 0, 3)
      second = GetBits(inpval, 4, 7)

      PokeB(*snddest+44+(i*2), first  * 16)
      PokeB(*snddest+45+(i*2), second * 16)
    Next
    
  EndIf
EndIf


;sndPlaySound_(*snddest,#SND_MEMORY | #SND_ASYNC | #SND_NODEFAULT)

;Delay(5000)

If CreateFile(0, "D:\demo.wav")
  WriteData(0, *snddest, length*2+44)
  CloseFile(0)
EndIf

  
please help to set correct variables, becouse final result have all positive values. i think it is a little wrong.
wilbert
PureBasic Expert
PureBasic Expert
Posts: 3942
Joined: Sun Aug 08, 2004 5:21 am
Location: Netherlands

Re: PortAudio for PB

Post by wilbert »

SeregaZ wrote:please help to set correct variables, becouse final result have all positive values. i think it is a little wrong.
You can try PeekA to get the input value instead of PeekB.

Here's also a small procedure to convert a buffer.

Code: Select all

Procedure PCM4to8(*src.Ascii, *dst.Ascii, cnt)
  Protected Dim vt.a(15)
  PokeQ(@vt(0),$261e18130f0c0a00)
  PokeQ(@vt(8),$f2c09979604d3d30)
  While cnt
    *dst\a = vt(*src\a&$f) : *dst+1
    *dst\a = vt(*src\a>>4) : *dst+1
    *src + 1 : cnt - 1
  Wend
EndProcedure
The first argument is the source buffer, the second one the destination buffer and the third one the number of bytes from the source buffer to convert.

With this procedure, the last part of your code would have to be changed to

Code: Select all

If *sndsource
  *snddest = AllocateMemory(length*2+44)
  If *snddest
    WavHeaderCreation(*snddest)
    
    ;size
    PokeL(*snddest +  4, length*2+40)
    PokeL(*snddest + 40, length*2)
    ;kbs
    PokeL(*snddest + 24, 6500)
    PokeL(*snddest + 28, 6500)
    
    PCM4to8(*sndsource, *snddest+44, length)
    
  EndIf
EndIf
Windows (x64)
Raspberry Pi OS (Arm64)
SeregaZ
Enthusiast
Enthusiast
Posts: 628
Joined: Fri Feb 20, 2009 9:24 am
Location: Almaty (Kazakhstan. not Borat, but Triple G)
Contact:

Re: PortAudio for PB

Post by SeregaZ »

thanks. but still a lot of hiss. console play it with clear sound. maybe i am create wrong header? it must be PCM, 8bit, 6500kbs or not kbs but frequency. i am still didnt see difference between this frequency and kbs. it sets by 2 different values in a header:

Code: Select all

PokeL(*snddest + 24, 6500)
PokeL(*snddest + 28, 6500)
wilbert
PureBasic Expert
PureBasic Expert
Posts: 3942
Joined: Sun Aug 08, 2004 5:21 am
Location: Netherlands

Re: PortAudio for PB

Post by wilbert »

SeregaZ wrote:thanks. but still a lot of hiss. console play it with clear sound.
Did you try the procedure I posted ?
Your own code assumes linear PCM while in reality the 4 bit PCM data doesn't seem to be linear.
The procedure I posted uses a lookup table.
Windows (x64)
Raspberry Pi OS (Arm64)
SeregaZ
Enthusiast
Enthusiast
Posts: 628
Joined: Fri Feb 20, 2009 9:24 am
Location: Almaty (Kazakhstan. not Borat, but Triple G)
Contact:

Re: PortAudio for PB

Post by SeregaZ »

yes. your code sounds better, but anyway have hiss.
Post Reply