Created
November 14, 2013 05:05
-
-
Save WarrenWeckesser/7461696 to your computer and use it in GitHub Desktop.
A couple functions for generating wav files with a 3 byte sample width.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# create_sample24.py | |
# Author: Warren Weckesser | |
# License: BSD 3-Clause (http://opensource.org/licenses/BSD-3-Clause) | |
import numpy as np | |
import wave | |
def create_sample(): | |
# 27 bytes (1 channel, 9 frames, 3 bytes per frame) | |
# The bytes are simply 1, 2, 3, ..., 27. | |
data = ''.join(chr(k) for k in range(1, 28)) | |
w = wave.open('sample24.wav', 'wb') | |
w.setnchannels(1) | |
w.setsampwidth(3) | |
w.setframerate(22050) | |
w.writeframes(data) | |
w.close() | |
def create_sine(): | |
# Create a 24 bit wav file containing a pure sine wave. | |
rate = 22050 # samples per second | |
T = 3 # sample duration (seconds) | |
f = 440.0 # sound frequency (Hz) | |
t = np.linspace(0, T, T*rate, endpoint=False) | |
x = (2**23 - 1) * np.sin(2 * np.pi * f * t) | |
a = x.astype(np.int32).view(np.uint32) | |
# By shifting first 0 bits, then 8, then 16, the resulting output | |
# is 24 bit little-endian. | |
b = (a.reshape(-1, 1) >> np.array([0, 8, 16])) & 255 | |
data = b.astype(np.uint8).tostring() | |
w = wave.open('sine24.wav', 'wb') | |
w.setnchannels(1) | |
w.setsampwidth(3) | |
w.setframerate(rate) | |
w.writeframes(data) | |
w.close() | |
if __name__ == "__main__": | |
create_sample() | |
create_sine() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment