1

我正在尝试通过意图(默认媒体播放器)播放远程视频文件,但我也想在流式传输时将其保存在本地。我正在尝试使用以下代码将蒸汽本地保存在工作正常的视频文件中。现在我想在文件被流式传输后立即开始我的意图但是当意图开始时我得到错误“ Sorry this video can not be played”。请注意,如果我在流式传输完成时(何时)将意图代码移动到此方法的末尾,downloadedSize==totalSize那么它可以正常工作,但我想在流式传输的同时播放。有什么帮助吗?

public String DownloadVideo(String Url, String fileName)
    {
    String filepath=null;
    try {
    URL url = new URL(Url);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true);
    urlConnection.connect();

    File SDCardRoot = Environment.getExternalStorageDirectory();
    File file = new File(SDCardRoot,fileName);
    if(file.createNewFile())
    {
    file.createNewFile();
    }
    FileOutputStream fileOutput = new FileOutputStream(file);
    InputStream inputStream = urlConnection.getInputStream();
    int totalSize = urlConnection.getContentLength();
    int downloadedSize = 0;

    byte[] buffer = new byte[1024];
    int bufferLength = 0; //used to store a temporary size of the buffer
    int counter=0;

    while ( (bufferLength = inputStream.read(buffer)) > 0 ) {

    fileOutput.write(buffer, 0, bufferLength);

    if(downloadedSize>2048)
    {
        Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(Uri.parse(file.getPath()),"video/*");
        startActivity(i);
    }
    downloadedSize += bufferLength;
    counter++;
    }
    fileOutput.close();
    if(downloadedSize==totalSize) {
        filepath=file.getPath();
                                }
    } catch (MalformedURLException e) {
    e.printStackTrace();
    } catch (IOException e) {
    filepath=null;
    e.printStackTrace();
    }
    return filepath;

    }
4

1 回答 1

0

我认为问题出在这一行:

i.setDataAndType(Uri.parse(file.getPath()),"video/*");

您将本地文件传递给 Intent,但那是尚未下载的文件。我认为您应该使用 Url 流式传输视频,并将内容存储在文件中

// Use the url of the remote location
i.setDataAndType(Uri.parse(Url),"video/*");
// Also, try to use lowercase for variables e.g. url vs Url

这样,您正在流式传输远程 url,并将内容保存到本地文件。我可能会误解代码,但我会先调查一下

于 2012-12-04T10:49:36.350 回答