简体   繁体   中英

How to detect whether an audio file stored in document directory is playable or not programmatically Xcode iPhone

I am working on Playing an audio file stored in Document Directory using AVAudioPlayer.The Audio exists in directory and has 82 bytes of size.

I want to detect whether this audio is Playable or not.

/*save the Audio file in Document Directory */

NSFileManager *fileManager=[NSFileManager defaultManager];

/*Get the Path  to Application Documents Directory*/
NSArray *docDir=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

/*append the neccessary file extension */
NSLog(@"%d",bt.tag);
int a=bt.tag-10000;
NSString *filepathStr=[NSString stringWithFormat:@"/%@/%@.mp3",docDir,[NSString stringWithFormat:@"%d",a]];

/*Check if my crrent file exists in the Documents Directory*/

if([fileManager fileExistsAtPath:filepathStr])
{


    NSData *dat = [fileManager contentsAtPath:filepathStr];
    NSLog(@"data is %d",[dat length]);
    if(player)
    {
        [player stop];
        [player release];
        player=nil;
    }

    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:filepathStr] options:nil];

   /* You can then check its playable property:*/

    if (asset.playable) 
    {
        player = [[AVAudioPlayer alloc] initWithData:dat error:nil];
        player.delegate = self;
        [player play];  




        //Do Something
    }

I have other playable audios also stored in Document directory those are playing fine.
I have used the AVURLAsset and tried to check its property "playable" but couldn't succeed as the AVURLAsset object is not formed.

This audio file has a size of 82 bytes but its not playing not even in the itunes.

I just found the solution to this we can detect the audio is playable or not by using the following code

 NSURL *url=[[NSURL alloc] initFileURLWithPath:filepathStr]; 
     AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
  /* You can then check its playable property:*/

        if (asset.playable) 
        {

       player = [[AVAudioPlayer alloc] initWithData:dat error:nil];
            player.delegate = self;
            [player play];  
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM