Search code examples
pythonaudiopyaudiowave

How to play infinitely a ".wav" file using python


I'm trying to play the ".wav" file infinitely to use in my experiment.

I'm using the script of the pyaudio website (http://people.csail.mit.edu/hubert/pyaudio/), however it plays for only 5 seconds.

I tried to use the code below, but it plays for some seconds.

import pyaudio
import wave

while True:
    CHUNK = 20*100

    wf = 
    wave.open('Metano_Ref_Lockin=SR830_mod=0.460V_freq=3936_PP=20_NP=100.wav', 'rb')
    data = wf.readframes(CHUNK)

   p = pyaudio.PyAudio()

   stream = p.open(format=pyaudio.paInt16,
            channels=wf.getnchannels(),
            rate=wf.getframerate(),
            output_device_index=4,
            output=True)


   while data != '':
      stream.write(data)
      data = wf.readframes(CHUNK)

   stream.stop_stream()
   stream.close()
   p.terminate()

On the other hand, this code works, nevertheless, the signal is not uniform (some noises appear).

import pyaudio
import wave

CHUNK = 20*100

wf = wave.open('Metano_Ref_Lockin=SR830_mod=0.460V_freq=3936_PP=20_NP=100.wav', 'rb')
data = wf.readframes(CHUNK)

p = pyaudio.PyAudio()

stream = p.open(format=pyaudio.paInt16,
            channels=wf.getnchannels(),
            rate=wf.getframerate(),
            output_device_index=4,
            output=True)

while data != '':
    stream.write(data)

stream.stop_stream()
stream.close()
p.terminate()

I expect a uniform signal to be reproduced infinitely. Thanks.


Solution

  • Your data comparison should be

    while data != b'':
        ...
    

    or the simpler variant (empty strings cast to False):

    while data:
        ...
    

    Also, you really should reuse wf, stream, and p inbetween loops:

    import pyaudio
    import wave
    
    CHUNK = 2 ** 11
    
    wf = wave.open('Metano_Ref_Lockin=SR830_mod=0.460V_freq=3936_PP=20_NP=100.wav', 'rb')
    
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paInt16,
            channels=wf.getnchannels(),
            rate=wf.getframerate(),
            output=True)
    
    
    while True:
        wf.rewind()
    
        data = wf.readframes(CHUNK)
        while data:
            stream.write(data)
            data = wf.readframes(CHUNK)
    
    wf.close()
    stream.stop_stream()
    stream.close()
    p.terminate()