使用AVAudioPlayer播放 引用AVFoundation类库
MainContoller.h代码:
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface MainController : UIViewController<AVAudioPlayerDelegate>
{
AVAudioPlayer *audioPaly;
}
@property (retain, nonatomic) IBOutlet UISlider *volumeSlider;
@property (retain, nonatomic) IBOutlet UILabel *timeLabel;
@property (retain, nonatomic) IBOutlet UISlider *currentTimeSlider;
- (IBAction)volumerAction:(id)sender;
- (IBAction)currentChange:(id)sender;
@property (retain, nonatomic) IBOutlet UIButton *btnPaly;
- (IBAction)btnPlay:(id)sender;
@end
MainContoller.h代码:
#import "MainController.h"
@interface MainController ()
@end
@implementation MainController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *path=[[NSBundle mainBundle]pathForResource:@"感谢" ofType:@"MP3"];
NSURL *url=[NSURL fileURLWithPath:path];
audioPaly=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
//设置delegate
audioPaly.delegate=self;
//准备播放
[audioPaly prepareToPlay];
//设置音量的最大最小值
self.volumeSlider.minimumValue=0;
self.volumeSlider.maximumValue=1;
double allTime=audioPaly.duration;//总时长
//设置进度的最值
self.currentTimeSlider.minimumValue=0;
self.currentTimeSlider.maximumValue=allTime;//总时长
if (self.currentTimeSlider.value <allTime) {
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
}
if ([audioPaly play]) {
NSLog(@"开始播放");
}
if (audioPaly.playing) {
[self.btnPaly setTitle:@"暂停" forState:UIControlStateNormal];
}
}
-(void)timerAction:(NSTimer *)timer
{
double currentTime=audioPaly.currentTime;
//可以设置为分钟的形式
self.timeLabel.text=[[NSString alloc]initWithFormat:@"%.2f/%.2f",currentTime,audioPaly.duration];
self.currentTimeSlider.value=audioPaly.currentTime;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc {
[_volumeSlider release];
[_timeLabel release];
[_currentTimeSlider release];
[_btnPaly release];
[super dealloc];
}
- (IBAction)volumerAction:(id)sender {
audioPaly.volume=self.volumeSlider.value;
}
- (IBAction)currentChange:(id)sender {
audioPaly.currentTime=self.currentTimeSlider.value;
}
- (IBAction)btnPlay:(id)sender {
if (audioPaly.playing) {
[audioPaly pause];
[self.btnPaly setTitle:@"播放" forState:UIControlStateNormal];
}
else
{
[audioPaly play];
[self.btnPaly setTitle:@"暂停" forState:UIControlStateNormal];
}
}
#pragma mark----AvAudioPlayDlegate
/* audioPlayerDidFinishPlaying:successfully: is called when a sound has finished playing. This method is NOT called if the player is stopped due to an interruption. */
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
NSLog(@"播放结束");
}
@end
.xib文件布局