我正在构建一个具有多个 View Controller 的应用程序,并且我已经编写了一个音频文件以在应用程序启动时播放。这工作正常,当我单击按钮查看不同的屏幕时,音频文件仍然会播放而不会像预期的那样跳过节拍,但当我单击按钮返回主屏幕时,我的问题出现了。当我单击返回主屏幕时,音频文件会自行播放,让我想起歌曲 Row Row Your Boat。该应用程序正在重新读取告诉自己播放音频文件的代码,从而重新播放它。我的问题是我不知道如何让它不这样做。我已经对应用程序进行了编码,以便在单击“开始游戏”按钮时停止音频,这正是我希望它执行的操作,但直到那时。我只需要帮助让应用程序在返回主屏幕时不要自行播放音频文件。音频文件被编码为无限播放,直到单击“开始”按钮。如果有人可以从我想说的内容中得出结论,那么请帮助我正确地编码这个东西。感谢任何能让它正常工作的人。
这是我的代码:
-(void)viewDidLoad
{
NSString *introMusic = [[NSBundle mainBundle]pathForResource:@"invadingForces" ofType:@"mp3"];
audioPlayer0 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:introMusic] error:NULL];
audioPlayer0.delegate = self;
audioPlayer0.numberOfLoops = -1;
[audioPlayer0 play];
}
最佳答案
问题在于,当加载 View 时,您在局部变量中启动声音,开始无休止地重复播放,然后忘记它。然后关闭 View Controller ,让现在被遗忘的音频播放器继续播放。下次调用 View Controller 时,它的 viewDidLoad
方法会创建另一个音频播放器并开始播放那个播放器,然后忘记那个播放器。每次打开该 View Controller 的新副本时,您都会启动另一个声音播放器,为您的“划船、划船、划船”循环添加另一种声音。
天真的解决方案是将启动声音播放器的代码放在应用委托(delegate)中。将 AVAudioPlayer
设置为您的应用委托(delegate)的属性。创建一个 startPlaying 方法和一个 stopPlaying 方法。在您的 didFinishLaunchingWithOptions
方法中,调用 startPlaying。
更简洁的应用设计不是将应用功能放在您的应用委托(delegate)中,而是创建一个单例来管理声音播放。 (搜索“iOS单例设计模式”了解更多。)在单例中创建一个appDidLaunch
方法,并从didFinishLaunchingWithOptions
调用appDidLaunch
开始播放你的声音。这样,应用程序委托(delegate)就不需要在其中包含特定于应用程序的逻辑,而只需调用 appDidLaunch
即可。
编辑:
如果你想在应用程序委托(delegate)中调用一个方法,并且你的应用程序委托(delegate)被声明为:
@interface AppDelegate : UIResponder <UIApplicationDelegate>
然后你可以像这样从另一个文件中调用它:
首先,导入应用委托(delegate)的 header :
#import "AppDelegate.h"
以及调用您的应用委托(delegate)的 stopPlaying 方法的实际代码:
//Get a pointer to the application object.
UIApplication *theApp = [UIApplication sharedApplication];
//ask the application object for a pointer to the app delegate, and cast it
//to our custom "AppDelegate" class. If your app delegate uses a different
//class name, use that name here instead of "AppDelegate"
AppDelegate *theAppDelegate = (AppDelegate *)theApp.delegate;
[theAppDelegate stopPlaying];
关于ios - 音频文件自己播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34510319/