繁体   English   中英

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

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

我正在使用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中也不播放。

我刚刚找到解决方案,可以使用以下代码来检测音频是否可播放

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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