1 Reply Latest reply on Jan 25, 2017 1:27 AM by clem57

    Error Playback wav file in python script

    register25

      Hey all, I am facing a problem playing back wav/audio files in python on my raspberry pi + cirrus logic audio card setup. The file being played back is always buzzing and full of distortion. This problem is only faced when I ran the playback script on python, and the playback is normal using aplay-. Can anyone advice me on this?

       

      Below is the playback python code. Please help me to see if everything is fine. Thanks.

       

      def playAudio():

       

          import pyaudio

          import wave

       

          CHUNK = 1024

       

          wf = wave.open('White_Noise.wav', 'rb')

       

          p = pyaudio.PyAudio()

       

          stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),

              channels=wf.getnchannels(),

              rate=wf.getframerate(),

              output=True)

       

          data = wf.readframes(CHUNK)

       

          while data != '': 

              stream.write(data) 

              data = wf.readframes(CHUNK)

       

          stream.stop_stream()

          stream.close()

          p.terminate()

        • Re: Error Playback wav file in python script
          clem57

          Instead of blocking mode, try callback mode

           

           

          """PyAudio Example: Play a wave file (callback version)."""

           

          import pyaudio

          import wave

          import time

          import sys

           

          if len(sys.argv) < 2:

             print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])

             sys.exit(-1)

           

          wf = wave.open(sys.argv[1], 'rb')

           

          # instantiate PyAudio (1)

          p = pyaudio.PyAudio()

           

          # define callback (2)

          def callback(in_data, frame_count, time_info, status):

             data = wf.readframes(frame_count)

             return (data, pyaudio.paContinue)

           

          # open stream using callback (3)

          stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),

             channels=wf.getnchannels(),

             rate=wf.getframerate(),

             output=True,

             stream_callback=callback)

           

          # start the stream (4)

          stream.start_stream()

           

          # wait for stream to finish (5)

          while stream.is_active():

             time.sleep(0.1)

           

          # stop stream (6)

          stream.stop_stream()

          stream.close()

          wf.close()

           

          # close PyAudio (7)

          p.terminate()

          1 of 1 people found this helpful