下载时播放音频文件 [英] Playing audio file while I download it

查看:81
本文介绍了下载时播放音频文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试播放部分下载的文件(我希望音频在下载的数据足够时开始播放).

I am trying to play partially downloaded file (I want the audio to start when it has enough downloaded data).

我尝试了以下操作:

self.mutableData = nil;
self.mutableData = [NSMutableData data];
self.mutableData.length = 0;

GTMHTTPFetcher *fetcher =
[[self driveService].fetcherService fetcherWithURLString:song.filePath];

[fetcher setReceivedDataBlock:^(NSData *dataReceivedSoFar) {
    [self.mutableData appendData:dataReceivedSoFar];

    if (!self.audioPlayer.playing && self.mutableData.length > 1000000)
    {
        self.audioPlayer = nil;
        self.audioPlayer = [[AVAudioPlayer alloc] initWithData:self.mutableData error:nil];
        [self.audioPlayer play];
    }
}];

[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
    if (error == nil) 
    {
        NSLog(@"NSURLResponse: %@", fetcher.response.);
    } 
    else 
    {
        NSLog(@"An error occurred: %@", error);
    }
}];

但是它会在开始的1-3秒内开始播放,然后应用程序崩溃或一遍又一遍地播放1-3秒,直到下载完成,然后播放整首歌曲.

But it starts playing the first 1-3 seconds and then the app either crashes or it plays that 1-3 seconds over and over again until the download finishes and then it plays the whole song.

我可以通过AVPlayer以某种方式实现此目标,还是可以解决此问题?

Can I somehow achieve this with AVPlayer, or fix this problem?

推荐答案

AVAudioPlayer无法播放打开的用于写入/下载的文件,但AVPlayer可以.切换到AVPlayer.

AVAudioPlayer cannot play files that are open for writing / downloading, but AVPlayer can. Switch to AVPlayer.

这篇关于下载时播放音频文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆