美文网首页
ios开发录音,转换(lame),本地音乐播放,网络音乐播放

ios开发录音,转换(lame),本地音乐播放,网络音乐播放

作者: Flynn_Lee | 来源:发表于2019-05-17 14:07 被阅读0次

一、录音
1、创建录音

#import "recordingController.h"
#import <AVFoundation/AVFoundation.h>
#import "ConvertAudioFile.h"
#import <lame/lame.h>
@interface recordingController ()<AVAudioRecorderDelegate,AVAudioPlayerDelegate>
/** 录音对象*/
@property(nonatomic ,strong) AVAudioRecorder *recorder;
/**
 音乐播放器
 */
@property(nonatomic,strong)AVAudioPlayer *musicPlayer;
/**
 保存录音caf文件路径
 */
@property(nonatomic,copy)NSString *filePath;
/**
存放转换后mp3文件路径
 */
@property(nonatomic,copy)NSString *mp3FilePath;
@end

- (void)createRecord{
  // 0.1 创建录音文件存放路径
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"test.caf"];
    
    self.filePath = path;
    NSURL *url = [NSURL URLWithString:self.filePath];
    
    // 0.2 创建录音设置
    NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] init];
    // 设置编码格式
    [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:16] forKey:AVLinearPCMBitDepthKey];
    //音频质量,采样质量
    [recordSettings setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
    
    // 1. 创建录音对象
    self.recorder = [[AVAudioRecorder alloc] initWithURL:url settings:recordSettings error:nil];
    
    // 2. 准备录音(系统会分配一些录音资源)
    [self.recorder prepareToRecord];
}

2、开始录音方法

-(void)beginRecord
{
//    NSLog(@"开始录音");
    [self.recorder record]; // 直接录音, 需要手动停止
//倒计时停止方法
    [self startTimeToEnd];
}

3、暂停录音

-(void)pauseRecord:(id)sender
{
//    NSLog(@"暂停录音");
    [self.recorder pause];
}

4、停止录音

-(void)stopRecord
{
//    NSLog(@"停止录音");
    [self.recorder stop];
    
//时间显示还原
    self.timeLabel.text = @"60\"";
    
//录音caf转mp3方法
    [self audio_PCMtoMP3:self.filePath andMP3FilePath:self.mp3FilePath];
    dispatch_source_cancel(self.timer);
}

二、录音格式caf转MP3
1、转换方法实现

//caf格式转编码为mp3
- (void)audio_PCMtoMP3:(NSString *)cafFilePath andMP3FilePath:(NSString *)mp3FilePath
{
    NSFileManager* fileManager=[NSFileManager defaultManager];
    if([fileManager removeItemAtPath:mp3FilePath error:nil]) {
        NSLog(@"---------删除");
    }
    
    @try {
        int read, write;
        
        FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb");  //source 被转换的音频文件位置
        
        if(pcm == NULL) {
            NSLog(@"file not found");
        } else {
            fseek(pcm, 4*1024, SEEK_CUR);                                   //skip file header
            FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");  //output 输出生成的Mp3文件位置
            
            const int PCM_SIZE = 8192;
            const int MP3_SIZE = 8192;
            short int pcm_buffer[PCM_SIZE*2];
            unsigned char mp3_buffer[MP3_SIZE];
            
            lame_t lame = lame_init();
            lame_set_in_samplerate(lame, 11025.0);
            lame_set_VBR(lame, vbr_default);
            lame_init_params(lame);
            
            do {
                read = fread(pcm_buffer, 2 * sizeof(short int), PCM_SIZE, pcm);
                if (read == 0)
                    write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
                else
                    write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
                
                fwrite(mp3_buffer, write, 1, mp3);
                
            } while (read != 0);
            
            lame_close(lame);
            fclose(mp3);
            fclose(pcm);
        }
    }
    @catch (NSException *exception) {
        NSLog(@"%@",[exception description]);
    }
    @finally {
//        NSLog(@"MP3生成成功");
       
    }
}

2、导入lame第三方
lame下载链接: https://pan.baidu.com/s/1Nbix55TdnHDPPNu9AVt8vw 提取码: ke9g

直接拖入工程内


image.png
image.png

3、播放本地音乐

//播放本地音乐
-(void)playAudioWithUrl:(NSURL*)url{

    NSString *mp3FileName = @"Mp3File";
    mp3FileName = [mp3FileName stringByAppendingString:@".mp3"];
    NSString *mp3FilePath = [[NSHomeDirectory() stringByAppendingFormat:@"/Documents/"] stringByAppendingPathComponent:mp3FileName];
    // 2. 创建音乐播放对象
    self.musicPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:mp3FilePath] error:nil];
    
    // 3.准备播放 (音乐播放的内存空间的开辟等功能)  不写这行代码直接播放也会默认调用prepareToPlay
    
    if (![self.musicPlayer isPlaying]){
        [self.musicPlayer setVolume:0.6];
        [self.musicPlayer prepareToPlay];
        [self.musicPlayer play];
    }

}
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    NSLog(@"音乐播放完成...");
}

4、播放网络音乐

//音乐播放方法
-(void)playMusicMethod:(NSString *)urlString
{
    NSURL * url = [NSURL URLWithString:urlString];
     self.player = [[AVPlayer alloc]initWithURL:url];
    if (self.player.status == AVPlayerStatusReadyToPlay) {
        self.player.volume = 1.0f;
        
    }
}

//播放方法
-(void)musicPlay
{
    [self.player play];
}

//停止方法
-(void)musicStop
{
    [self.player stop];
}

//暂停方法
-(void)musicPause
{
    [self.player pause];
}

相关文章

网友评论

      本文标题:ios开发录音,转换(lame),本地音乐播放,网络音乐播放

      本文链接:https://www.haomeiwen.com/subject/vkvnaqtx.html