Xamarin Android C# 播放音频流(在线电台)

Posted

技术标签:

【中文标题】Xamarin Android C# 播放音频流(在线电台)【英文标题】:Xamarin Android C# play audio stream (online radio) 【发布时间】:2014-02-16 01:35:29 【问题描述】:

我有一个在线电台的 URL,我想播放它。所以,我这样做了:读取流并将其写入字节数组并使用 audioTrack 类播放它。代码如下:

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);
                

            
        

但这样我只能听到噪音,听不到音乐。

【问题讨论】:

【参考方案1】:

您可以使用 MediaPlayer 类通过提供 URL 来流式传输音频。

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

【讨论】:

以上是关于Xamarin Android C# 播放音频流(在线电台)的主要内容,如果未能解决你的问题,请参考以下文章

C# Android 暂停音频文件

Xamarin.Android 使用SoundPool进行音频播放

实时音频流库

使用 C# 从 RTMP 服务器获取和播放音频流的最简单方法是啥?

Xamarin - 遍历 Android 设备上的所有音频文件

Android20.0 第20章 音频视频拍照截图