Skip to content

Instantly share code, notes, and snippets.

@toshinoritakata
Last active August 29, 2015 13:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toshinoritakata/8800518 to your computer and use it in GitHub Desktop.
Save toshinoritakata/8800518 to your computer and use it in GitHub Desktop.
pyaudioで取得した音量をOSCを使ってデータを送る。 2つのマイクをコールバック関数にIDを返すことで識別している。
#!python3
# -*- coding: utf-8 -*-
import math
import pyaudio
import time
import argparse
import struct
from pythonosc import osc_message_builder
from pythonosc import udp_client
FORMAT = pyaudio.paInt16
SHORT_NORMALIZE = (1.0/32768.0)
WIDTH = 2
CHANNELS = 2
RATE = 44100
def get_rms(block):
count = len(block)/2
format = "%dh"%(count)
shorts = struct.unpack( format, block )
# iterate over the block.
sum_squares = 0.0
for sample in shorts:
# sample is a signed short in +/- 32768.
# normalize it to 1.0
n = sample * SHORT_NORMALIZE
sum_squares += n*n
return math.sqrt( sum_squares / count )
class Callback(object):
def __init__(self, id, client):
self.osc_id = id
self.osc_client = client
def callback(self, in_data, frame_count, time_info, status):
msg = osc_message_builder.OscMessageBuilder(address='/volume')
msg.add_arg(self.osc_id, arg_type = "i")
msg.add_arg(get_rms(in_data), arg_type = "f")
msg = msg.build()
self.osc_client.send(msg)
return (in_data, pyaudio.paContinue)
class MicSender(object):
def __init__(self):
pass
def start(self, id, cbfunc):
stream = p.open(format = FORMAT,
channels = CHANNELS,
rate = RATE,
input = True,
input_device_index = id,
output = True,
stream_callback = cbfunc.callback)
stream.start_stream()
while stream.is_active():
time.sleep(0.1)
stream.stop_stream()
stream.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--ip', default='127.0.0.1', help='This ip of the OSC server')
parser.add_argument('--port', type=int, default=8002, help='The port the OSC server is listening on')
args = parser.parse_args()
client = udp_client.UDPClient(args.ip, args.port)
p = pyaudio.PyAudio()
ms = MicSender()
ms.start(1, Callback(1, client))
ms.start(2, Callback(2, client))
p.terminate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment