Audio Streaming | WebRTC | 2.2.1-preview
docs.unity3d.com
    Show / Hide Table of Contents

    Audio Streaming

    In order to stream audio, first you need to get the stream instance. Call Audio.CaptureStream().

    audioStream = Audio.CaptureStream();
    

    Add the audio track to the peer. RTCRtpSender will be used when discarding media.

        var senders = new List<RTCRtpSender>();
        foreach (var track in audioStream.GetTracks())
        {
            var sender = localConnection.AddTrack(track);
            senders.Add(sender);
        }
    

    Use the RemoveTrack method to discard the media.

        foreach(var sender in senders)
        {
            localConnection.RemoveTrack(sender);
        }
    

    Call the Audio's Update method inside the MonoBehaviour's OnAudioFilterRead method.

        private void OnAudioFilterRead(float[] data, int channels)
        {
            Audio.Update(data, data.Length);
        }
    
    Note

    As with the AudioListener component, when using the OnAudioFilterRead method, it must be associated with a GameObject.

    Alternatively, AudioRenderer can also be used.

    
        private void Start()
        {
            AudioRenderer.Start();
        }
    
        private void Update()
        {
            var sampleCountFrame = AudioRenderer.GetSampleCountForCaptureFrame();
            var channelCount = 2; // AudioSettings.speakerMode == Stereo
            var length = sampleCountFrame * channelCount;
            var buffer = new NativeArray<float>(length, Allocator.Temp);
            AudioRenderer.Render(buffer);
            Audio.Update(buffer.ToArray(), buffer.Length);
            buffer.Dispose();
        }
    
    Back to top
    Copyright © 2023 Unity Technologies — Terms of use
    • Legal
    • Privacy Policy
    • Cookies
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)
    "Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
    Generated by DocFX on 18 October 2023