简体   繁体   English

AVAudioPlayer:MP3文件无法在设备上播放,但适用于模拟器(iOS 6)

[英]AVAudioPlayer: MP3 file not playing on device, but works in Simulator (iOS 6)

I'm using the code below to play a MP3 file with AVAudioPlayer on iOS 6. The file seems to be playing, but there is no sound output on the device. 我正在使用下面的代码在iOS 6上播放带有AVAudioPlayer的MP3文件。该文件似乎正在播放,但设备上没有声音输出。 It works fine in the iOS Simulator though. 它在iOS模拟器中工作正常。

File .h: 档案.h:

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

@interface ViewController : UIViewController <AVAudioPlayerDelegate>

@property (strong, nonatomic) AVAudioPlayer *player;

@end

File .m: 档案.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

The code you've posted works fine for me. 您发布的代码对我来说很好。

  • Are you sure you're including the beep_7.mp3 in your target? 你确定你的目标中包含了beep_7.mp3吗?
  • Are you sure the filename is correct? 你确定文件名是正确的吗? iOS devices use a case-sensitive filesystem! iOS设备使用区分大小写的文件系统!
  • Are you sure your device isn't muted? 你确定你的设备没有静音吗?
  • Are you sure the file is a valid, working MP3 file? 您确定该文件是有效的MP3文件吗?

check your device's silent mode is on or off? 检查设备的静音模式是打开还是关闭? I once got the same problem as yours,after i changed my slient mode off,all solved! 我曾经遇到过和你一样的问题,在我改变了我的模式之后,一切都解决了!

Did you set AudioSessionCategory? 你有没有设置AudioSessionCategory?

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

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

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