我正在构建一个必须播放 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