源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2020-06-04 09:40 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:iOS App中实现播放音效和音乐功能的简单示例
[b]播放音效 [/b]iOS开发过程中可能会遇到播放音效的功能 其实很简单,iOS已经提供了一个框架直接负责播放音效 AudioToolbox.framework 新建项目  TestWeChatSounds [img]http://files.jb51.net/file_images/article/201603/201633193440239.png?20162319351[/img] [img]http://files.jb51.net/file_images/article/201603/201633193511334.png?201623193523[/img] 给新建的项目导入AudioToolbox.framework [img]http://files.jb51.net/file_images/article/201603/201633193536489.png?201623193544[/img] [img]http://files.jb51.net/file_images/article/201603/201633193742629.png?201623193756[/img] 导入成功之后如下图 [img]http://files.jb51.net/file_images/article/201603/201633193805421.png?201623193815[/img] 项目目录如下 [img]http://files.jb51.net/file_images/article/201603/201633193846873.png?201623193855[/img] 接下来我们给项目中添加几个caf格式的音效文件 [img]http://files.jb51.net/file_images/article/201603/201633193904175.png?201623193916[/img] 接下来 我们打开 项目默认生成的ViewController中添加代码 导入 AudioToolbox
[u]复制代码[/u] 代码如下:
#import <AudioToolbox/AudioToolbox.h> 
给View上添加button点击之后播放音效
[u]复制代码[/u] 代码如下:
- (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];  } 
实现播放效果
[u]复制代码[/u] 代码如下:
-(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(@"播放完成...");  } 
代码部分截图 [img]http://files.jb51.net/file_images/article/201603/201633193930760.jpg?201623193941[/img] 好了播放音效基本实现 。 [b]播放音乐 [/b]我们同样使用苹果提供的框架 AVFoundation.framework 首先,新建项目 [img]http://files.jb51.net/file_images/article/201603/201633193953166.png?20162319407[/img] 给项目起名: TestAVGoundation [img]http://files.jb51.net/file_images/article/201603/201633194017611.png?201623194025[/img] 接下来导入framework [img]http://files.jb51.net/file_images/article/201603/201633194046751.png?201623194053[/img] 导入成功之后如下 [img]http://files.jb51.net/file_images/article/201603/201633194102800.png?201623194110[/img] 项目结构 [img]http://files.jb51.net/file_images/article/201603/201633194126690.png?201623194135[/img] 开始写代码之前,我们找一首歌曲放到项目中 这里我们放一首比较经典的歌曲 周华健的 朋友 [img]http://files.jb51.net/file_images/article/201603/201633194145282.png?201623194153[/img] 同样我们还是打开项目默认生成的ViewController.m 在里面添加播放功能 首先,导入头文件
[u]复制代码[/u] 代码如下:
#import <AVFoundation/AVFoundation.h>
接下来,创建个控件
[u]复制代码[/u] 代码如下:
@property (nonatomic,strong) AVAudioPlayer *audioPlayer;//播放器  @property (strong, nonatomic) UIProgressView *playProgress;//播放进度  @property (strong, nonatomic) UIButton *playOrPause; //播放/暂停按钮(如果tag为0认为是暂停状态,1是播放状态)    @property (strong ,nonatomic) NSTimer *timer;//进度更新定时器 
初始化界面
[u]复制代码[/u] 代码如下:
- (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];        } 
添加几个播放,暂停,修改歌曲进度条显示的方法
[u]复制代码[/u] 代码如下:
-(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];        } 
我们给播放按钮添加点击事件
[u]复制代码[/u] 代码如下:
-(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 文件 [img]http://files.jb51.net/file_images/article/201603/201633194211928.png?201623194219[/img] 添加一项 [img]http://files.jb51.net/file_images/article/201603/201633194233047.png?201623194241[/img] 2,打开ViewController.m 找到如下方法 添加一段 [img]http://files.jb51.net/file_images/article/201603/201633194347772.jpg?201623194356[/img] 好了 试下后台运行吧~
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部