下载后立即播放音频或视频文件

时间:2012-05-06 14:05:34

标签: objective-c ios5

我使用NSURLConnection委托方法下载视频或音频文件,下载正常,现在我需要在完成下载后立即播放。

我的相关代码是:

 -(IBAction)downloadAndPlay:(id)sender{
    NSString *fileUrlPath=[host stringByAppendingString:rowContent];  


            // Create the request.
            NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:fileUrlPath]
            cachePolicy:NSURLRequestUseProtocolCachePolicy
            timeoutInterval:60.0];


            // create the connection with the request
            // and start loading the data
            NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

            if (theConnection) {
                // Create the NSMutableData to hold the received data.

                receivedData = [NSMutableData data] ;
                //NSLog(@"connection succeeded");

            } else {

                // Inform the user that the connection failed.
                UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Music Album" message:@"Connection failed, please try again" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alertView show];

            }
    }

  //NSURLConnection delegate methods  
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        // This method is called when the server has determined that it
        // has enough information to create the NSURLResponse.

        // It can be called multiple times, for example in the case of a
        // redirect, so each time we reset the data.

        // receivedData is an instance variable declared elsewhere.
        [receivedData setLength:0];
    }

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
        // Append the new data to receivedData.
        // receivedData is an instance variable declared elsewhere.
        [receivedData appendData:data];
    }

    - (void)connection:(NSURLConnection *)connection
      didFailWithError:(NSError *)error
    {

        // inform the user
        NSLog(@"Connection failed! Error - %@ %@",
              [error localizedDescription],
              [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
    }

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        // do something with the data
        // receivedData is declared as a method instance elsewhere
        NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);

    }

如何在下载文件(自动播放)后立即播放文件(音频或视频)。 提前完成。

1 个答案:

答案 0 :(得分:0)

您需要将已下载的数据保存到文件中,然后使用MPMoviePlayerViewController或类似内容打开该文件。现在,您只需将文件下载为NSData,然后保留即可。

因此,使用适当的名称/扩展名将NSData对象保存到文件系统(或者只是将下载文件写入文件系统本身,这对于较大的文件更有意义),获取文件URL句柄,以及将它传递给你的媒体播放器。