Skip to content

Instantly share code, notes, and snippets.

@yura415
Created November 11, 2015 13:06
Show Gist options
  • Save yura415/e19c29219f4a35b1da03 to your computer and use it in GitHub Desktop.
Save yura415/e19c29219f4a35b1da03 to your computer and use it in GitHub Desktop.
Play audio PCM stream over TCP in Unity with example broadcaster.
using UnityEngine;
using System.IO;
using System.Net.Sockets;
using System.Collections;
using System;
public class PlayPCMStreamOverTCP : MonoBehaviour
{
public TcpClient Client { get; private set; }
public string Hostname = "localhost";
public int Port = 5555;
public int Channels = 2;
private NetworkStream _netStream;
public void Awake ()
{
Screen.sleepTimeout = SleepTimeout.NeverSleep;
int bufferSize, numBuffers;
AudioSettings.GetDSPBufferSize (out bufferSize, out numBuffers);
Client = new TcpClient (Hostname, Port);
Client.NoDelay = true;
Client.ReceiveTimeout = 0;
_netStream = Client.GetStream ();
}
public void OnApplicationQuit ()
{
if (_netStream != null) {
_netStream.Close ();
_netStream = null;
}
if (Client != null) {
Client.Close ();
Client = null;
}
}
public void OnAudioFilterRead (float[] data, int channels)
{
if (_netStream == null)
return;
var buffer = new byte[data.Length * 4];
_netStream.Read (buffer, 0, buffer.Length);
for (var i = 0; i < data.Length; i++) {
data [i] = BitConverter.ToSingle (buffer, i * 4);
}
}
}
(function () {
"use strict";
const mp3File = "test.mp3";
const lame = require("lame"),
fs = require("fs"),
net = require("net");
const tcpServer = net.createServer(socket => {
var pcmStream = fs.createReadStream(mp3File)
.pipe(new lame.Decoder({
bitDepth: 32,
sampleRate: 48000
}))
.on('format', console.log);
pcmStream.pipe(socket);
socket.on("error", () => {});
socket.on("close", () => {
pcmStream.unpipe(socket);
pcmStream.end();
console.log("bye bye");
});
}).listen(5555);
const address = tcpServer.address();
console.log("TCP Server listening on " + address.address + ":" + address.port);
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment