【问题标题】:How to detect whether an audio file stored in document directory is playable or not programmatically Xcode iPhone如何以编程方式检测存储在文档目录中的音频文件是否可播放 Xcode iPhone
【发布时间】:2012-09-25 12:40:49
【问题描述】:

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

【问题讨论】:

  • 我也用过 AVAsset avAsset = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:filepathStr] options:nil]; if (avAsset.playable) {/ its playable*/ } 但是 AVURLAsset *asset 是 nil

标签: ios objective-c audio playback detect


【解决方案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];  
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 1970-01-01
    • 2023-02-13
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多