2014-01-24 4 views
1

URL이 온라인 라디오이므로 재생하고 싶습니다. 그래서, 나는 이렇게했습니다 : 스트림을 읽고 그것을 바이트 배열에 쓰고 audioTrack 클래스로 재생합니다. 코드는 다음과 같습니다.Xamarin Android C# 오디오 스트림 재생 (온라인 라디오)

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

      } 
     } 

그러나이 방법으로 나는 잡음 만 듣고 음악은들을 수 없습니다.

답변

2

MediaPlayer 클래스를 사용하면 URL을 제공하여 오디오를 스트리밍 할 수 있습니다.

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