0

In Unity, I'm using the following code to stream audio from the server, but I don't know how to add a seek bar(slider to change the playing duration) to it. Any help would be much appreciated.

   IEnumerator GetAudioClip()
     {
         using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.MPEG))
         {
             DownloadHandlerAudioClip dHA = new DownloadHandlerAudioClip(url, AudioType.MPEG);
             dHA.streamAudio = true;
             www.downloadHandler = dHA;
             www.SendWebRequest();
             while (www.downloadProgress < 0.01)
             {
                 Debug.Log(www.downloadProgress);
                 yield return new WaitForSeconds(.1f);
             }
             if (www.isNetworkError)
             {
                 Debug.Log("error");
             }
             else
             {
                 audioSource.clip = dHA.audioClip;
                 audioSource.Play();
             }
         }
     }
EA1
  • 11
  • 1
  • 4

1 Answers1

0

Here is the basic example which shows what you need. Make changes according to your preference.

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.Networking;

public class Test : MonoBehaviour
{
    private float _audioLength;
    private string url = "test url";

    public Slider slider;
    public AudioSource audioSource;

    private void Start()
    {
        slider.maxValue = 1f;
        slider.onValueChanged.AddListener(OnSliderValueChange);
        StartCoroutine(GetAudioClip());
    }

    private void OnSliderValueChange(float f) => audioSource.time = f * _audioLength;

    private void OnDisable() => slider.onValueChanged.RemoveAllListeners();

    private IEnumerator GetAudioClip()
    {
        using (var www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.UNKNOWN))
        {
            yield return www.SendWebRequest();
        
            if (www.result == UnityWebRequest.Result.ConnectionError)
            {
                Debug.Log("error");
                yield break;
            }
            ((DownloadHandlerAudioClip)www.downloadHandler).streamAudio = true;
            var audioClip = ((DownloadHandlerAudioClip)www.downloadHandler).audioClip;
            yield return null;
            audioSource.clip = audioClip;
            _audioLength = audioClip.length;
            audioSource.Play();
        }
    }
}

Add slider in inspector and you good to go.

Jaimin
  • 501
  • 4
  • 13