How do I access Audio output for analysis in python 3

I'm trying to play a song, make a audio visualizer for it while it's playing, and I want the visualizer to be based on output signals so that it more modular and easier to sync, but I don't know how to get access my computer's audio output without making a special hardware. How do I do it with just programming.

I've been researching pyaudio, and here is my code thus far. I think it's accessing both input and output signals, but I don't know how to remove the former. All my attempts have crashed the program.

Lastly, this code mostly comes from this fantastic article on the subject: https://www.swharden.com/wp/2016-07-19-realtime-audio-visualization-in-python/

import pyaudio
import numpy as np
maxValue = 2**16
bars = 35
p=pyaudio.PyAudio()
stream=p.open(format=pyaudio.paInt16,channels=2,rate=44100, 
              input=True, output=True, frames_per_buffer=256
             )
while True:
    data = np.fromstring(stream.read(1024),dtype=np.int16)*100
    #print(type(data))
    dataL = data[0::2]
    dataR = data[1::2]
    #print(dataR.shape)
    peakL = np.abs(np.max(dataL)-np.min(dataL))/maxValue
    peakR = np.abs(np.max(dataR)-np.min(dataR))/maxValue
    lString = "#"*int(peakL*bars)+"-"*int(bars-peakL*bars)
    rString = "#"*int(peakR*bars)+"-"*int(bars-peakR*bars)
    #print(dataL)
    print("L=[%s]\tR=[%s]"%(lString, rString))
    #if lString != rString:
    #    print('here')

Upvotes: 4

Views: 7104

Answers (1)

Lukasz Tracewski
Lukasz Tracewski

Reputation: 11407

Here are three ideas:

  1. Route your output to JACK, process in pyaudio (with pyjack) and then output to the speakers.
  2. Use the microphone, which is exactly what is done in the article.
  3. If it's OK to play the music in the same app as visualisation, then you have lot's of options. I'd probably check e.g. PyGame, as it provides everything that is needed to play music in real time and make visual effects. Otherwise lot's of resources can be found in Python In Music.

Mind that if your idea was to play music in some player and let Python somehow catch the stream, that would be rather challenging. The processes and streams are isolated for a good purpose. Accessing memory space that does not belong to you can easily result in segmentation fault.

Upvotes: 2

Related Questions