test_ossaudiodev.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. from test import support
  2. from test.support import import_helper, warnings_helper
  3. import warnings
  4. support.requires('audio')
  5. from test.support import findfile
  6. with warnings.catch_warnings():
  7. warnings.simplefilter("ignore", DeprecationWarning)
  8. ossaudiodev = import_helper.import_module('ossaudiodev')
  9. audioop = warnings_helper.import_deprecated('audioop')
  10. sunau = warnings_helper.import_deprecated('sunau')
  11. import errno
  12. import sys
  13. import time
  14. import unittest
  15. # Arggh, AFMT_S16_NE not defined on all platforms -- seems to be a
  16. # fairly recent addition to OSS.
  17. try:
  18. from ossaudiodev import AFMT_S16_NE
  19. except ImportError:
  20. if sys.byteorder == "little":
  21. AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
  22. else:
  23. AFMT_S16_NE = ossaudiodev.AFMT_S16_BE
  24. def read_sound_file(path):
  25. with open(path, 'rb') as fp:
  26. au = sunau.open(fp)
  27. rate = au.getframerate()
  28. nchannels = au.getnchannels()
  29. encoding = au._encoding
  30. fp.seek(0)
  31. data = fp.read()
  32. if encoding != sunau.AUDIO_FILE_ENCODING_MULAW_8:
  33. raise RuntimeError("Expect .au file with 8-bit mu-law samples")
  34. # Convert the data to 16-bit signed.
  35. data = audioop.ulaw2lin(data, 2)
  36. return (data, rate, 16, nchannels)
  37. class OSSAudioDevTests(unittest.TestCase):
  38. def play_sound_file(self, data, rate, ssize, nchannels):
  39. try:
  40. dsp = ossaudiodev.open('w')
  41. except OSError as msg:
  42. if msg.args[0] in (errno.EACCES, errno.ENOENT,
  43. errno.ENODEV, errno.EBUSY):
  44. raise unittest.SkipTest(msg)
  45. raise
  46. # at least check that these methods can be invoked
  47. dsp.bufsize()
  48. dsp.obufcount()
  49. dsp.obuffree()
  50. dsp.getptr()
  51. dsp.fileno()
  52. # Make sure the read-only attributes work.
  53. self.assertFalse(dsp.closed)
  54. self.assertEqual(dsp.name, "/dev/dsp")
  55. self.assertEqual(dsp.mode, "w", "bad dsp.mode: %r" % dsp.mode)
  56. # And make sure they're really read-only.
  57. for attr in ('closed', 'name', 'mode'):
  58. try:
  59. setattr(dsp, attr, 42)
  60. except (TypeError, AttributeError):
  61. pass
  62. else:
  63. self.fail("dsp.%s not read-only" % attr)
  64. # Compute expected running time of sound sample (in seconds).
  65. expected_time = float(len(data)) / (ssize/8) / nchannels / rate
  66. # set parameters based on .au file headers
  67. dsp.setparameters(AFMT_S16_NE, nchannels, rate)
  68. self.assertTrue(abs(expected_time - 3.51) < 1e-2, expected_time)
  69. t1 = time.monotonic()
  70. dsp.write(data)
  71. dsp.close()
  72. t2 = time.monotonic()
  73. elapsed_time = t2 - t1
  74. percent_diff = (abs(elapsed_time - expected_time) / expected_time) * 100
  75. self.assertTrue(percent_diff <= 10.0,
  76. "elapsed time (%s) > 10%% off of expected time (%s)" %
  77. (elapsed_time, expected_time))
  78. def set_parameters(self, dsp):
  79. # Two configurations for testing:
  80. # config1 (8-bit, mono, 8 kHz) should work on even the most
  81. # ancient and crufty sound card, but maybe not on special-
  82. # purpose high-end hardware
  83. # config2 (16-bit, stereo, 44.1kHz) should work on all but the
  84. # most ancient and crufty hardware
  85. config1 = (ossaudiodev.AFMT_U8, 1, 8000)
  86. config2 = (AFMT_S16_NE, 2, 44100)
  87. for config in [config1, config2]:
  88. (fmt, channels, rate) = config
  89. if (dsp.setfmt(fmt) == fmt and
  90. dsp.channels(channels) == channels and
  91. dsp.speed(rate) == rate):
  92. break
  93. else:
  94. raise RuntimeError("unable to set audio sampling parameters: "
  95. "you must have really weird audio hardware")
  96. # setparameters() should be able to set this configuration in
  97. # either strict or non-strict mode.
  98. result = dsp.setparameters(fmt, channels, rate, False)
  99. self.assertEqual(result, (fmt, channels, rate),
  100. "setparameters%r: returned %r" % (config, result))
  101. result = dsp.setparameters(fmt, channels, rate, True)
  102. self.assertEqual(result, (fmt, channels, rate),
  103. "setparameters%r: returned %r" % (config, result))
  104. def set_bad_parameters(self, dsp):
  105. # Now try some configurations that are presumably bogus: eg. 300
  106. # channels currently exceeds even Hollywood's ambitions, and
  107. # negative sampling rate is utter nonsense. setparameters() should
  108. # accept these in non-strict mode, returning something other than
  109. # was requested, but should barf in strict mode.
  110. fmt = AFMT_S16_NE
  111. rate = 44100
  112. channels = 2
  113. for config in [(fmt, 300, rate), # ridiculous nchannels
  114. (fmt, -5, rate), # impossible nchannels
  115. (fmt, channels, -50), # impossible rate
  116. ]:
  117. (fmt, channels, rate) = config
  118. result = dsp.setparameters(fmt, channels, rate, False)
  119. self.assertNotEqual(result, config,
  120. "unexpectedly got requested configuration")
  121. try:
  122. result = dsp.setparameters(fmt, channels, rate, True)
  123. except ossaudiodev.OSSAudioError as err:
  124. pass
  125. else:
  126. self.fail("expected OSSAudioError")
  127. def test_playback(self):
  128. sound_info = read_sound_file(findfile('audiotest.au'))
  129. self.play_sound_file(*sound_info)
  130. def test_set_parameters(self):
  131. dsp = ossaudiodev.open("w")
  132. try:
  133. self.set_parameters(dsp)
  134. # Disabled because it fails under Linux 2.6 with ALSA's OSS
  135. # emulation layer.
  136. #self.set_bad_parameters(dsp)
  137. finally:
  138. dsp.close()
  139. self.assertTrue(dsp.closed)
  140. def test_mixer_methods(self):
  141. # Issue #8139: ossaudiodev didn't initialize its types properly,
  142. # therefore some methods were unavailable.
  143. with ossaudiodev.openmixer() as mixer:
  144. self.assertGreaterEqual(mixer.fileno(), 0)
  145. def test_with(self):
  146. with ossaudiodev.open('w') as dsp:
  147. pass
  148. self.assertTrue(dsp.closed)
  149. def test_on_closed(self):
  150. dsp = ossaudiodev.open('w')
  151. dsp.close()
  152. self.assertRaises(ValueError, dsp.fileno)
  153. self.assertRaises(ValueError, dsp.read, 1)
  154. self.assertRaises(ValueError, dsp.write, b'x')
  155. self.assertRaises(ValueError, dsp.writeall, b'x')
  156. self.assertRaises(ValueError, dsp.bufsize)
  157. self.assertRaises(ValueError, dsp.obufcount)
  158. self.assertRaises(ValueError, dsp.obufcount)
  159. self.assertRaises(ValueError, dsp.obuffree)
  160. self.assertRaises(ValueError, dsp.getptr)
  161. mixer = ossaudiodev.openmixer()
  162. mixer.close()
  163. self.assertRaises(ValueError, mixer.fileno)
  164. def setUpModule():
  165. try:
  166. dsp = ossaudiodev.open('w')
  167. except (ossaudiodev.error, OSError) as msg:
  168. if msg.args[0] in (errno.EACCES, errno.ENOENT,
  169. errno.ENODEV, errno.EBUSY):
  170. raise unittest.SkipTest(msg)
  171. raise
  172. dsp.close()
  173. if __name__ == "__main__":
  174. unittest.main()