无法在ios应用程序中的avplayer中播放mp3文件

时间:2017-03-20 05:13:37

标签: ios objective-c

我尝试使用AVP播放器播放mp3文件。但我无法播放它..我的代码是

NSString *fileurl=[FILE_URL_Array objectAtIndex:indexPath.row];
NSArray *parts = [fileurl componentsSeparatedByString:@"/"];
NSString *filename = [parts lastObject];

NSLog(@"file name is %@",filename);

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString  *documentsDirectory = [paths objectAtIndex:0];

NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,filename];
//NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

NSString* foofile = [documentsDirectory stringByAppendingPathComponent:filename];
NSLog(@"foofile %@",foofile);
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];
NSLog(@"boolean value is %hhd",fileExists);


if (fileExists)
{

    NSURL *audioURL = [NSURL fileURLWithPath:filePath];
    NSLog(@"existig url is%@",audioURL);

    NSData *urlData =[NSData dataWithContentsOfURL:audioURL];
   // NSString *sourcePath =[audioURL path];
    //UISaveVideoAtPathToSavedPhotosAlbum(sourcePath,nil,nil,nil);
    NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,filename];
    [urlData writeToFile:filePath atomically:YES];


    audioPlayer = [[AVAudioPlayer alloc]initWithData:urlData  error:NULL];
    audioPlayer.delegate = self;
    [audioPlayer play];
}

但我无法播放该音频文件....请提供您宝贵的解决方案。谢谢!

1 个答案:

答案 0 :(得分:0)

您目前正在两次附加documentsDirectory。

NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,filename];
//NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

NSString* foofile = [documentsDirectory stringByAppendingPathComponent:filename];

一旦进入filePath,再次进入foofile。

此外,您似乎正在做一大堆您不需要做的额外处理。您应该能够从初始文件URL:

创建音频播放器
NSString *fileurl=[FILE_URL_Array objectAtIndex:indexPath.row];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL urlWithString:fileUrl] error:&error];
if (error != nil) {
    NSLog(@"Error creating player: %@", error);
}
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
[audioPlayer play];