Advertisement
Guest User

Untitled

a guest
Jan 20th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. import pyaudio
  2. import numpy as np
  3. import pygame
  4. import multiprocessing as mp
  5.  
  6. CHUNK = 8192
  7. FORMAT = pyaudio.paInt16
  8. CHANNELS = 1
  9. RATE = 48000
  10. NP_FORMAT = np.int16
  11. DELAY_LENGTH = 8
  12.  
  13.  
  14. def delay_modification(data, buffer, index):
  15.     start_index = index
  16.     buffer_len = len(buffer)
  17.     was_filled = buffer[buffer_len-1] != 0
  18.    
  19.     if was_filled:
  20.         for i in range(len(data) - 1, -1, -1):
  21.             start_index -= 1
  22.             if start_index < 0:
  23.                 start_index = buffer_len - 1
  24.             data[i] = data[i] // 2 + buffer[start_index] // 2
  25.  
  26.     for i in range(len(data)):
  27.         if index == buffer_len:
  28.             index = 0
  29.             was_filled = True
  30.  
  31.         buffer[index] = data[i]
  32.         index += 1
  33.  
  34.     return index
  35.  
  36. def feed_queue(q):
  37.    
  38.     buffer = np.zeros(CHUNK * DELAY_LENGTH)
  39.     index = 0
  40.  
  41.     p = pyaudio.PyAudio()
  42.     stream = p.open(format=FORMAT,
  43.                     channels=CHANNELS,
  44.                     rate=RATE,
  45.                     input=True,
  46.                     output=False,
  47.                     frames_per_buffer=CHUNK)
  48.  
  49.     while True:
  50.         data = stream.read(CHUNK, exception_on_overflow=False)
  51.         data = np.fromstring(data, dtype=NP_FORMAT)
  52.  
  53.         index = delay_modification(data, buffer, index)
  54.         if q.full():
  55.             q.get_nowait()
  56.         q.put(data)
  57.  
  58. def main():
  59.     np.set_printoptions(threshold=np.nan)
  60.  
  61.     queue = mp.Queue(maxsize=RATE // CHUNK)
  62.     p = mp.Process(target=feed_queue, args=(queue,))
  63.     p.start()
  64.    
  65.     pygame.mixer.init()
  66.     S = pygame.mixer.Sound
  67.    
  68.     while True:
  69.         d = queue.get()
  70.         S(d).play()
  71.  
  72.  
  73. if __name__ == "__main__":
  74.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement