[英]How do you make a sound file play automatically thought an iOS app and loop using Objective-C?
我正在使用Objective-C为iPhone制作游戏。 我要在项目的文件中播放音乐。 我需要知道如何在应用启动时使其开始播放,并在最后循环播放。 有谁知道如何做到这一点? 代码示例会很棒! 谢谢。
您可以在App Delegate中使用AVAudioPlayer。
首先在您的App Delegate .h文件中添加以下行:
#import <AVFoundation/AVFoundation.h>
而这些:
AVAudioPlayer *musicPlayer;
在您的.m文件中,添加以下方法:
- (void)playMusic {
NSString *musicPath = [[NSBundle mainBundle] pathForResource:@"phone_loop" ofType:@"wav"];
NSURL *musicURL = [NSURL fileURLWithPath:musicPath];
musicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil];
[musicPlayer setNumberOfLoops:-1]; // Negative number means loop forever
[musicPlayer prepareToPlay];
[musicPlayer play];
}
最后,在didFinishLaunchingWithOptions
方法中调用它:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...
[self playMusic];
...
}
如果您想停止音乐播放,只需:
[musicPlayer stop];
另外,您可以查看Apple AVAudioPlayer委托的文档以处理音频中断http://developer.apple.com/library/ios/#DOCUMENTATION/AVFoundation/Reference/AVAudioPlayerDelegateProtocolReference/Reference/Reference.html
PS:请记住将AVFoundation框架导入到您的项目中。
首先将AVFoundation框架导入您的项目。 然后将音乐文件插入您的项目。
宣布
#import <AVFoundation/AVFoundation.h>
接着
AVAudioPlayer *audioPlayer;
NSURL *file = [NSURL URLWithString:[[NSBundle mainBundle] pathForResource:@"soundName" ofType:@"mp3"]];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:nil];
audioPlayer.numberOfLoops = -1; // Infinite loops
[audioPlayer setVolume:1.0];
[audioPlayer prepareToPlay];
[audioPlayer start]
您可以使用以下方法停止声音,直到应用程序转到背景为止
[audioPlayer stop];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.