【iOS】音频系统方法格式转换,获取音频信息获取

2024-09-01 23:18

本文主要是介绍【iOS】音频系统方法格式转换,获取音频信息获取,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

直接上代码

  • .h
#import <MobileCoreServices/MobileCoreServices.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AudioUnit/AudioUnit.h>
#import <AVFoundation/AVFoundation.h>/// ogg,amr,acc 格式无法使用
@interface YSAudioTool : NSObject
+ (AudioFileID)getAudioFileID:(NSURL *)fileUrl;
+ (NSDictionary *)getAuidoBaseInfo:(AudioFileID)audioId;
+ (NSString *)getFileFormat:(AudioFileID)audioId showNormalType:(BOOL)flag;
+ (void)playAuido:(NSURL *)fileUrl;
@end
  • .m
#import "YSAudioTool.h"@interface YSAudioTool()
+ (NSString *)fileFormatCovert:(NSString*)file;
@end@implementation YSAudioTool+ (AudioFileID)getAudioFileID:(NSURL *)fileUrl {AudioFileID fileID;AudioFileOpenURL((__bridge CFURLRef)fileUrl, kAudioFileReadWritePermission,kAudioFileWAVEType, &fileID);return fileID;
}/// 获取音频信息, 编码.声道数.采样率
/// @param audioId  音频文件id
+ (NSDictionary *)getAuidoBaseInfo:(AudioFileID)audioId {NSMutableDictionary * result = [NSMutableDictionary new];UInt32 formatListSize = 0;OSStatus status = AudioFileGetPropertyInfo(audioId, kAudioFilePropertyFormatList, &formatListSize, NULL);if (status == noErr) {AudioFormatListItem *formatList = (AudioFormatListItem *)malloc(formatListSize);status = AudioFileGetProperty(audioId, kAudioFilePropertyFormatList, &formatListSize, formatList);for (int i = 0; i * sizeof(AudioFormatListItem) < formatListSize; i += sizeof(AudioFormatListItem)){AudioStreamBasicDescription pasbd = formatList[i].mASBD;//选择需要的格式。。switch (pasbd.mFormatID) {case kAudioFormatAC3:result[@"acodec"] = @"aac";break;case kAudioFormatOpus:result[@"acodec"] = @"opus";break;case kAudioFormatLinearPCM:result[@"acodec"] = @"pcm";break;case kAudioFormatMPEGLayer3:result[@"acodec"] = @"mp3";break;default:result[@"acodec"] = @"unknow";break;}UInt32 channel = pasbd.mChannelsPerFrame;   // 声道result[@"channelNumber"] = @(channel);result[@"sampleRate"] = @(pasbd.mSampleRate);free(formatList);}}return result;
}/// 获取音频 文件类型
/// @param audioId  音频文件id
+ (NSString *)getFileFormat:(AudioFileID)audioId showNormalType:(BOOL)flag {char * result ;UInt32 formatListSize = 0;OSStatus status = AudioFileGetPropertyInfo(audioId, kAudioFilePropertyFileFormat, &formatListSize, NULL);result = (char *)malloc(formatListSize);status = AudioFileGetProperty(audioId, kAudioFilePropertyFileFormat, &formatListSize, result);NSMutableString *tranformFormat = [NSMutableString new];for (long i = strlen(result) -1; i >= 0; i--) {[tranformFormat appendFormat:@"%c", result[i]];}if (flag) {return [YSAudioTool fileFormatCovert:tranformFormat];}return tranformFormat;
}+ (NSString *)fileFormatCovert:(NSString*)file {NSDictionary *params = @{@"MPG3": @"mp3",@"WAVE": @"wav",@"MPG3": @"mp3"};return params[file];
}+ (void)playAuido:(NSURL *)fileUrl {SystemSoundID soundID;AudioServicesCreateSystemSoundID((__bridge CFURLRef)fileUrl, &soundID);AudioServicesPlaySystemSound(soundID);
}/**把mp3->wav; wav->wav;格式(ogg 不能转换,acc 不能转换)@param originalUrlStr .m4a文件路径@param destUrlStr .wav文件路径@param completed 转化完成的block*/
+ (void)convetM4aToWav:(NSString *)originalUrlStrdestUrl:(NSString *)destUrlStrcompleted:(void (^)(NSError *error)) completed {if ([[NSFileManager defaultManager] fileExistsAtPath:destUrlStr]) {[[NSFileManager defaultManager] removeItemAtPath:destUrlStr error:nil];}NSURL *originalUrl = [NSURL fileURLWithPath:originalUrlStr];NSURL *destUrl     = [NSURL fileURLWithPath:destUrlStr];AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:originalUrl options:nil];NSLog(@"finallUrl: %@", destUrl);//读取原始文件信息NSError *error = nil;AVAssetReader *assetReader = [AVAssetReader assetReaderWithAsset:songAsset error:&error];NSArray<AVMetadataItem *> *a = assetReader.asset.metadata;for (int i = 0; i < a.count; i++) {NSString* type =  a[i].dataType;NSLog(@"%@", type);}NSArray<AVMetadataFormat> * b = assetReader.asset.availableMetadataFormats;for (int i = 0; i < b.count; i++) {NSString* type =  b[i].pathExtension;NSLog(@"%@", type);}AVMediaSelection *selection = assetReader.asset.preferredMediaSelection;NSArray<AVMetadataItem *> *c = selection.asset.metadata;for (int i = 0; i < a.count; i++) {NSString* type =  c[i].dataType;NSLog(@"%@", type);}// 采样率CMTimeScale sample = assetReader.asset.duration.timescale;NSLog(@"asdfasdfsdf %d", sample);if (songAsset.tracks.count <= 0) {return;}AVAssetReaderOutput *assetReaderOutput = [AVAssetReaderAudioMixOutputassetReaderAudioMixOutputWithAudioTracks:songAsset.tracksaudioSettings: nil];if (![assetReader canAddOutput:assetReaderOutput]) {NSLog(@"can't add reader output... die!");completed(error);return;}[assetReader addOutput:assetReaderOutput];AVAssetWriter *assetWriter = [AVAssetWriter assetWriterWithURL:destUrlfileType:AVFileTypeWAVEerror:&error];if (error) {NSLog(@"error: %@", error);completed(error);return;}AudioChannelLayout channelLayout;memset(&channelLayout, 0, sizeof(AudioChannelLayout));channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;NSDictionary *outputSettings = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,[NSNumber numberWithFloat:8000], AVSampleRateKey,[NSNumber numberWithInt:1], AVNumberOfChannelsKey,[NSNumber numberWithInt:16], AVLinearPCMBitDepthKey,[NSNumber numberWithBool:NO], AVLinearPCMIsNonInterleaved,[NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,[NSNumber numberWithBool:NO], AVLinearPCMIsBigEndianKey,nil];AVAssetWriterInput *assetWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeAudiooutputSettings:outputSettings];if ([assetWriter canAddInput:assetWriterInput]) {[assetWriter addInput:assetWriterInput];} else {NSLog(@"can't add asset writer input... die!");if (completed != nil) {completed(error);}return;}assetWriterInput.expectsMediaDataInRealTime = NO;[assetWriter startWriting];[assetReader startReading];AVAssetTrack *soundTrack = [songAsset.tracks objectAtIndex:0];CMTime startTime = CMTimeMake (0, soundTrack.naturalTimeScale);[assetWriter startSessionAtSourceTime:startTime];__block UInt64 convertedByteCount = 0;dispatch_queue_t mediaInputQueue = dispatch_queue_create("mediaInputQueue", NULL);[assetWriterInput requestMediaDataWhenReadyOnQueue:mediaInputQueueusingBlock: ^{while (assetWriterInput.readyForMoreMediaData) {CMSampleBufferRef nextBuffer = [assetReaderOutput copyNextSampleBuffer];if (nextBuffer) {// append buffer[assetWriterInput appendSampleBuffer: nextBuffer];NSLog(@"appended a buffer (%zu bytes)",CMSampleBufferGetTotalSampleSize (nextBuffer));convertedByteCount += CMSampleBufferGetTotalSampleSize (nextBuffer);} else {[assetWriterInput markAsFinished];[assetWriter finishWritingWithCompletionHandler:^{}];[assetReader cancelReading];NSDictionary *outputFileAttributes = [[NSFileManager defaultManager]attributesOfItemAtPath:[destUrl path]error:nil];NSLog(@"FlyElephant %lld",[outputFileAttributes fileSize]);break;}}NSLog(@"转换结束");// 删除临时temprecordAudio.m4a文件NSError *removeError = nil;if ([[NSFileManager defaultManager] fileExistsAtPath:originalUrlStr]) {BOOL success = [[NSFileManager defaultManager] removeItemAtPath:originalUrlStr error:&removeError];if (!success) {NSLog(@"删除临时temprecordAudio.m4a文件失败:%@",removeError);completed(removeError);}else{NSLog(@"删除临时temprecordAudio.m4a文件:%@成功",originalUrlStr);if (completed != nil) {completed(removeError);}}}}];
}@end

您的一举一动都是对我的莫大支持

这篇关于【iOS】音频系统方法格式转换,获取音频信息获取的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1128327

相关文章

Nginx设置连接超时并进行测试的方法步骤

《Nginx设置连接超时并进行测试的方法步骤》在高并发场景下,如果客户端与服务器的连接长时间未响应,会占用大量的系统资源,影响其他正常请求的处理效率,为了解决这个问题,可以通过设置Nginx的连接... 目录设置连接超时目的操作步骤测试连接超时测试方法:总结:设置连接超时目的设置客户端与服务器之间的连接

Java判断多个时间段是否重合的方法小结

《Java判断多个时间段是否重合的方法小结》这篇文章主要为大家详细介绍了Java中判断多个时间段是否重合的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录判断多个时间段是否有间隔判断时间段集合是否与某时间段重合判断多个时间段是否有间隔实体类内容public class D

Python使用国内镜像加速pip安装的方法讲解

《Python使用国内镜像加速pip安装的方法讲解》在Python开发中,pip是一个非常重要的工具,用于安装和管理Python的第三方库,然而,在国内使用pip安装依赖时,往往会因为网络问题而导致速... 目录一、pip 工具简介1. 什么是 pip?2. 什么是 -i 参数?二、国内镜像源的选择三、如何

IDEA编译报错“java: 常量字符串过长”的原因及解决方法

《IDEA编译报错“java:常量字符串过长”的原因及解决方法》今天在开发过程中,由于尝试将一个文件的Base64字符串设置为常量,结果导致IDEA编译的时候出现了如下报错java:常量字符串过长,... 目录一、问题描述二、问题原因2.1 理论角度2.2 源码角度三、解决方案解决方案①:StringBui

Linux使用nload监控网络流量的方法

《Linux使用nload监控网络流量的方法》Linux中的nload命令是一个用于实时监控网络流量的工具,它提供了传入和传出流量的可视化表示,帮助用户一目了然地了解网络活动,本文给大家介绍了Linu... 目录简介安装示例用法基础用法指定网络接口限制显示特定流量类型指定刷新率设置流量速率的显示单位监控多个

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

C#中读取XML文件的四种常用方法

《C#中读取XML文件的四种常用方法》Xml是Internet环境中跨平台的,依赖于内容的技术,是当前处理结构化文档信息的有力工具,下面我们就来看看C#中读取XML文件的方法都有哪些吧... 目录XML简介格式C#读取XML文件方法使用XmlDocument使用XmlTextReader/XmlTextWr

C++初始化数组的几种常见方法(简单易懂)

《C++初始化数组的几种常见方法(简单易懂)》本文介绍了C++中数组的初始化方法,包括一维数组和二维数组的初始化,以及用new动态初始化数组,在C++11及以上版本中,还提供了使用std::array... 目录1、初始化一维数组1.1、使用列表初始化(推荐方式)1.2、初始化部分列表1.3、使用std::

Python如何实现PDF隐私信息检测

《Python如何实现PDF隐私信息检测》随着越来越多的个人信息以电子形式存储和传输,确保这些信息的安全至关重要,本文将介绍如何使用Python检测PDF文件中的隐私信息,需要的可以参考下... 目录项目背景技术栈代码解析功能说明运行结php果在当今,数据隐私保护变得尤为重要。随着越来越多的个人信息以电子形