0

我正在构建一个必须播放 mp3 文件的应用程序。对于那个问题,我正在使用 AVAudioPlayer 遵循我从其他帖子中阅读的指示。但我的问题是,代码(我附在下面)适用于 iOS 模拟器,但是当我尝试在我的 iPhone 中使用它时,它不起作用......我希望你们中的任何人都可以帮助我解决这个问题。

文件.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;
    self.player =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:soundFilePath] error:&error];

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

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

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

-(void)audioPlayerDecodeErrorDidOccur: (AVAudioPlayer *)player error:(NSError *)error {
    NSLog(@"audioPlayerDecodeErrorDidOccur -> Error in audioPlayer: %@",[error localizedDescription]);
}
-(void)audioPlayerDidFinishPlaying: (AVAudioPlayer *)player successfully:(BOOL)flag{
    NSLog(@"audioPlayerDidFinishPlaying");
}
-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{
    NSLog(@"audioPlayerBeginInterruption");
}
-(void)audioPlayerEndInterruption:(AVAudioPlayer *)player{
    NSLog(@"audioPlayerEndInterruption");
}

@end
4

1 回答 1

4

检查音频(或图像)何时在模拟器中而不是在设备上工作(显示)的第一件事是您尝试访问的音频文件的拼写。

由于 Mac OSX 不区分大小写,但 iOS 是这意味着在您的代码中拼写iMage.png和访问的图像image.png将显示在模拟器中,但不会显示在您的 iPhone 上。

要检查的另一件事可能是您不小心按下了 iPhone 上的物理静音按钮。(上周发生在我身上)

希望能帮助到你!

于 2013-02-27T10:02:31.333 回答