OC 音频播放(AVPlayer等)

录音

NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    NSString *fullPath = [path stringByAppendingPathComponent:@"test.caf"];
    NSURL *url = [NSURL URLWithString:fullPath];
    
    NSMutableDictionary *recordSettings = [NSMutableDictionary dictionary];
    
    //编码格式
    [recordSettings setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
    // 采样率
    [recordSettings setValue :[NSNumber numberWithFloat:11025.0] forKey: AVSampleRateKey];
    // 通道数
    [recordSettings setValue :[NSNumber numberWithInt:2] forKey: AVNumberOfChannelsKey];
    //音频质量,采样质量
    [recordSettings setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];

    AVAudioRecorder *recorder = [[AVAudioRecorder alloc]initWithURL:url settings:recordSettings error:nil];

    //2. prepare to record
    [recorder prepareToRecord];
    
    //3. 开始录音
    [recorder record];  // 直接录音, 需要手动停止
    [recorder recordForDuration:5];  // 从当前执行这行代码开始录音, 录音5秒
    [recorder recordAtTime:recorder.deviceCurrentTime + 2]; // 2s后录音, 需要手动停止
    
    [recorder recordAtTime:recorder.deviceCurrentTime + 2 forDuration:5];
播放声音
  • 导入框架
#import 

    //1. 需要播放的url
    NSURL *url = [[NSBundle mainBundle]URLForResource:@"m_17.wav" withExtension:nil];
    CFURLRef urlRef = (__bridge CFURLRef)(url);
    
    //2. 创建SystemSoundID
    SystemSoundID soundID;  //类型: typedef unsigned int UInt32;
    AudioServicesCreateSystemSoundID(urlRef, &soundID);
    
    //1. 创建another SystemSoundID
    NSURL *url2 = [[NSBundle mainBundle]URLForResource:@"win.aac" withExtension:nil];
    CFURLRef urlRef2 = (__bridge CFURLRef)url2;
    SystemSoundID soundID2;
    AudioServicesCreateSystemSoundID(urlRef2, &soundID2);
    
    //3. 播放
//    AudioServicesPlayAlertSoundWithCompletion(soundID, ^{
//    AudioServicesDisposeSystemSoundID(soundID);
//        NSLog(@"播放over");
//    });
    
    //3. 播放完一个音频,紧接着播放另外一个音频
    AudioServicesPlayAlertSoundWithCompletion(soundID, ^{
        
        //url播放完毕,释放
        AudioServicesDisposeSystemSoundID(soundID);
       
        AudioServicesPlaySystemSoundWithCompletion(soundID2, ^{
            
            //url2播放完毕,释放soundID2
            AudioServicesDisposeSystemSoundID(soundID2);
            NSLog(@"播放2个音频完毕");
        });
    });
播放本地音乐
- (AVAudioPlayer *)player{
    if (!_player) {
        
        // 1. 创建播放器对象
        // 虽然传递的参数是NSURL地址, 但是只支持播放本地文件, 远程音乐文件路径不支持
        NSURL *url = [[NSBundle mainBundle]URLForResource:@"简单爱.mp3" withExtension:nil];
        _player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
        
        //允许调整速率,此设置必须在prepareplay 之前
        _player.enableRate = YES;
        _player.delegate = self;
        
        [_player prepareToPlay];
        
    }
    return _player;
}
- (IBAction)startPlay {
    [self.player play];
}

- (IBAction)pause {
    
    [self.player pause];
}

- (IBAction)stop {
    
    [self.player stop];
    //为保证下次start时,从头播放.self.currentTime需要设置为0,因为系统不会重置.
    self.player.currentTime = 0;
    
    //或者清空player
    self.player = nil;
}

- (IBAction)forward5Seconds {
    
    self.player.currentTime += 5;
}

- (IBAction)back5Seconds {
    
    self.player.currentTime -= 5;
}

- (IBAction)times2Faster {
    
    self.player.rate = 2;
}

- (IBAction)volume:(UISlider *)sender {
    
    //音量
    self.player.volume = sender.value;
}
#pragma mark ------------------------------------------
#pragma mark AVAudioPlayerDelegate 监听播放完成
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    
    //flag 表示是否播放有错误
    if (flag) {
        NSLog(@"play completed successfully");
    }
}

#pragma mark ------------------------------------------
#pragma mark 实现后台播放
//注:模拟器不准确:如果不设置,在真机中,无法后台播放
- (void)backPlay{
    
    //1.获取音频会话
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    
    //2.设置音频播放模式
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    //3.激活音频会话
    [audioSession setActive:YES error:nil];
}
AVPlayer异步播放
- (void)asyncPlay:(AVURLAsset *)asset{
    NSArray *keys = @[@"playable", @"tracks",@"duration"];
    [asset loadValuesAsynchronouslyForKeys:keys completionHandler:^{
        
        AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            self.playerItem = item;
            if (self.player) {
                
                [self.player replaceCurrentItemWithPlayerItem:item];
            }else{
                self.player = [AVPlayer playerWithPlayerItem:item];
                if ([YHIphoneTool yh_iphoneVersion:10]) {
                    self.player.automaticallyWaitsToMinimizeStalling = NO;
                }
            }
            
            if ([self.delegate respondsToSelector:@selector(remotePlayerDidFinishAsyncLoadValues:)]) {
                [self.delegate remotePlayerDidFinishAsyncLoadValues:self];
            }
        });
        
        
        NSError *error = nil;
        AVKeyValueStatus status =
        [asset statusOfValueForKey:@"playable" error:&error];
        switch (status) {
            case AVKeyValueStatusLoaded:
                // Sucessfully loaded, continue processing
                YHLog(@"Sucessfully loaded");
//                [self.player play];
                break;
            case AVKeyValueStatusFailed:
                // Examine NSError pointer to determine failure
                YHLog(@"fail loaded, %@", error.description);
                break;
            case AVKeyValueStatusCancelled:
                // Loading cancelled
                YHLog(@"cancel loaded");
                break;
            default:
                // Handle all other cases
                break;
        }
    }];
    
}

你可能感兴趣的:(OC 音频播放(AVPlayer等))