109 lines
2.3 KiB
C#
109 lines
2.3 KiB
C#
using System;
|
|
using Crosstales.Radio.Util;
|
|
using UnityEngine;
|
|
|
|
namespace Crosstales.Radio.Tool
|
|
{
|
|
[RequireComponent(typeof(AudioSource))]
|
|
[HelpURLAttribute("https://www.crosstales.com/media/data/assets/rtvoice/api/class_crosstales_1_1_r_t_voice_1_1_tool_1_1_loudspeaker.html")]
|
|
public class Loudspeaker : MonoBehaviour
|
|
{
|
|
[Tooltip("Origin Player.")]
|
|
public BasePlayer Player;
|
|
|
|
[Tooltip("Silence the origin (default: true).")]
|
|
public bool SilenceSource = true;
|
|
|
|
private AudioSource audioSource;
|
|
|
|
private bool stopped = true;
|
|
|
|
private long dataPosition;
|
|
|
|
public bool isSilenceSource
|
|
{
|
|
get
|
|
{
|
|
return SilenceSource;
|
|
}
|
|
set
|
|
{
|
|
SilenceSource = value;
|
|
}
|
|
}
|
|
|
|
public void Awake()
|
|
{
|
|
audioSource = GetComponent<AudioSource>();
|
|
audioSource.playOnAwake = false;
|
|
audioSource.Stop();
|
|
}
|
|
|
|
public void Start()
|
|
{
|
|
if (Player == null)
|
|
{
|
|
Debug.LogWarning("No 'Player' added to the Loudspeaker!");
|
|
}
|
|
else
|
|
{
|
|
Player.isCaptureDataStream = true;
|
|
}
|
|
}
|
|
|
|
public void Update()
|
|
{
|
|
if (Player != null && Player.isAudioPlaying)
|
|
{
|
|
if (stopped)
|
|
{
|
|
stopped = false;
|
|
dataPosition = Player.DataStream.Position;
|
|
AudioClip clip = AudioClip.Create(Player.RadioStation.Name, int.MaxValue, Player.Channels, Player.SampleRate, true, readPCMData);
|
|
audioSource.clip = clip;
|
|
audioSource.Play();
|
|
if (SilenceSource)
|
|
{
|
|
Player.Silence();
|
|
}
|
|
}
|
|
}
|
|
else if (!stopped)
|
|
{
|
|
audioSource.Stop();
|
|
audioSource.clip = null;
|
|
stopped = true;
|
|
}
|
|
}
|
|
|
|
public void OnDisable()
|
|
{
|
|
audioSource.Stop();
|
|
audioSource.clip = null;
|
|
stopped = true;
|
|
}
|
|
|
|
private void readPCMData(float[] data)
|
|
{
|
|
if (Player.isAudioPlaying && Player.DataStream != null)
|
|
{
|
|
byte[] array = new byte[data.Length * 2];
|
|
long position = Player.DataStream.Position;
|
|
Player.DataStream.Position = dataPosition;
|
|
int num;
|
|
if ((num = Player.DataStream.Read(array, 0, array.Length)) > 0)
|
|
{
|
|
float[] src = Helper.ConvertByteArrayToFloatArray(array, num);
|
|
Buffer.BlockCopy(src, 0, data, 0, data.Length * 4);
|
|
dataPosition += num;
|
|
}
|
|
Player.DataStream.Position = position;
|
|
}
|
|
else
|
|
{
|
|
Buffer.BlockCopy(new float[data.Length], 0, data, 0, data.Length * 4);
|
|
}
|
|
}
|
|
}
|
|
}
|