changeset 117:6c81dac04c03

Add _mix_audio_channels function
author Amine Sehili <amine.sehili@gmail.com>
date Thu, 31 Jan 2019 21:12:09 +0100
parents 97be2ee272b2
children 1af0c6050073
files auditok/io.py
diffstat 1 files changed, 17 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/auditok/io.py	Wed Jan 30 20:24:45 2019 +0100
+++ b/auditok/io.py	Thu Jan 31 21:12:09 2019 +0100
@@ -27,6 +27,7 @@
 import os
 import sys
 import wave
+import audioop
 from array import array
 
 if sys.version_info >= (3, 0):
@@ -166,6 +167,22 @@
         return a.tostring()
 
 
+def _mix_audio_channels(data, channels, sample_width):
+    if channels == 1:
+        return data
+    if channels == 2:
+        return audioop.tomono(data, sample_width, 0.5, 0.5)
+    fmt = DATA_FORMAT[sample_width]
+    buffer = array(fmt, data)
+    mono_channels = [
+        array(fmt, buffer[ch::channels]) for ch in range(channels)
+    ]
+    avg_arr = array(
+        fmt, (sum(samples) // channels for samples in zip(*mono_channels))
+    )
+    return _array_to_bytes(avg_arr)
+
+
 def _extract_selected_channel(data, channels, sample_width, use_channel):
     if use_channel == "mix":
         return _mix_audio_channels(data, channels, sample_width)