WavSource.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. ###########################################
  2. # Project: CMSIS DSP Library
  3. # Title: WavSource.py
  4. # Description: Source node for reading wave files
  5. #
  6. # $Date: 06 August 2021
  7. # $Revision: V1.10.0
  8. #
  9. # Target Processor: Cortex-M and Cortex-A cores
  10. # -------------------------------------------------------------------- */
  11. #
  12. # Copyright (C) 2010-2021 ARM Limited or its affiliates. All rights reserved.
  13. #
  14. # SPDX-License-Identifier: Apache-2.0
  15. #
  16. # Licensed under the Apache License, Version 2.0 (the License); you may
  17. # not use this file except in compliance with the License.
  18. # You may obtain a copy of the License at
  19. #
  20. # www.apache.org/licenses/LICENSE-2.0
  21. #
  22. # Unless required by applicable law or agreed to in writing, software
  23. # distributed under the License is distributed on an AS IS BASIS, WITHOUT
  24. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25. # See the License for the specific language governing permissions and
  26. # limitations under the License.
  27. ############################################
  28. from ..simu import *
  29. import wave
  30. # It is assuming the input is a stereo file
  31. # It is not yet customizable in this version
  32. # Pad with zero when end of file is reached
  33. class WavSource(GenericSource):
  34. "Read a stereo wav with 16 bits encoding"
  35. def __init__(self,outputSize,fifoout,stereo,name):
  36. GenericSource.__init__(self,outputSize,fifoout)
  37. self._file=wave.open(name, 'rb')
  38. self._stereo=stereo
  39. #print(self._file.getnchannels())
  40. #print(self._file.getnframes())
  41. def run(self):
  42. a=self.getWriteBuffer()
  43. if self._stereo:
  44. # Stereo file so chunk must be divided by 2
  45. frame=np.frombuffer(self._file.readframes(self._outputSize//2),dtype=np.int16)
  46. else:
  47. frame=np.frombuffer(self._file.readframes(self._outputSize),dtype=np.int16)
  48. if frame.size > 0:
  49. a[:frame.size] = frame
  50. a[frame.size:] = 0
  51. return(0)
  52. else:
  53. a[:]=0
  54. return(0)
  55. def __del__(self):
  56. self._file.close()