本文介绍了如何通过iOS应用程序自动播放声音文件并使用Objective-C循环播放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Objective-C为iPhone制作游戏.我要在项目的文件中播放音乐.我需要知道如何在应用启动时使其开始播放,并在最后循环播放.有谁知道如何做到这一点?代码示例会很棒!谢谢.

I am making a game for iPhone using objective-c. I have the music I want to play in a file in the project. I need to know how to make it begin playing when the app launches, and loop at the end. Does anyone know how to do this? Code examples would be great! Thanks.

推荐答案

您可以在App Delegate中使用AVAudioPlayer.

you can use AVAudioPlayer in App Delegate.

首先在您的App Delegate .h文件中添加以下行:

First in your App Delegate .h file add these lines:

#import <AVFoundation/AVFoundation.h>

和这些:

AVAudioPlayer *musicPlayer;

在您的.m文件中,添加以下方法:

In your .m file add this method:

- (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];
  ...
}

如果您只想停止播放音乐,

If you want to stop the music just:

[musicPlayer stop];

另外,您可以查看Apple文档中的AVAudioPlayer委托以处理音频中断 http://developer.apple.com/library/ios/#DOCUMENTATION/AVFoundation/Reference/AVAudioPlayerDelegateProtocolReference/Reference/Reference.html

Aditionally you can check the Apple Documentation for AVAudioPlayer delegate for Handling Audio Interruptions http://developer.apple.com/library/ios/#DOCUMENTATION/AVFoundation/Reference/AVAudioPlayerDelegateProtocolReference/Reference/Reference.html

PS:请记住将AVFoundation框架导入到您的项目中.

PS: Remember to import the AVFoundation Framework to your project.

这篇关于如何通过iOS应用程序自动播放声音文件并使用Objective-C循环播放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 06:59