如何检测存储在文档目录中的音频文件是否可以以编程方式播放Xcode iPhone

时间:2012-09-25 12:40:50

标签: ios objective-c audio playback detect

我正在使用AVAudioPlayer播放存储在文档目录中的音频文件。音频存在于目录中,大小为82字节。

我想检测此音频是否可播放。

/*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
    }

我还有其他可播放的音频也存储在Document目录中,这些音频播放正常 我使用了AVURLAsset并尝试检查其属性“可播放”但由于未形成AVURLAsset对象而无法成功。

此音频文件的大小为82字节,但在itunes中不能播放。

1 个答案:

答案 0 :(得分:1)

我刚刚找到解决方法,我们可以通过使用以下代码检测音频是否可播放

 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];  
 }