AVURLAsset返回的持续时间为0。

13

我正在尝试获取音频文件的持续时间以便进行裁剪,我使用以下代码:

audioAsset = [AVURLAsset assetWithURL:itemURL];

CMTime assetTime = [audioAsset duration];
Float64 duration = CMTimeGetSeconds(assetTime);

当我提供媒体库中任何音频文件的itemURL时,我可以得到正确的持续时间,然后我就能够剪辑音频文件。然后我将修剪过的音频文件保存在文档目录中。但是,当我尝试修剪已经被修剪过的文件时,相同的代码会返回0作为持续时间。不过,我能够使用AVAudioPlayer播放修剪过的文件并获取其持续时间,但AVURLAsset有什么问题我无法找出。

有人能帮忙吗?我已经尝试了stackoverflow上几乎所有这类问题的答案。

6个回答

23

可能你已经使用过

  NSURL *itemPathURL = [NSURL URLWithString:outPath];

取代

NSURL *itemPathURL = [NSURL fileURLWithPath:outPath];

2

我认为AVURLAsset需要知道文件的类型扩展名来计算其持续时间。你可能将文件存储为{fileName}而不是{fileName}.{extension}

如果你使用没有扩展名的yourFileName运行以下代码,就会出现*** Could not find format reader for URL的错误,并返回值 0。

import AVFoundation

let fileName = *yourFileName*
let url = NSURL(fileURLWithPath: fileName)
let asset = AVURLAsset(URL: url, options: nil)
println(asset.duration.value.description)

当我打开本地文件时,遇到了类似的问题。我的解决方案是在“asset = AVURLAsset(...)”之后包含一个“asset.init()”。然后,持续时间就会填充为电影的正确长度。我正在使用C#编写,因此可能会有所不同。但是在寻找解决方案时,我着陆了这个主题。 - Morten

1
对于我的情况,需要识别文件名的扩展名,例如“.mp3”。 如果没有识别到,将返回0。
... 让asset = AVURLAsset(url:URL(fileURLWithPath:filefullname),options:nil) ... asset.duration ...

1
对于Swift 3.0及以上版本

导入AVFoundation

  let asset = AVAsset(url: URL(fileURLWithPath: ("Your File Path here")!))
  let totalSeconds = Int(CMTimeGetSeconds(asset.duration))
  let minutes = totalSeconds / 60
  let seconds = totalSeconds % 60
  let mediaDuration = String(format:"%02i:%02i",minutes, seconds)

您还可以使用 asset.duration.seconds。 - Dmitry Kozlov

0
尝试以下方式......
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask,   YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getAudioPath = [documentsDirectory stringByAppendingPathComponent:@"song.mp3"];
NSURL *finalUrl=[[NSURL alloc]initFileURLWithPath:getAudioPath];
NSLog(@"finalUrl===%@",finalUrl);
AVURLAsset *asset = [AVURLAsset assetWithURL: finalUrl];
duration = CMTimeGetSeconds(asset.duration);
NSLog(@"duration==%f",duration);

是的,我正在尝试你代码的第一部分,但在我的情况下,它在另一个方法中,我也能够获取URL,就像你一样,所以那不是问题。 - Rameswar Prasad

-3

试试这个……

AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:Yoururl options:nil];
CMTime time = asset.duration;
double durationInSeconds = CMTimeGetSeconds(time);
int minutes = floor(durationInSeconds/60);
int seconds = round(durationInSeconds - (minutes * 60));
NSString * duration = [NSString stringWithFormat:@"%i:%i",minutes,seconds];
NSLog(@"Duration : %@", duration);

1
你真的读了问题吗?他说持续时间是0。将其格式化为分钟和秒钟完全没有任何区别。 - Jarrod Robins

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接