changeset 754:5df644a3b6b8

add: support for loading mono-ogg, change default sample rate to 44100 (audacity default)
author Sam <sam@basx.dev>
date Sat, 24 Jun 2023 21:04:04 +0700
parents eb5ae1f1bc87
children 8817b99ae16e
files src/semicongine/core/audiotypes.nim src/semicongine/resources/audio.nim
diffstat 2 files changed, 13 insertions(+), 6 deletions(-) [+]
line wrap: on
line diff
--- a/src/semicongine/core/audiotypes.nim	Tue Jun 20 00:30:58 2023 +0700
+++ b/src/semicongine/core/audiotypes.nim	Sat Jun 24 21:04:04 2023 +0700
@@ -3,9 +3,9 @@
 # in order to generate sound files that are directly usable with the engine,
 # convert an audio file to a raw PCM signed 16 bit little endian file with 2 channels and 48kHz:
 #
-# ffmpeg -i <infile> -f s16le -ac 2 -ar 48000 -acodec pcm_s16le <outfile>
+# ffmpeg -i <infile> -f s16le -ac 2 -ar 44100 -acodec pcm_s16le <outfile>
 
-const AUDIO_SAMPLE_RATE* = 48000
+const AUDIO_SAMPLE_RATE* = 44100
 
 type
   Level* = 0'f .. 1'f
--- a/src/semicongine/resources/audio.nim	Tue Jun 20 00:30:58 2023 +0700
+++ b/src/semicongine/resources/audio.nim	Sat Jun 24 21:04:04 2023 +0700
@@ -79,10 +79,17 @@
     raise newException(Exception, &"Unable to read ogg/vorbis sound file, error code: {nSamples}")
   if sampleRate != AUDIO_SAMPLE_RATE:
     raise newException(Exception, &"Only support sample rate of {AUDIO_SAMPLE_RATE} Hz but got {sampleRate} Hz, please resample (e.g. ffmpeg -i <infile> -acodec libvorbis -ar {AUDIO_SAMPLE_RATE} <outfile>)")
-  if channels != 2:
-    raise newException(Exception, &"Currently only support 2 channels, but ogg/ vorbis file had {channels}")
 
   result = new Sound
   result[].setLen(int(nSamples))
-  copyMem(addr result[][0], output, nSamples * sizeof(Sample))
-  free(output)
+  if channels == 2:
+    copyMem(addr result[][0], output, nSamples * sizeof(Sample))
+    free(output)
+  elif channels == 1:
+    for i in 0 ..< nSamples:
+      let value = cast[ptr UncheckedArray[int16]](output)[i]
+      result[].add [value, value]
+    free(output)
+  else:
+    free(output)
+    raise newException(Exception, "Only support mono and stereo audio at the moment (1 or 2 channels), but found " & $channels)