Xamarin Android C# play audio stream (online radio)

怎甘沉沦 提交于 2021-02-10 13:36:11

问题


I have a URL of online-radio and I'd like to play it. So, I've done it this way: reading stream and writing it to byte array and playing it with audioTrack class. Here's the code:

private static async Task Play()
        {
            using (WebClient wcDownload = new WebClient())
            {
                // Create a request to the file we are downloading
                WebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://media.vmariel.ru:8000/puls");
                // Set default authentication for retrieving the file
                webRequest.Credentials = CredentialCache.DefaultCredentials;
                // Retrieve the response from the server
                WebResponse webResponse = (HttpWebResponse)webRequest.GetResponseAsync().Result;
                // Ask the server for the file size and store it
                Int64 fileSize = webResponse.ContentLength;

                // Open the URL for download 
                System.IO.Stream strResponse = wcDownload.OpenRead(new System.Uri("http://media.vmariel.ru:8000/puls"));


                // It will store the current number of bytes we retrieved from the server
                int bytesSize = 0;
                // A buffer for storing and writing the data retrieved from the server
                byte[] downBuffer = new byte[131072];
                // Loop through the buffer until the buffer is empty
                AudioTrack audioTrack = new AudioTrack(
                    // Stream type
                    Android.Media.Stream.Music,
                    // Frequency
                    48000,
                    // Mono or stereo
                    ChannelConfiguration.Stereo,
                    // Audio encoding
                    Android.Media.Encoding.Pcm16bit,
                    // Length of the audio clip.
                    downBuffer.Length,
                    // Mode. Stream or static.
                    AudioTrackMode.Stream);

                audioTrack.Play();
                while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
                {
                    await audioTrack.WriteAsync(downBuffer, 0, downBuffer.Length);
                }

            }
        }

but this way I can hear only noise, no music.


回答1:


You can use the MediaPlayer class to stream audio by providing a URL.

MediaPlayer player = new MediaPlayer();
player.SetAudioStreamType (Stream.Music);
player.SetDataSource ("http://media.vmariel.ru:8000/puls");
player.Prepare();
player.Start();


来源:https://stackoverflow.com/questions/21343161/xamarin-android-c-sharp-play-audio-stream-online-radio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!