在iOS应用程序中播放一个mp3文件

我无法弄清楚如何在iPhone游戏中播放音乐文件。

我创build一个游戏,我试图找出如何播放音乐,每当应用程序启动。

我试过这个:

- (void)awakeFromNib { NSString *path = [[NSBundle mainBundle] pathForResource:@"musicamenu" ofType:@"mp3"]; AVAudioPlayer *theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; [theAudio play]; } 

这是你如何做到的。 在你的v1AppDelegate.h文件中添加

 #import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> #import <AudioToolbox/AudioToolbox.h> @interface v1AppDelegate : UIResponder <UIApplicationDelegate> { AVAudioPlayer *myAudioPlayer; } @property (nonatomic, retain) AVAudioPlayer *myAudioPlayer; @property (strong, nonatomic) UIWindow *window; @end 

现在在你的v1AppDelegate.m文件中添加这个

 #import "v1AppDelegate.h" #import <AVFoundation/AVFoundation.h> #import <AudioToolbox/AudioToolbox.h> @implementation v1AppDelegate @synthesize window = _window; @synthesize myAudioPlayer; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //start a background sound NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Soothing_Music2_Long" ofType: @"mp3"]; NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath ]; myAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil]; myAudioPlayer.numberOfLoops = -1; //infinite loop [myAudioPlayer play]; // Override point for customization after application launch. return YES; } 

如果你想停止或从你的代码中的其他任何地方开始这个音乐,然后简单地添加这个

 #import "v1AppDelegate.h" - (IBAction)stopMusic { v1AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; [appDelegate.myAudioPlayer stop]; } - (IBAction)startMusic { v1AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; [appDelegate.myAudioPlayer play]; } 

我build议在applicationDidBecomeActive:方法中添加播放音乐方法。 因为您希望每次启动应用时都播放音乐。 注意你应该持有一个参考玩家。 否则音乐将不会播放。

 - (void)applicationDidBecomeActive:(UIApplication *)application { // Play music on another queue so that the main queue is not blocked. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [self playMusic]; }); } - (void)playMusic { NSString *path = [[NSBundle mainBundle] pathForResource:@"done" ofType:@"mp3"]; NSError *error = nil; NSURL *url = [NSURL fileURLWithPath:path]; self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; [self.player play]; } 

对于Swift 3.1:

使用这两个import:

 import AVFoundation import AudioToolbox 

为您的AVAudioPlayer创build一个参考:

 private var mAudioPlayer : AVAudioPlayer? 

使用此function播放您存储在应用中的声音:

 func onTapSound(){ let soundFile = Bundle.main.path(forResource: "slap_placeholder.wav", ofType: nil) let url = URL(fileURLWithPath: soundFile!) self.mAudioPlayer = try! AVAudioPlayer(contentsOf: url as URL) self.mAudioPlayer?.play() }