0

我使用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]);

    }

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

4

1 回答 1

0

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

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

于 2012-05-06T14:59:55.667 回答