iOS AVAudioPlayer简单的MP3播放

- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setFrame:CGRectMake(100, 100, 60, 40)];
    [button setTitle:@"Play" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(play) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button1 setFrame:CGRectMake(100, 150, 60, 40)];
    [button1 setTitle:@"pause" forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(pause) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button1];
    
     UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button2 setFrame:CGRectMake(100, 200, 60, 40)];
    [button2 setTitle:@"stop" forState:UIControlStateNormal];
    [button2 addTarget:self action:@selector(stop) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button2];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"MP3Sample" ofType:@"mp3"];
    NSURL *url = [NSURL URLWithString:path];
    //每个AVAudioPlayer只能播放一个音乐文件,如果需要播放多次,需要创建多次
    self.avAudioPalayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    self.avAudioPalayer.delegate = self;
    self.avAudioPalayer.volume = 1;//初始化音量
    self.avAudioPalayer.numberOfLoops = -1;//设置音乐播放次数  -1为一直循环
    [self.avAudioPalayer prepareToPlay];//预播放
    
    self.progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(20, 50, 200, 20)];
    [self.view addSubview:self.progressView];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(playProgress) userInfo:nil repeats:YES];
    
    self.slider = [[UISlider alloc]initWithFrame:CGRectMake(20, 70, 200, 20)];
    [self.slider addTarget:self action:@selector(volumeChange)
                          forControlEvents:UIControlEventValueChanged];
    self.slider.minimumValue = 1.0;
    self.slider.maximumValue = 10.0;
    self.slider.value = 5.0;
    [self.view addSubview:self.slider];
}
- (void)volumeChange
{
    self.avAudioPalayer.volume = self.slider.value;
}
- (void)playProgress
{

    self.progressView.progress = self.avAudioPalayer.currentTime/self.avAudioPalayer.duration;
}
- (void)play
{
    [self.avAudioPalayer play];
}
- (void)pause
{
    [self.avAudioPalayer pause];
}
- (void)stop
{
    self.avAudioPalayer.currentTime = 0;
    [self.avAudioPalayer stop];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [self.timer invalidate];
}

允许效果

技术分享

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。