首页 > 学院 > 开发设计 > 正文

UI音乐播放之初级篇AVAudioPlayer

2019-11-14 18:29:42
字体:
来源:转载
供稿:网友

/*

 不是技术性的文章,只是自己记录每天所学的方式。

                                 -----------------------程序员的天空是去往星辰和大海

*/

 

-1-同样作为播放音乐文件的类,AvAudioPlayer音乐播放器常用于:

   1.时间较长的音乐文件播放

   2.可在音乐播放过程中进行操作

   3.需要执行循环播放,播放暂停等要求

   4.需要改变声音音道等属性

-2-准备工作:

    1>导入AVFoundation.framework系统类库

   2>关联头文件  #import <AVFoundation/AVFoundation.h>

 

        

-3-AVAudioPlayer的常用属性和基本方法

       初始化方法:

      _avPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];

   准备方法

       [_avPlayer PRepareToPlay];

       开始播放歌曲

       [_avPlayer play];

   暂停播放的方法 

        [_avPlayer stop];

        判断是否正在播放的方法

        [_avPlayer isPlaying]

       常用属性

       duration :当前加载歌曲的总时长 为基本数据类型

      currentTime  当前播放进度时间 也为基本数据类型

【特别注意】使用AVAudioPlayer需要注意一下几点

         1. 每次加载歌曲,都必须将当前加载数据内容销毁 ,这是因为AVAudioPlayer每次有且只能加载一个文件

                if([_avPlayer isPlaying]){

                   [_avPlayer stop];

                  _avPlayer=nil;

                 }

                2.当设置了AVAudioPlayer代理方法时,必须在每次重新加载文件时,重新设置代理,这是因为_avPlayer=nil造成的

 

 -4-简单的代码实现一个小型的音乐播放器

                                    支持循环播放,音量调节,下一首播放 播放暂停及重新启动等功能

 

////  RootViewController.m//  GGAvAudioPlayer////  Created by MS on 15-8-18.//  Copyright (c) 2015年 GG. All rights reserved.//#import "RootViewController.h"@interface RootViewController ()<UITableViewDataSource,UITableViewDelegate,AVAudioPlayerDelegate>{    UITableView * _tableView;    NSMutableArray * _dataArray;    NSString * songName;    AVAudioPlayer * _avPlayer;}@end@implementation RootViewController- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];    if (self) {           }    return self;}- (void)viewDidLoad{    [super viewDidLoad];    [self creatDataSource];    [self creatUI];}//从plist文件中获取播放列表-(void)creatDataSource{    _dataArray=[[NSMutableArray alloc]init];    NSString * str=[[NSBundle mainBundle]pathForResource:@"songsName" ofType:@"plist"];    NSArray * arr=[NSArray arrayWithContentsOfFile:str];    [_dataArray addObjectsFromArray:arr];    //songName 为当前播放歌曲名    songName=_dataArray[0];}//创建音乐列表UI-(void)creatUI{    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 90, 320, 320) style:UITableViewStylePlain];    _tableView.delegate=self;    _tableView.dataSource=self;    [self.view addSubview:_tableView];        _nameLabel.text=songName;    //通过url高效的加载播放歌曲    NSURL * url=[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:songName ofType:@"mp3"]];    _avPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];    _avPlayer.delegate=self;    [_avPlayer prepareToPlay];}#pragma mark - UITableViewDelegate-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    return  _dataArray.count;}-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    static NSString * cellName=@"cellName";    UITableViewCell * cell=[tableView dequeueReusableCellWithIdentifier:cellName];    if(!cell){        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];    }    cell.textLabel.text=_dataArray[indexPath.row];    return cell;}-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    return 40.0f;}-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{    songName=[_dataArray objectAtIndex:indexPath.row];    _nameLabel.text=[_dataArray objectAtIndex:indexPath.row];    NSURL * url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:_nameLabel.text ofType:@"mp3" ]];    if([_avPlayer isPlaying]){             [_avPlayer stop];        _avPlayer=nil;    }    _avPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];    [_avPlayer prepareToPlay];    [_avPlayer play];}- (void)didReceiveMemoryWarning{    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}- (IBAction)volumeChanged:(id)sender {    UISlider * slider=(UISlider *)sender;    _avPlayer.volume=slider.value * 20;}- (IBAction)progressChanged:(id)sender {    UISlider * slider=(UISlider *)sender;    _avPlayer.currentTime=slider.value*_avPlayer.duration;    [self playBtn:nil];   }- (IBAction)playBtn:(id)sender {    [_avPlayer play];    //加入计时器,计时为1秒    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeChanged) userInfo:nil repeats:YES];}-(void)timeChanged{    NSInteger allTime = _avPlayer.duration;    NSInteger MM=allTime/60;    NSInteger SS=allTime%60;    NSInteger currtentTime=_avPlayer.currentTime;    NSInteger mm=currtentTime/60;    NSInteger ss=currtentTime%60;    NSString * str=[NSString stringWithFormat:@"%02d:%02d/%02d:%02d",mm,ss,MM,SS];    self.timeLabel.text=str;     self.progressSlider.value=_avPlayer.currentTime/_avPlayer.duration;}- (IBAction)nextBtn:(id)sender {    NSInteger index = [_dataArray indexOfObject:songName];    if(index==_dataArray.count){        index=0;    }else{        index ++;    }    songName=_dataArray[index];    _nameLabel.text=songName;     NSURL * url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource: songName ofType:@"mp3" ]];    if([_avPlayer isPlaying]){        [_avPlayer stop];        _avPlayer=nil;    }    _avPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];    _avPlayer.delegate=self;    [_avPlayer prepareToPlay];    [_avPlayer play];}- (IBAction)stopBtn:(id)sender {    if([_avPlayer isPlaying]){        [_avPlayer stop];    }}#pragma mark - AVAudioPlayer-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{    if([_avPlayer isPlaying]){        [_avPlayer stop];        _avPlayer=nil;    }    NSInteger index = [_dataArray indexOfObject:songName];    if(index==_dataArray.count){        index=0;    }else{        index ++;    }    songName=_dataArray[index];    _nameLabel.text=songName;    NSURL * url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource: songName ofType:@"mp3" ]];    _avPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];    _avPlayer.delegate=self;    [_avPlayer prepareToPlay];    [self playBtn:nil];    }@end

 


上一篇:iOS动画——CoreAnimation

下一篇:图像处理

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表