AVAudioPlayer:iOS 6模拟器可播放MP3文件,但在设备上无法播放

4

我将使用下面的代码在iOS 6上使用AVAudioPlayer播放MP3文件。该文件似乎正在播放,但设备上没有声音输出。但在iOS模拟器中正常工作。

文件.h:

#import "UIKit/UIKit.h"
#import "AVFoundation/AVFoundation.h"

@interface ViewController : UIViewController <AVAudioPlayerDelegate>

@property (strong, nonatomic) AVAudioPlayer *player;

@end

文件 .m:

#import "ViewController.h"

@implementation ViewController

@synthesize player;

- (void)viewDidLoad {
    [super viewDidLoad];

    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"beep_7" ofType:@"mp3"];
    NSLog(@"Audio path: %@", soundFilePath);

    NSError *error;
    player =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:soundFilePath] error:&error];

    if (error) {
        NSLog(@"Error in audioPlayer: %@",[error localizedDescription]);
    } 
    else {
        [player setDelegate:self];
        [player setNumberOfLoops:3]; //just to make sure it is playing my file several times
        player.volume = 1.0f;

        if([player prepareToPlay]) //It is always ready to play
            NSLog(@"It is ready to play");
        else
            NSLog(@"It is NOT ready to play ");

        if([player play]) //It is always playing
            NSLog(@"It should be playing");
        else
            NSLog(@"An error happened");
    }
}
@end

如果你实现了委托方法 audioPlayerDecodeErrorDidOccur:error:,你是否看到任何错误? - trojanfoe
我已经实现了该方法,但没有出现任何日志...-(void)audioPlayerDecodeErrorDidOccur: (AVAudioPlayer *)player error:(NSError *)error { NSLog(@"audioPlayerDecodeErrorDidOccur -> 音频播放器出错: %@",[error localizedDescription]); } - rubrin
你似乎正在设备上进行测试。在iOS模拟器中能否正常工作? - Andreas Ley
我犯了几个错误。首先,我的文件已经损坏了,其次,我关闭了静音按钮。不管怎样,还是谢谢 :) - rubrin
它在iOS模拟器中运行正常,但在我的iPhone上却无法运行...我的iPhone可能出了什么问题? - Monika Patel
显示剩余2条评论
3个回答

5

您发布的代码对我来说运行正常。

  • 您确定在目标中包含了beep_7.mp3吗?
  • 您确定文件名正确吗?iOS设备使用区分大小写的文件系统!
  • 您确定您的设备没有静音吗?
  • 您确定该文件是有效的、可工作的MP3文件吗?

我正在测试两个不同的mp3文件。我已经将这些文件与我的iPhone同步,并在那里播放,它可以正常工作。因此,文件是有效的,我的设备也没有静音。 至于是否已将这些文件包含到我的目标中,我所做的唯一事情就是将它们拖到我的项目中的Supporting Files中...我还有什么遗漏吗? - rubrin
我刚刚检查了我的target->Build Phases,两个文件都在那里。 - rubrin
啊,我的设备静音了。很棒的答案涵盖了所有的问题。 - Easwaramoorthy K

2

检查您的设备是否处于静音模式? 我曾经遇到了与您相同的问题,之后我关闭了我的静音模式,问题得以解决!


0

你设置了AudioSessionCategory吗?

{
    NSError *setCategoryError = nil;
    BOOL success = [[AVAudioSession sharedInstance] setCategory: 
    avaudiosessioncategoryplayandrecorderror: &setCategoryError];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接