posts - 186,  comments - 17,  views - 35万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

AVAudioplayer 有两个初始化方法:

1、[[AVAudioPlayer alloc] initWithData:musicData error&e];
2、[[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
第一种是使用将音频文件的data文件初始化,但是data必须是一个完整的文件。
第二种是从url获取,但是这里的url是本地的file URL。
 
 所以AVAudioplayer无法直接从网络url上获取音频文件,所以可以用:
data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://.../file.mp3"]];
将网络上音频down下来,再用initWithData初始化player。但是这样down下来的文件有时是不完整的,所以出现创建失败问题,出现:
Error Domain=NSOSStatusErrorDomain Code=1954115647
解决这个问题的方法就是将data保存在本地,在通过initWithContentsOfURL,找到该文件,这样就可以成功创建了。
整个流程为:
NSData *audioData = [NSData dataWithContentsOfURL:someURL]; 
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMaskYES) objectAtIndex:0]; 
NSString *filePath = [NSString stringWithFormat:@"%@/%@.mp3", docDirPath , fileName];
[audioData writeToFile:filePath atomically:YES]
NSError *error
NSURL *fileURL = [NSURL fileURLWithPath:filePath]; 
player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
if (player == nil
{ NSLog(@"AudioPlayer did not load properly: %@", [error description]); }
else
[player play]; }



局限性:recorder,player简单易用,但是有局限性。
对我项目影响最大的是,多次录音时,并播放时,会出现文件错误。
在继续利用recorder,player的前提下,就需要将每次录音完成的文件进行数据追加。

if ([[NSFileManager defaultManager] fileExistsAtPath:临时音频路径) {

      NSData *tempAudioData = [[NSData alloc] initWithContentsOfFile:临时音频路径];

      if ([[NSFileManager defaultManager] fileExistsAtPath:音频路径]) {
          NSMutableData *newAudioData = [NSMutableData data];
          NSData *audioData = [[NSData alloc] initWithContentsOfFile:[self configureAudioRecordFilePath:self.currentFileName]];
          [newAudioData appendData:audioData];
          [newAudioData appendData:tempAudioData];
          PADebug(@"data length:%zd", [newAudioData length]);
          [newAudioData writeToFile:音频路径 atomically:YES];
      }else
      {
          [tempAudioData writeToFile:[self configureAudioRecordFilePath:self.currentFileName] atomically:YES];
      }
      [[NSFileManager defaultManager]removeItemAtPath:音频路径 error:nil];
  }


 
 
posted on   ZOYOO  阅读(7996)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示