_SNDNEW

From QB64 Phoenix Edition Wiki
Revision as of 21:30, 7 January 2023 by A740g (talk | contribs)
Jump to navigation Jump to search

The _SNDNEW function creates a raw empty sound in memory and returns a LONG handle value above 0. The sound's raw memory can then be accessed using _MEMSOUND, _MEMGET (function) & _MEMPUT.


Syntax

soundHandle& = _SNDNEW(frames&, channels&, bits&)


Parameters

  • frames& is the number of sample frames needed.
  • channels& is the number of channels needed (1 = mono, 2 = stereo).
  • bits& is the number of bits per channel (8 = 8-bit unsigned integer, 16 = 16-bit signed integer, 32 = 32-bit floating point).


Description

  • Use the function to create a raw sound in memory.
  • Once the sound is created, it can then be accessed using _MEMSOUND, _MEMGET (function) & _MEMPUT.
  • Using this one can generate sounds once programmatically and play it multiple times.
  • The sound memory can also be filled with sample data from other sources like files, DATA statements and more!
  • Sound handle values and the memory used must be freed using _SNDCLOSE when no longer required.
  • A sample rate (_SNDRATE) of 48000 means 48000 sample frames / second.
  • 1 sample frame = 1 sample x number of channels.


Availability

  • QBPE 3.5 and up (QB64 Phoenix Edition)


Examples

Example 1: Creating a sound at runtime and playing it.

$CONSOLE
OPTION _EXPLICIT
OPTION _EXPLICITARRAY

RANDOMIZE TIMER

CONST SOUND_DURATION = 5 ' duration is seconds
CONST SAMPLE_CHANNELS = 1 ' number of channes. For stereo we need to add another _MEMPUT below and +offset by SAMPLE_BYTES
CONST SAMPLE_BYTES = 4 ' number of bytes / sample (not frame!)

DIM h AS LONG: h = _SNDNEW(SOUND_DURATION * _SNDRATE, SAMPLE_CHANNELS, SAMPLE_BYTES * 8)
IF (h < 1) THEN
    PRINT "Failed to create sound!"
    END
END IF

DIM sndblk AS _MEM: sndblk = _MEMSOUND(h, 0)
IF sndblk.SIZE = 0 THEN
    _SNDCLOSE h
    PRINT "Failed to access sound data!"
    END
END IF

DIM t AS _INTEGER64
FOR t = 0 TO (SOUND_DURATION * _SNDRATE) - 1
    _MEMPUT sndblk, sndblk.OFFSET + (t * SAMPLE_BYTES * SAMPLE_CHANNELS), SIN(2 * _PI * 440 * t / _SNDRATE) + RND - RND AS SINGLE ' mixes noise and a sine wave
NEXT

_SNDPLAY h

SLEEP SOUND_DURATION

_SNDCLOSE h

END


See also


Navigation:
Main Page with Articles and Tutorials
Keyword Reference - Alphabetical
Keyword Reference - By usage
Report a broken link