【问题标题】:AVAudioPlayer only initializes with some filesAVAudioPlayer 只用一些文件初始化
【发布时间】:2010-04-12 20:17:34
【问题描述】:

我在玩一些filesAVAudioPlayer 时遇到问题。当我尝试播放某个 m4a 时,它工作正常。它也适用于我尝试的 mp3。但是,无论我尝试播放它们的顺序如何,它每次都在一个特定的mp3 上失败(15 Step,由 Radiohead)。音频只是没有play,尽管视图加载和同时发生的所有事情都是正确的。代码如下。我得到“播放器加载”。记录其他两首歌曲的输出,但不是 15 Step。我知道file path 是正确的(我在应用程序中早些时候输出了它的日志,它是正确的)。有什么想法吗?

NSData *musicData = [NSData dataWithContentsOfURL:[[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:[song filename] ofType:nil]]];

NSLog([[NSBundle mainBundle] pathForResource:[song filename] ofType:nil]);
if(musicData)
{
    NSLog(@"File found.");
}

self.songView.player = [[AVAudioPlayer alloc] initWithData:musicData error:nil];

if(self.songView.player) 
{
    NSLog(@"Player loaded.");
}

[self.songView.player play];
NSLog(@"You should be hearing something now.");

【问题讨论】:

    标签: iphone objective-c cocoa-touch avaudioplayer


    【解决方案1】:

    很抱歉这么晚才参加聚会。只是想发布一个提示,以便将来对任何引用此内容的人有用。

    shaggy frog 的回答的小修正。正确的用法是:

    NSError *anError = nil;
    anAVAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:someURL] error:&anError];
    if (!anAVAudioPlayer) {
        NSLog(@"localizedDescription : %@", [anError localizedDescription]);
    }
    

    【讨论】:

    • 有同样的问题 - 这是一个间歇性问题,我将表单数据切换到 url 并且它也可以工作
    【解决方案2】:
    NSData *musicData = [NSData dataWithContentsOfURL:[[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:[song filename] ofType:nil]]];
    

    这里是musicDatanil 用于问题案例吗?

    还有:

    self.songView.player = [[AVAudioPlayer alloc] initWithData:musicData error:nil];
    

    对于采用NSError 对象的方法,您不应传递nil。如果您正确使用它,它可能会更清楚地说明您的问题:

    NSError* error = nil;
    self.songView.player = [[AVAudioPlayer alloc] initWithData:musicData error:&error];
    if (error)
    {
        NSLog(@"Error with initWithData: %@", [error localizedDescription]);
    }
    

    【讨论】:

    • 感谢 NSError 的提示...我是 Objective-c 的新手,不知道如何正确使用它。我会试一试。不幸的是,musicData 在问题案例中不是零。我记录了进入它的 URL,它是正确的。如果我仍然有问题,我会尝试更多的东西并重新发布。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 2011-08-24
    相关资源
    最近更新 更多