iOS App中实现播放音效和音乐功能的简单示例

播放音效
iOS开发过程中可能会遇到播放音效的功能
其实很简单,iOS已经提供了一个框架直接负责播放音效 AudioToolbox.framework
新建项目  TestWeChatSounds

给新建的项目导入AudioToolbox.framework

导入成功之后如下图

项目目录如下

接下来我们给项目中添加几个caf格式的音效文件

接下来 我们打开 项目默认生成的ViewController中添加代码
导入 AudioToolbox


#import <AudioToolbox/AudioToolbox.h>  


给View上添加button点击之后播放音效

- (void)viewDidLoad {  

    [super viewDidLoad];  

    // Do any additional setup after loading the view, typically from a nib.  

      

    UIButton *btn1=[[UIButton alloc] initWithFrame:CGRectMake(20, 100, 120, 36)];  

    [btn1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];  

    [btn1 setTitle:@"警告" forState:UIControlStateNormal];  

    [btn1 addTarget:self action:@selector(btn1Act) forControlEvents:UIControlEventTouchUpInside];  

    [self.view addSubview:btn1];  

      

    UIButton *btn2=[[UIButton alloc] initWithFrame:CGRectMake(20, 150, 120, 36)];  

    [btn2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];  

    [btn2 setTitle:@"错误" forState:UIControlStateNormal];  

    [btn2 addTarget:self action:@selector(btn2Act) forControlEvents:UIControlEventTouchUpInside];  

    [self.view addSubview:btn2];  

}  


实现播放效果

-(void)btn1Act {  

      

    [self playSoundEffect:@"alarm.caf"];  

}  

-(void)btn2Act {  

      

    [self playSoundEffect:@"ct-error.caf"];  

}  

  

-(void)playSoundEffect:(NSString *)name{  

    NSString *audioFile=[[NSBundle mainBundle] pathForResource:name ofType:nil];  

    NSURL *fileUrl=[NSURL fileURLWithPath:audioFile];  

    //1.获得系统声音ID  

    SystemSoundID soundID=0;  

    /** 

     * inFileUrl:音频文件url 

     * outSystemSoundID:声音id(此函数会将音效文件加入到系统音频服务中并返回一个长整形ID) 

     */  

    AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &soundID);  

    //如果需要在播放完之后执行某些操作,可以调用如下方法注册一个播放完成回调函数  

    AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, soundCompleteCallback, NULL);  

    //2.播放音频  

    AudioServicesPlaySystemSound(soundID);//播放音效  

    //    AudioServicesPlayAlertSound(soundID);//播放音效并震动  

}  

  

void soundCompleteCallback(SystemSoundID soundID,voidvoid * clientData){  

    NSLog(@"播放完成...");  

}  


代码部分截图

好了播放音效基本实现 。


播放音乐
我们同样使用苹果提供的框架 AVFoundation.framework
首先,新建项目

给项目起名: TestAVGoundation

接下来导入framework

导入成功之后如下

项目结构

开始写代码之前,我们找一首歌曲放到项目中
这里我们放一首比较经典的歌曲 周华健的 朋友

同样我们还是打开项目默认生成的ViewController.m 在里面添加播放功能
首先,导入头文件


#import <AVFoundation/AVFoundation.h> 


接下来,创建个控件

@property (nonatomic,strong) AVAudioPlayer *audioPlayer;//播放器  

@property (strong, nonatomic) UIProgressView *playProgress;//播放进度  

@property (strong, nonatomic) UIButton *playOrPause; //播放/暂停按钮(如果tag为0认为是暂停状态,1是播放状态)  

  

@property (strong ,nonatomic) NSTimer *timer;//进度更新定时器  


初始化界面

- (void)viewDidLoad {  

    [super viewDidLoad];  

    // Do any additional setup after loading the view, typically from a nib.  

    self.view.backgroundColor=[UIColor lightGrayColor];  

    [self initUserFace];  

      

}  

  

-(void)initUserFace{  

      

    //添加playProgress  

      

    _playProgress= [[UIProgressView alloc] initWithProgressViewStyle: UIProgressViewStyleDefault];  

      

    _playProgress.frame=CGRectMake(0, 100, self.view.bounds.size.width, 36);  

      

    [self.view addSubview:_playProgress];  

      

    //添加播放按钮  

    _playOrPause=[[UIButton alloc]initWithFrame:CGRectMake(0, 150, 120, 36)];  

    [_playOrPause setTitle:@"播放" forState:UIControlStateNormal];  

    [_playOrPause setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];  

    [_playOrPause addTarget:self action:@selector(playOrPauseAct:) forControlEvents:UIControlEventTouchUpInside];  

    [self.view addSubview:_playOrPause];  

      

}  


添加几个播放,暂停,修改歌曲进度条显示的方法

-(NSTimer *)timer{  

    if (!_timer) {  

        _timer=[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateProgress) userInfo:nil repeats:true];  

    }  

    return _timer;  

}  

  

-(AVAudioPlayer *)audioPlayer{  

    if (!_audioPlayer) {  

        NSString *urlStr=[[NSBundle mainBundle]pathForResource:@"朋友.mp3" ofType:nil];  

        NSURL *url=[NSURL fileURLWithPath:urlStr];  

        NSError *error=nil;  

        //初始化播放器,注意这里的Url参数只能时文件路径,不支持HTTP Url  

        _audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];  

        //设置播放器属性  

        _audioPlayer.numberOfLoops=0;//设置为0不循环  

        _audioPlayer.delegate=self;  

        [_audioPlayer prepareToPlay];//加载音频文件到缓存  

        if(error){  

            NSLog(@"初始化播放器过程发生错误,错误信息:%@",error.localizedDescription);  

            return nil;  

        }  

    }  

    return _audioPlayer;  

}  

  

  

/** 

 *  播放音频 

 */  

-(void)play{  

    if (![self.audioPlayer isPlaying]) {  

        [self.audioPlayer play];  

        self.timer.fireDate=[NSDate distantPast];//恢复定时器  

    }  

}  

  

/** 

 *  暂停播放 

 */  

-(void)pause{  

    if ([self.audioPlayer isPlaying]) {  

        [self.audioPlayer pause];  

        self.timer.fireDate=[NSDate distantFuture];//暂停定时器,注意不能调用invalidate方法,此方法会取消,之后无法恢复  

          

    }  

}  

  

/** 

 *  更新播放进度 

 */  

-(void)updateProgress{  

    float progress= self.audioPlayer.currentTime /self.audioPlayer.duration;  

    [self.playProgress setProgress:progress animated:true];  

}  

  

#pragma mark - 播放器代理方法  

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{  

    NSLog(@"音乐播放完成...");  

      

    [_playOrPause setTitle:@"播放" forState:UIControlStateNormal];  

      

}  


我们给播放按钮添加点击事件

-(void)playOrPauseAct:(UIButton *)sender{  

    NSString *strPlay=sender.titleLabel.text;  

    NSLog(@"strPlay=%@",strPlay);  

    if ([strPlay isEqualToString:@"播放"]) {  

        [sender setTitle:@"暂停" forState:UIControlStateNormal];  

        [self play];  

    }else{  

        [sender setTitle:@"播放" forState:UIControlStateNormal];  

        [self pause];  

    }  

}  


好了,到此 我们创建完成 可以运行试试

仔细的朋友可能发现我们的app播放音乐的过程中 如果切换到后台之后发现音乐暂停了  再次打开 又接着播放了
如果想要后台 也可以接着播放音乐 我们需要修改两个地方
1,打开项目 plist 文件

添加一项

2,打开ViewController.m 找到如下方法 添加一段

好了 试下后台运行吧~

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。