audio_experiment/visualiser/player.py
2022-02-20 17:34:22 +01:00

66 lines
1.5 KiB
Python

#import modules
import numpy as np
import time
import math
import pyaudio
import pygame as pg
#load song.npy
data = np.load('song.npy')
surface = pg.display.set_mode((800, 600))
progress = 0
average = 0
# define callback (2)
def callback(in_data, frame_count, time_info, status):
#read frames from data
global progress
global average
#print(frame_count)
#read frames from data
frames = data[progress:progress+frame_count]
#average half of the frames
framesx = []
for i in range(0, len(frames), 80):
average = np.average(frames[i:i+2])
framesx.append(average)
#print(len(framesx))
for tmp in framesx:
#remap tmp from -1 to 1 to 0 to 255
tmp = (tmp + 1) * 127.5
#convert to int
tmx, _ = math.modf(tmp)
tmp = tmx * 255
#set treshold
#print(tmp)
#create color
if tmp > 250:
xtmp = 255
else:
xtmp = 0
color = (xtmp, xtmp, xtmp)
#set screen to color
surface.fill(color)
#update progress
pg.display.flip()
#increment progress
progress += frame_count
#return frames
return (frames, pyaudio.paContinue)
#initialise pyaudio
pg.init()
p = pyaudio.PyAudio()
#play the song from data
stream = p.open(format=p.get_format_from_width(data.dtype.itemsize),
channels=1,
rate=16000,
output=True,
stream_callback=callback)
stream.start_stream()
while True:
time.sleep(0.1)