简体   繁体   中英

PyAudio 'unknown format: %r' error when trying to play a wav file

I am trying to run the following code (taken from How to play an audiofile with pyaudio? ):

import pyaudio
import wave
import sys

class AudioFile:
    chunk = 1024

    def __init__(self, file):
        """ Init audio stream """ 
        self.wf = wave.open(file, 'rb')
        self.p = pyaudio.PyAudio()
        self.stream = self.p.open(
            format = self.p.get_format_from_width(self.wf.getsampwidth()),
            channels = self.wf.getnchannels(),
            rate = self.wf.getframerate(),
            output = True
        )

    def play(self):
        """ Play entire file """
        data = self.wf.readframes(self.chunk)
        while data != '':
            self.stream.write(data)
            data = self.wf.readframes(self.chunk)

    def close(self):
        """ Graceful shutdown """ 
        self.stream.close()
        self.wf.close()
        self.p.terminate()

# Usage example for pyaudio
a = AudioFile("Filename.wav")
a.play()
a.close()

But I keep getting the following error:

Traceback (most recent call last):
  File "c:\Users\tangu\OneDrive\Bureau\Python 101\Python.py", line 33, in <module>
    a = AudioFile("DP.wav")
  File "c:\Users\tangu\OneDrive\Bureau\Python 101\Python.py", line 10, in __init__
    self.wf = wave.open(file, 'rb')
  File "C:\Users\tangu\anaconda3\lib\wave.py", line 510, in open
    return Wave_read(f)
  File "C:\Users\tangu\anaconda3\lib\wave.py", line 164, in __init__
    self.initfp(f)
  File "C:\Users\tangu\anaconda3\lib\wave.py", line 144, in initfp
    self._read_fmt_chunk(chunk)
  File "C:\Users\tangu\anaconda3\lib\wave.py", line 269, in _read_fmt_chunk
    raise Error('unknown format: %r' % (wFormatTag,))
wave.Error: unknown format: 3

Does anyone know how to fix this?

It's because I was using 32-bit WAV files... Once I changed them to 16-bit, I had no issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM