如何在iOS中播放音频文件时显示进度条

Sud*_*uri 1 iphone avfoundation audio-streaming avaudioplayer ios

我在服务器中有一个音频文件,所以我可以用url播放音频文件.下面是代码.如何在播放音频文件时显示进度条?

-(void)playselectedsong{
    AVPlayer *player = [[AVPlayer alloc]initWithURL:[NSURL URLWithString:urlString]];
    [player play];
}
Run Code Online (Sandbox Code Playgroud)

Pra*_*ngh 5

使用URL创建AVAsset,然后获取使用URL创建的AVAsset的持续时间.

AVAsset *audio = [AVAsset assetWithURL:]; // create an audio instance.
float duration = CMTimeGetSeconds([audio currentTime]); // gives the seconds of audio file.

AVPlayerItem *item = [AVPlayerItem playerItemWithAsset: audio]; // create a player item.

AVPlayer *avPlayer = [[AVPlayer alloc] initWithPlayerItem: item]; // initialise the AVPlayer with the AVPlayerItem.

[avPlayer play]; // play the AVPlayer
Run Code Online (Sandbox Code Playgroud)

然后你可以设计进度条,它会在播放音频文件后每秒更新一次.

UIProgressView *myProgressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
Run Code Online (Sandbox Code Playgroud)

每秒后调用一次更新方法.

NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(methodToUpdateProgress) userInfo:nil repeats:YES];
Run Code Online (Sandbox Code Playgroud)

然后在"methodToUpdateProgress"中更新进度条.

[myProgressView setProgress:someFloat animated:YES];
Run Code Online (Sandbox Code Playgroud)