nighthawk
nighthawk

Reputation: 832

Playing audio from network on Xamarin.Forms

Is it possible to play audio on Xamarin.Forms (Android only, no iOS required) which is received from network over TCP or UDP? In WPF, I'm using NAudio and I have something like this:

// set output device
var provider = new BufferedWaveProvider(codec.RecordFormat);
outputDevice = new WaveOut();
outputDevice.DeviceNumber = 0;
outputDevice.Init(provider);
outputDevice.Play();

Data is received from TCP connection:

if (outputDevice != null)
{
   byte[] decoded = codec.Decode(data, 0, data.Length);
   provider.AddSamples(decoded, 0, decoded.Length);
}

In this case, data is byte[] - its added to circular buffer and WaveOut handles it like stream, playing it continously. That solution works great.

I need same thing in Xamarin - I guess I need some kind of wrapper around AudioTrack since it apparently supports playing from byte stream. How should I do this, what is the "best" or preferred way? Basically, how to play streamed audio received over pure TCP/UDP socket?

Upvotes: 0

Views: 437

Answers (1)

Jessie Zhang -MSFT
Jessie Zhang -MSFT

Reputation: 13863

Google's Android ExoPlayer can stream that media format properly.

The following code is a really simple example of ExoPlayer, but it will show you that it does play that stream:

var mediaUrl = "http://api-streaming.youscribe.com/v1/products/2919465/documents/3214936/audio/stream";
var mediaUri = Android.Net.Uri.Parse(mediaUrl);

var userAgent = Util.GetUserAgent(this, "ExoPlayerDemo");
var defaultHttpDataSourceFactory = new DefaultHttpDataSourceFactory(userAgent);
var defaultDataSourceFactory = new DefaultDataSourceFactory(this, null, defaultHttpDataSourceFactory);
var extractorMediaSource = new ExtractorMediaSource(mediaUri, defaultDataSourceFactory, new DefaultExtractorsFactory(), null, null);
var defaultBandwidthMeter = new DefaultBandwidthMeter();
var adaptiveTrackSelectionFactory = new AdaptiveTrackSelection.Factory(defaultBandwidthMeter);
var defaultTrackSelector = new DefaultTrackSelector(adaptiveTrackSelectionFactory);

exoPlayer = ExoPlayerFactory.NewSimpleInstance(this, defaultTrackSelector);
exoPlayer.Prepare(extractorMediaSource);
exoPlayer.PlayWhenReady = true;

Note:

1.exoPlayer is a class-level variable of SimpleExoPlayer type;

2.this is using the Xamarin.Android binding libraries from the Xam.Plugins.Android.ExoPlayer package

ExoPlayer Docs:

https://developer.android.com/guide/topics/media/exoplayer

Upvotes: 1

Related Questions