我正在制作一个播放音频的应用程序。我使用滑块在滑块中以图形方式显示已用时间和剩余时间。但我没有得到如何获得该值的程序。我使用了以下代码但是它抛出异常。
-(void) updateMyProgress
{
float progress = [avPlayer currentTime]/[avPlayer duration];
self.myProgressView.progress = progress;
}
我的viewcontoller.m文件的代码是
#import "ViewController.h"
@interface ViewController ()
{
AVAudioPlayer *avPlayer;
AVPlayer *avp;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *stringPath = [[NSBundle mainBundle]pathForResource:@"naat" ofType:@"mp3"];
NSURL *url = [NSURL fileURLWithPath:stringPath];
NSError *error;
avPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
[avPlayer setNumberOfLoops:2];
[avPlayer setVolume:self.sliderVolumeOutlet.value];
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateMyProgress) userInfo:nil repeats:YES];
}
/*-(void) updateMyProgress
{
CGFloat progress = [avPlayer currentTime]/[avPlayer duration];
self.myProgressView.progress = progress;
}
*/
-(void) updateMyProgress
{
AVPlayerItem *currentItem = avp.currentItem ;
CMTime duration = currentItem.duration; //total time
CMTime currentTime = currentItem.currentTime; //playing time
CGFloat progress = currentTime.value/duration.value;
self.myProgressView.progress = progress;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)sliderVolumeAction:(id)sender
{
UISlider *myslider= sender;
[avPlayer setVolume:myslider.value];
}
- (IBAction)stopButton:(id)sender
{
[avPlayer stop];
[avPlayer setCurrentTime:0];
}
- (IBAction)pauseButton:(id)sender
{
[avPlayer pause];
}
- (IBAction)playButton:(id)sender
{
[avPlayer play];
}
@end![enter image description here][1]
附图显示了例外的屏幕截图
答案 0 :(得分:1)
- (void)updateMyProgress
{ AVPlayerItem *currentItem = avPlayer.currentItem; CMTime duration = currentItem.duration; //total time CMTime currentTime = currentItem.currentTime; //playing time CGFloat progress = currentTime.value/duration.value; self.myProgressView.progress = progress; }