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

2020-01-14 22:32:38王冬梅

    [_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];//恢复定时器