百度Mp3的API在windows phone 7中的使用

l_serein發表於2012-11-28

最近重新寫了一個音樂的播放器。其中用到了百度音樂的API:http://cloud21.iteye.com/blog/611914

由於百度MP3的API的地址和我們請求的到得XML檔案都是GB2312編碼的。所以遇到了點麻煩。好了廢話不說,上程式碼。

namespace BaiduAPI_test
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
public class MusicUpdateState
{
public HttpWebRequest AsyncRequest { get; set; }
public HttpWebResponse AsyncResponse { get; set; }
}
private void btn_search_Click(object sender, RoutedEventArgs e)
{
//string gb_songname = utf_8_to_gb2312(SongName.Text);
//string gb_singername = utf_8_to_gb2312(SingerName.Text);
            //由於百度的地址是用GB2312編碼的,所以要用HttpUtility.UrlEncode這個函式來編碼
string songname = HttpUtility.UrlEncode(SongName.Text);
string singername = HttpUtility.UrlEncode(SingerName.Text);

string Uri = "http://box.zhangmen.baidu.com/x?op=12&count=1&title=" + songname + "$$" + singername + "$$$$";

UriBuilder fullUri = new UriBuilder(Uri);
HttpWebRequest musicRequest = (HttpWebRequest)WebRequest.Create(fullUri.Uri);

MusicUpdateState musicState = new MusicUpdateState();
musicState.AsyncRequest = musicRequest;
musicRequest.BeginGetResponse(new AsyncCallback(HandleMusicResponse), musicState);
}

private void HandleMusicResponse(IAsyncResult asyncResult)
{
MusicUpdateState musicState = (MusicUpdateState)asyncResult.AsyncState;
HttpWebRequest musicRequest = (HttpWebRequest)musicState.AsyncRequest;
musicState.AsyncResponse = (HttpWebResponse)musicRequest.EndGetResponse(asyncResult);

Stream streamResult;
string encode = "";
string decode = "";
streamResult = musicState.AsyncResponse.GetResponseStream();
//這裡也是一樣的,請求得到的XML是用GB2312編碼的,直接用XmlReader讀取Stream的話會提示系統不支援GB2312編碼
var sr = new StreamReader(streamResult);
string srResult = sr.ReadToEnd();

//----Test----------

//Dispatcher.BeginInvoke(() =>
// {
// tb_decode.Text = srResult;
// });

using (XmlReader reader = XmlReader.Create(new StringReader(srResult)))
{
reader.ReadToFollowing("encode");
encode = reader.ReadElementContentAsString();
                //百度地址中間的數字是7位或者8位的,所以要判斷最後一個是不是數字
string encodeUrl = encode.Substring(44,8);
string lastNumberUri = IsNumber(encodeUrl);

reader.ReadToFollowing("decode");
decode = reader.ReadElementContentAsString();

UriBuilder fullUri = new UriBuilder("http://zhangmenshiting.baidu.com/data/music/" + lastNumberUri + "/" + decode);
Dispatcher.BeginInvoke(() =>
{
BaiduMusicElement.Source = fullUri.Uri;
BaiduMusicElement.AutoPlay = true;
BaiduMusicElement.Position = TimeSpan.FromMilliseconds(0);
BaiduMusicElement.Play();
});
}
}
private string IsNumber(string str)
{//判斷str的最後一個字元是否數字
int result;
string lastOne = str.Substring(7);
if (int.TryParse(lastOne, out result))
{
return str;
}
else
{
return str.Substring(0, 7);
}
}

}
}

相關文章