Search code examples
pythonmacospython-2.7pyaudio

While using PyAudio to generate tones why do I get clicks between them?


Title explains what the problem is. I have no idea how to fix this. The clicking is between each of the tones played. I also sounds like a pop to some people.

import math
import pyaudio
import sys

PyAudio = pyaudio.PyAudio


def playTone(rate,wave,time,channel):
  data = ''.join([chr(int(math.sin(x/((rate/wave)/math.pi))*127+128)) for x in xrange(rate)])
  p = PyAudio()

  stream = p.open(format =
    p.get_format_from_width(1),
    channels = channel,
    rate = rate,
    output = True)
  for DISCARD in xrange(int(time)):
      stream.write(data)
  #stream.stop_stream()
  #stream.close()
  #p.terminate()


'''
playTone(88000,400,1,2)
playTone(88000,500,1,1)
playTone(88000,600,1,2)
playTone(88000,700,1,2)
'''

def scale(noteNumber):
  counter = 100
  while noteNumber*100 > counter:
    playTone(88000,100+counter,1,2)
    counter += 100

scale(10)

Solution

  • There is a gap between building data = ''.join([... and playing stream.write(data). The gap makes click sound.

    To find out, try dump the data and play it as 88000Hz, 8bit and 2ch raw data.

    Simple solution is to generate all signal before playing.

    Or, use different threads to generate and play sound.