如何在我的应用程序启动后自动播放音乐?
我需要一些帮助,我最近开始我的应用程序。 我是一个非常大的开始编码,所以请帮助我,这将意味着很多。 当用户进入我的应用程序时,我需要一段音乐才能播放,我已经遵循了其他YouTube教程,但是它们只适用于较旧的Xcode版本,所以请大家非常感谢。
如何把它放在你的application didFinishLaunching
但一定要实例化它在你.h和.m。
像这样的东西应该做你的问题:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSString* resourcePath = [[NSBundle mainBundle] resourcePath]; resourcePath = [resourcePath stringByAppendingString:@"/YOURMUSICNAME.wav"]; NSLog(@"Path to play: %@", resourcePath); NSError* err; //Initialize our player pointing to the path to our resource player = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:resourcePath] error:&err]; if( err ){ //bail! NSLog(@"Failed with reason: %@", [err localizedDescription]); } else{ //set our delegate and begin playback player.delegate = self; [player play]; player.numberOfLoops = -1; player.currentTime = 0; player.volume = 1.0; } }
那么如果你想阻止它:
[player stop];
或暂停:
[player pause];
并将其导入到您的头文件中:
#import <AVFoundation/AVFoundation.h>
编辑:
你应该当然地在你的头部声明它,然后综合它。
//.h并添加粗体部分:
@interface ViewController:UIViewController < AVAudioPlayerDelegate > {
AVAudioPlayer *player; } @property (nonatomic, retain) AVAudioPlayer *player;
//.m
@synthesize player;
您可以使用AVAudioPlayer
。 它非常简单易用:
NSURL *path = [[NSURL alloc] initFileURLWithPath:[DataPersister getQualifiedPathForFileInDirectory:DataPersisterPathBundle fileName:@"music.mp3"]]; NSError *outError; AVAudioPlayer *musicSound = [[AVAudioPlayer alloc] initWithContentsOfURL:path error:&outError]; [musicSound play]; [path release];
记得导入
#import <AVFoundation/AVFoundation.h>
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/MUSIC.mp3", [[NSBundle mainBundle] resourcePath]]]; NSError *error; audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; audioPlayer.numberOfLoops = -1; [audioPlayer play]; audioPlayer.volume = 1.0; audioPlayer.currentTime = 2;
在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
方法将播放音乐
快乐编码;)