Skip to content

Instantly share code, notes, and snippets.

@Luavis
Last active August 11, 2016 19:35
Show Gist options
  • Save Luavis/36eef7d1d5976be54812d12a0892fd36 to your computer and use it in GitHub Desktop.
Save Luavis/36eef7d1d5976be54812d12a0892fd36 to your computer and use it in GitHub Desktop.
wav file play - pip install pyaudio
from struct import unpack
import pyaudio
AUDIO_PCM_FORMAT = 1
CHUNK = 4096
def _check_chunk(f):
chunck_id = f.read(4).decode('ascii')
if not chunck_id == 'RIFF':
return False
(chunk_size, ) = unpack('<L', f.read(4))
format = f.read(4).decode('ascii')
if not format == 'WAVE':
return False
return chunk_size
def _check_sub_chunk(f):
if not f.read(4).decode('ascii') == 'fmt ':
return False
sub_fmt_chunk_size, = unpack('<L', f.read(4))
audio_format, num_channels, sample_rate, byte_rate, block_align, bits_per_sample = \
unpack('<HHLLHH', f.read(sub_fmt_chunk_size)[:16])
if not sample_rate * num_channels * bits_per_sample / 8 == byte_rate:
print("Not proper byte rate size")
if not bits_per_sample * num_channels / 8 == block_align:
print("not proper block align; Sample size of total channel")
if not f.read(4).decode('ascii') == 'data':
return False
(sub_data_chunk_size, ) = unpack('<L', f.read(4))
return WavMusic(
f,
audio_format,
num_channels,
sample_rate,
byte_rate,
block_align,
bits_per_sample,
sub_data_chunk_size
)
def read_wav(path):
f = open(path, 'rb')
if _check_chunk(f) is False:
print("Not proper wav file")
f.close()
return None
wav_music = _check_sub_chunk(f)
if wav_music is False:
print("Not proper wav sub chunk file")
f.close()
return None
return wav_music
class WavMusic(object):
def __init__(
self,
f,
audio_format,
num_channels,
sample_rate,
byte_rate,
block_align,
bits_per_sample,
sub_data_chunk_size
):
self._f = f
self.audio_format = audio_format
self.num_channels = num_channels
self.sample_rate = sample_rate
self.byte_rate = byte_rate
self.block_align = block_align
self.bits_per_sample = bits_per_sample
self.sub_data_chunk_size = sub_data_chunk_size
def read_data(self, size):
return self._f.read(size)
def close(self):
self._f.close()
if __name__ == '__main__':
p = pyaudio.PyAudio()
wav_music = read_wav('./test.wav')
stream = p.open(
format=p.get_format_from_width(wav_music.bits_per_sample / 8),
channels=wav_music.num_channels,
rate=wav_music.sample_rate,
output=True
)
data = wav_music.read_data(CHUNK)
while not len(data) == 0:
stream.write(data)
data = wav_music.read_data(CHUNK)
stream.stop_stream()
stream.close()
wav_music.close()
p.terminate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment