Forum Xamarin.Android

Trouble streaming music

I am trying to get my app to register a music stream I have set up online. Here is what I have so far using the sample code Xamarin provides:

protected override void OnCreate (Bundle bundle)

    {

        base.OnCreate (bundle);



            SetContentView (Resource.Layout.Main);



            String url = "http://www.publicenemy.com/radio-n.php";

            MediaPlayer mediaPlayer = new MediaPlayer();

            mediaPlayer.SetAudioStreamType(Stream.Music);

            mediaPlayer.SetDataSource(url);

            mediaPlayer.PrepareAsync ();

            mediaPlayer.Start();



        // Create your application here

    }

It builds fine but when I go to deploy to test it I get an error in the app output

[MediaPlayer] start called in state 4

[MediaPlayer] error (-38, 0)

[MediaPlayer] Error (-38,0)

[MediaPlayer] error (1, -2147483648)

[MediaPlayer] Error (1,-2147483648)

Pretty new to Android app development, not sure what's wrong here. Any help will be appreciated!

Best Answer

Answers

  • KlutchSCKlutchSC USMember

    On final thing, I found the graph display of the states the stream must be in for each step to work (found here:http://developer.android.com/reference/android/media/MediaPlayer.html)

    However, NONE of the operations shown actually work with the MediaPlayer class. Im extremely lost and the documentation for the media player is complete crap as it leads me nowhere.

    Maybe someone could simply explain this diagram. I also checked the error codes above.
    -38 means that the start was called before the stream is prepared, but according to the documentation Async should return it immediately, so I'm not sure why this is breaking.
    -1, -21474... was not coming up with anything was I searched, I'm sorry

  • ChrisHonselaarChrisHonselaar NLBeta ✭✭✭
    edited May 2013

    If you are using PrepareAsync() instead of Prepare(), you should only Start() after receiving the Prepared event.

    You may find the Media Playback Guide document easier to start with than the API reference link you mentioned above. This is true in general for Android documentation.

  • KlutchSCKlutchSC USMember

    Thank you, I actually found that site too and began looking at it. I noticed it says that in order to send it from an initialized state into a prepared state I need to use the method of MediaPlayer.OnPreparedListener
    but first of all there is no call that can be made to this method, doesn't exist in Xamarin. Second, I can call the method
    MediaPlayer.SetOnPreparedListener ()
    but this is telling me that it must take in a parameter of type listener. I have no idea what this is and no idea where to look.

    Like I said before, I am very new to app development and the references are not the same on this page as the ones Xamarin uses.

  • kingleroygkingleroyg ZAMember ✭✭

    Hey KlutchSC, Did you find a solution too your problem ? If so could you github your code or atleast show us a sample. I am also facing the same problem

    Thanks

  • Here is my solution with fading and remote streaming source async

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    using Android.Media;
    using TepTepMobile.Droid.Services.Media;
    using TepTepMobile.Services.Audio;
    using TepTepMobile.Services.Messaging;
    using Xamarin.Forms;
    
    [assembly: Dependency(typeof(MultiAudioPlayer))]
    namespace TepTepMobile.Droid.Services.Media
    {
        public class MultiAudioPlayer : IMultiAudioPlayer
        {
            private readonly Dictionary<int, TepTepMediaPlayer> _mediaPlayers;
            private Queue<KeyValuePair<string, int>> _quene;
            public int FadeInSeconds { get; set; }
            public int FadeOutSeconds { get; set; }
            private readonly IMapInfoMessenger _infoMessenger;
    
            public MultiAudioPlayer(int fadeInSecond, int fadeOutSeconds)
            {
                FadeInSeconds = fadeInSecond;
                FadeOutSeconds = fadeOutSeconds;
            }
    
            public MultiAudioPlayer() : this(5, 5)
            {
                _mediaPlayers = new Dictionary<int, TepTepMediaPlayer>();
                _infoMessenger = App.IoC.Resolve<IMapInfoMessenger>();
            }
    
            public void PlayMp3File(string filePath, int remoteId, bool loop)
            {
    
                if (!_mediaPlayers.TryGetValue(remoteId, out TepTepMediaPlayer existPlayer))
                {
    
                    existPlayer = new TepTepMediaPlayer();
                    existPlayer.Reset();
                    existPlayer.UniqueHash = remoteId;
                    existPlayer.SetDataSource(filePath);
                    existPlayer.Looping = loop;
                    existPlayer.PrepareAsync();
                    existPlayer.Prepared += delegate { existPlayer.Start(); };
    
                    existPlayer.Completion += ExistPlayer_Completion;
                    FadeInAsync(this.FadeInSeconds, 0, existPlayer.UniqueHash, new CancellationToken());
                    _mediaPlayers.Add(remoteId, existPlayer);
                    return;
                }
    
                FadeOutAsync(FadeOutSeconds, 1, existPlayer.UniqueHash, new CancellationToken());
            }
    
            private void ExistPlayer_Completion(object sender, EventArgs e)
            {
                if (sender is TepTepMediaPlayer player)
                {
                    var audoFinishParam = new AudioFinishArgs();
                    audoFinishParam.FileId = player.UniqueHash;
                    _infoMessenger.SetAudioFinished(audoFinishParam);
                }
    
                ;
    
                //AudioCompletedChange?.Invoke(new AudioFinishArgs());
                if (_quene != null && _quene.Any())
                {
                    var element = _quene.Dequeue();
                    PlayMp3File(element.Key, element.Value, false);
                }
    
    
            }
    
    
    
            public void StopMp3File(int remoteId)
            {
                if (remoteId == 0)
                {
                    return;
                }
    
                if (_mediaPlayers.TryGetValue(remoteId, out TepTepMediaPlayer existPlayer))
                {
    
                    FadeOutAsync(FadeOutSeconds, 1, existPlayer.UniqueHash, new CancellationToken());
                }
            }
    
            public void StopAll()
            {
                foreach (var tepTepMediaPlayer in _mediaPlayers)
                {
                    var player = tepTepMediaPlayer.Value;
                    player.Stop();
                }
            }
    
    
            public async void FadeInAsync(int sec, float volume, int remoteId, CancellationToken token)
            {
                bool fading = true;
                if (!_mediaPlayers.TryGetValue(remoteId, out TepTepMediaPlayer player))
                {
                    return;
                }
    
                if (player == null)
                {
                    return;
                }
    
                try
                {
                    while (fading)
                    {
                        float iter = (float)1 / sec;
                        for (int i = 1; i <= sec; i++)
                        {
                            float vol = (float)volume + (iter * i);
                            if (vol < 0) break;
                            await Task.Delay(1000);
                            var player1 = player;
                            await Task.Run(() =>
                            {
                                Console.WriteLine("Setting vol to: " + player1 + ": " + vol);
                                player1.SetVolume(vol, vol);
                            }, token);
                        }
                        player.SetVolume(0, 0);
                        if (token.IsCancellationRequested != true)
                        {
                            player.Stop();
                            player.Release();
                            player = null;
                        }
    
                        fading = false;
                    }
    
                }
                catch (OperationCanceledException)
                {
                    //Do stuff to handle cancellation
                    Console.WriteLine("OperationCanceledException ");
                }
                finally
                {
                    if (player != null)
                    {
                        _mediaPlayers.Remove(player.UniqueHash);
                        player?.Stop();
                    }
                }
            }
    
            public void PushToQueue(string filePath, int remoteId)
            {
                if (_quene == null)
                {
                    _quene = new Queue<KeyValuePair<string, int>>();
                }
    
                if (_mediaPlayers.Count == 0)
                {
                    PlayMp3File(filePath, remoteId, false);
                }
                else
                {
                    _quene.Enqueue(new KeyValuePair<string, int>(filePath, remoteId));
                }
            }
    
            public async void FadeOutAsync(int sec, float volume, int remoteId, CancellationToken token)
            {
                bool fading = true;
                TepTepMediaPlayer player = null;
                if (!_mediaPlayers.TryGetValue(remoteId, out player))
                {
                    return;
                }
                _mediaPlayers.Remove(remoteId);
    
                if (player == null)
                {
                    return;
                }
    
    
                try
                {
                    while (fading)
                    {
                        float iter = (float)1 / sec;
                        for (int i = 1; i <= sec; i++)
                        {
                            float vol = (float)volume - (iter * i);
                            if (vol < 0) break;
                            await Task.Delay(1000, token);
                            var player1 = player;
                            await Task.Run(() =>
                            {
                                Console.WriteLine("Setting vol to: " + player1.ToString() + ": " + vol.ToString());
                                player1.SetVolume(vol, vol);
                            }, token);
                        }
                        player.SetVolume(0, 0);
                        if (token.IsCancellationRequested != true)
                        {
                            player.Stop();
                            player.Release();
                            player = null;
                        }
    
                        fading = false;
                    }
    
                }
                catch (OperationCanceledException)
                {
                    //Do stuff to handle cancellation
                    Console.WriteLine("OperationCanceledException ");
                }
                finally
                {
                    //https://stackoverflow.com/questions/7816551/java-lang-illegalstateexception-what-does-it-mean
    
                    if (player != null)
                    {
                        if (player.IsPlaying) player?.Stop();
                        player.Release();
                        player = null;
                    }
                }
    
    
            }
    
        }
    }
    
Sign In or Register to comment.