test.py 2.5 KB
Newer Older
André Anjos's avatar
André Anjos committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.anjos@idiap.ch>
# Elie Khoury < elie.khoury@idiap.ch>
# Wed 20 Jan 2016 14:35:05 CET
#
# Copyright (C) 2011-2016 Idiap Research Institute, Martigny, Switzerland


"""Tests audio reader and writer based on sox for bob and python
"""

import os, sys
import unittest
import scipy.io.wavfile
import numpy
import pkg_resources
import .
from ._ext import reader

def F(name, f):
  """Returns the test file on the "data" subdirectory"""
  return pkg_resources.resource_filename(name, os.path.join('data', f))


class SoxTest(unittest.TestCase):
  """Performs various tests on audio reading and writing using sox for bob and python"""

  def run_for(self, sample, extension):

    # audio file name
    infile = F(__name__, '%s%s' % (sample, extension))

    # reading the file using xbob.sox
    sox_audio = reader(infile)
    (sox_rate, sox_data) = sox_audio.load()

    # reading the file using scipy.io.wavfile
    (scipy_rate, scipy_data)=scipy.io.wavfile.read(infile)

    # verify if the rates are the same
    self.assertTrue(numpy.equal(int(sox_rate), scipy_rate))

    # If one channel
    if sox_data.shape[0] == 1:
      # verify if the data are the same (x 2^15)
      sox_data_ =  sox_data[0] * pow(2,15)
      sox_data_.astype(int)
      self.assertTrue(numpy.array_equal(sox_data_, scipy_data))

    #If more than one channel
    elif sox_data.shape[0] > 1:
      # verify if the nchannels are the same
      self.assertTrue(numpy.equal(sox_data.shape[0], scipy_data.shape[1]))

      # verify if the data are the same (x 2^15)
      for i in range(0, sox_data.shape[0]):
        sox_data_ =  sox_data[i] * pow(2,15)
        sox_data_.astype(int)
        scipy_data_ = scipy_data[:,i]
        self.assertTrue(numpy.array_equal(sox_data_, scipy_data_))



  # compare mono: ours vs scipy.io.wavfile
  def test01_read_mono_wav(self):
    self.run_for('sample1', '.wav')


  # compare stereo: ours vs scipy.io.wavfile
  def test02_read_stereo_wav(self):
    self.run_for('sample4', '.wav')



  # compare mono: ours vs matlab
  def test03_read_mono_wav(self):

    # audio file name
    infile = F(__name__, 'sample3.wav')

    # reading the file using xbob.sox
    sox_audio = reader(infile)
    (sox_rate, sox_data) = sox_audio.load()

    # reading the .mat file that contains the data generated by the Matlab wavread function
    mat_data = bob.io.load(F(__name__, 'sample3.mat'))
    self.assertTrue(numpy.array_equal(sox_data, mat_data))

 # TODO: could add test for writing