12

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

audioAsset = [AVURLAsset assetWithURL:itemURL];

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

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

任何人都可以帮忙吗?我已经在stackoverflow中尝试了几乎所有此类问题的答案。

4

6 回答 6

22

可能你用过

  NSURL *itemPathURL = [NSURL URLWithString:outPath];

代替

NSURL *itemPathURL = [NSURL fileURLWithPath:outPath];
于 2015-05-28T07:19:06.823 回答
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)
于 2015-06-02T09:40:42.323 回答
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)
于 2016-12-29T12:04:03.957 回答
1

就我而言,必须识别文件名的扩展名,例如“.mp3”。如果不是,它将返回 0。

...让asset = AVURLAsset(url: URL(fileURLWithPath: filefullname), options: nil) ...asset.duration ...

于 2017-02-03T09:16:25.203 回答
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);
于 2014-09-26T09:11:29.437 回答
-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);
于 2014-10-06T13:55:46.257 回答