Objective-Cを使ってiPhone向けのゲームを作っています。プロジェクト内のファイルに再生したい音楽があります。アプリの起動時に再生を開始し、最後にループする方法を知る必要があります。誰もこれを行う方法を知っていますか? コード例は素晴らしいでしょう!ありがとう。
1587 次
2 に答える
2
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];
さらに、オーディオ割り込みの処理に関する AVAudioPlayer デリゲートの Apple ドキュメントを確認できますhttp://developer.apple.com/library/ios/#DOCUMENTATION/AVFoundation/Reference/AVAudioPlayerDelegateProtocolReference/Reference/Reference.html
PS: AVFoundation フレームワークをプロジェクトにインポートすることを忘れないでください。
于 2012-08-07T23:18:00.503 に答える
1
まず、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];
于 2012-08-07T22:58:09.303 に答える