如何在这个Phonegap插件中为iOS AudioServices编写停止函数

How to write a stop function for iOS AudioServices in this Phonegap plugin?

本文关键字:AudioServices iOS 函数 插件 Phonegap      更新时间:2023-09-26

我正在使用Phonegap插件SoundPlug来管理我正在构建的HTML5游戏中的音频,尽管它有播放声音的方法,但它没有任何停止声音的方法。播放函数是用PhoneGap.exec("SoundPlug.play","sound.wav")从应用程序的javascript调用的。相关代码如下:

- (void) play:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
    NSBundle * mainBundle = [NSBundle mainBundle];
    NSMutableArray *directoryParts = [NSMutableArray arrayWithArray:[(NSString*)[arguments objectAtIndex:0] componentsSeparatedByString:@"/"]];
    NSString       *filename       = [directoryParts lastObject];
    [directoryParts removeLastObject];
    NSMutableArray *filenameParts  = [NSMutableArray arrayWithArray:[filename componentsSeparatedByString:@"."]];
    NSString *directoryStr = [directoryParts componentsJoinedByString:@"/"];
    NSString *filePath = [mainBundle pathForResource:(NSString*)[filenameParts objectAtIndex:0]
                                              ofType:(NSString*)[filenameParts objectAtIndex:1]
                                         inDirectory:directoryStr];
    SystemSoundID soundID;
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    AudioServicesCreateSystemSoundID((CFURLRef)fileURL, &soundID);   
    AudioServicesPlaySystemSound(soundID);
}

不幸的是,我对Obj-C一无所知,所以我不确定如何为此编写一个合适的停止函数。(我试图处理的确切情况是,当玩家想要静音所有运行的声音时。)

如果需要停止,您真的不应该使用AudioServicesPlaySystemSound。如果phonegap有一个到AVAudioPlayer的桥,这可能是一个更适合用于启动和停止声音的API。

但是,如果您将AudioServicesPlaySystemSound()使用的soundID变量保存在某个位置(在实例变量、全局变量或传递回webview javascript land等中);AudioServicesDisposeSystemSoundID(soundID)可能会停止该soundID产生的系统声音。