【问题标题】:Save MP3 file from URL in VB.NET在 VB.NET 中从 URL 保存 MP3 文件
【发布时间】:2013-08-13 05:04:50
【问题描述】:

我正在尝试从我的服务器下载一个 .mp3 文件,并将其保存在本地的 VB.NET 中。但是,当我这样做时,保存的文件是损坏的,因为内容包含多行如下所示的内容,其下方有大量随机/奇怪的字符(我假设构建块音频文件)。

这是我所看到的:http://i.troll.ws/11d37d00.png

date = "20130811_18:22:58.466";
host = "DC3APS421";
kbps = "48";
khz = "22050";

当我尝试在 WMP 中播放 .mp3 文件时,它还说它已损坏。这是我用来下载和保存的代码。

' Download the MP3 file contents

Dim request As WebRequest = WebRequest.Create("http://www.mysite.org/secure/speech/?text=Test.")
request.Credentials = CredentialCache.DefaultCredentials
Dim response As WebResponse = request.GetResponse()
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
Dim dataStream As Stream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()

reader.Close()
response.Close()

Debug.Print("Downloaded. Saving to local Audio Cache...")

' Check and create the audio-cache directory

If (Not System.IO.Directory.Exists(WorkingDir + "\audio-cache\")) Then
    Debug.Print("Audio cache directory doesn't exist. Creating... ")
    System.IO.Directory.CreateDirectory(WorkingDir + "\audio-cache\")
    Debug.Print("Created at " + WorkingDir + "\audio-cache\")
End If

Dim Data As String = responseFromServer

' Save the mp3 file!

Dim fileLoc As String = WorkingDir + "\audio-cache\" + Mp3Hash + ".mp3"
Dim fs As FileStream = Nothing
If (Not File.Exists(fileLoc)) Then
    fs = File.Create(fileLoc)
    Using fs

    End Using
End If
If File.Exists(fileLoc) Then
    Using sw As StreamWriter = New StreamWriter(fileLoc)
        sw.Write(Data)
    End Using
End If

Debug.Print("Saved successfully to " + fileLoc)

如何从 URL 正确下载和本地保存 mp3 文件?

【问题讨论】:

  • 如果您打开浏览器并导航到http://www.mysite.org/secure/speech/?text=Test,浏览器将开始下载完美的 MP3 文件,对吧?
  • mysite.org/secure/speech/?text=Test”。它从重定向下载到 .mp3 文件的 URL。因此,它是一个有效/合法的 mp3 文件。我什至可以在我的浏览器中播放它。
  • 保存的文件如下所示。 i.troll.ws/11d37d00.png 用 NP++ 打开

标签: vb.net download mp3


【解决方案1】:

试试这个

Dim HttpReq As HttpWebRequest = DirectCast(WebRequest.Create("http://...."), HttpWebRequest)

        Using HttpResponse As HttpWebResponse = DirectCast(HttpReq.GetResponse(), HttpWebResponse)
            Using Reader As New BinaryReader(HttpResponse.GetResponseStream())
                Dim RdByte As Byte() = Reader.ReadBytes(1 * 1024 * 1024 * 10)
                Using FStream As New FileStream("FileName.extension", FileMode.Create)
                    FStream.Write(RdByte, 0, RdByte.Length)
                End Using
            End Using
        End Using

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多