我修改寫在C#中的YouTube下載類使用它在Windows手機上。我的結果如下。但是當我調用dw();我從Web瀏覽器的文件未找到的異常在行e.Result.Read(緩衝,0,buffer.Length)。我當然知道這意味着什麼,但我不知道如何解決它。所以我有兩個問題:爲什麼我的代碼不工作?或者有另一種方式在WindowsPhone 7上下載Youtube視頻? (如圖書館或免費代碼片段...)謝謝。的Youtube類工作不
class YoutubeDownload
{
string youtubeurl;
string fileext;
private WebClient webClient = new WebClient();
public void dw()
{
youtubeurl = "http://www.youtube.com/watch?v=locIxsfpgp4&feature=related";
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri(youtubeurl));
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string rawHtml = e.Result;
string getUrl = "http://www.youtube.com/get_video.php?video_id={0}&t={1}";
Regex _titleRegex = new Regex("'VIDEO_TITLE': '(.+)',");
Regex _qualiRegex = new Regex("\"fmt_map\": \"([0-9]{2})");
Regex _idRegex = new Regex("\",\\s*\"t\":\\s*\"([^\"]+)");
Match title = _titleRegex.Match(rawHtml);
Match id = _idRegex.Match(rawHtml);
Match quali = _qualiRegex.Match(rawHtml);
string videotitle = title.Groups[1].Value;
string videoid = youtubeurl.Substring(youtubeurl.IndexOf("?v=") + 3);
string id2 = id.Groups[1].Value.Replace("%3D", "=");
string dlurl = string.Format(getUrl, videoid, id2);
fileext = "flv";
if (rawHtml.Contains("'IS_HD_AVAILABLE': true")) // 1080p/720p
{
dlurl += "&fmt=" + quali.Groups[1].Value;
fileext = "mp4";
}
else
{
dlurl += "&fmt=" + quali.Groups[1].Value;
if (quali.Groups[1].Value == "18") // Medium
fileext = "mp4";
else if (quali.Groups[1].Value == "17") // Mobile
fileext = "3gp";
}
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
webClient.OpenReadAsync(new Uri(dlurl));
}
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
var file = IsolatedStorageFile.GetUserStoreForApplication();
file.CreateDirectory("YoutubeDownloader");
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("file." + fileext, System.IO.FileMode.Create, file))
{
byte[] buffer = new byte[1024];
while (e.Result.Read(buffer, 0, buffer.Length) > 0)
{
stream.Write(buffer, 0, buffer.Length);
}
}
}
}
除了別的,你的「複製」的方法是不正確 - 你永遠*寫*'buffer.Length'字節,即使你讀過小於... – 2012-02-09 17:34:43
我該怎麼辦改用? – user1200226 2012-02-09 17:45:37
當你調用'Read',你應該記住的結果,這樣,那麼你可以使用它在調用寫:'而((bytesRead = stream.Read(緩衝,0,buffer.Length))> 0)'。 .. – 2012-02-09 17:46:33