0

我创建了这个方法来轻松地在 XCode iPhone 应用程序中播放声音。

void playSound(NSString* myString) {
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    NSString *string = myString;
    CFURLRef soundFileURLRef;
    soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (__bridge CFStringRef) string, CFSTR ("wav"), NULL);
    UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
    AudioServicesPlaySystemSound(soundID);
}

问题是,我不知道以后如何停止声音或让声音永远循环播放,直到它停止。我该怎么做呢?我是否可以让该方法返回声音,然后将其放入变量中以供稍后修改?

4

4 回答 4

2

恐怕我不知道如何停止它,但试试这个循环:

soundFile = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:@"AudioName" ofType:@"wav"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.numberOfLoops = -1; //infinite
[sound play];
于 2013-07-12T17:43:17.173 回答
1

From documentation: "The interface does not provide level, positioning, looping, or timing control, and does not support simultaneous playback...".

http://developer.apple.com/library/ios/#documentation/AudioToolbox/Reference/SystemSoundServicesReference/Reference/reference

So for sound playback it is better use AVFoundation classes.

于 2013-07-12T17:49:00.390 回答
1

系统声音服务通常用于播放短声音/警报/等,应该避免暂停/停止。如果确实需要这样做,您可以尝试AudioServicesDisposeSystemSoundID(systemSoundID)停止声音。至于循环,您可以创建递归函数来使用AudioServicesPlaySystemSoundWithCompletion.

示例(快速 3):

func playSystemSound(systemSoundID: SystemSoundID, count: Int){
    AudioServicesPlaySystemSoundWithCompletion(systemSoundID) {
        if count > 0 {
            self.playSystemSound(systemSoundID: systemSoundID, count: count - 1)
        }
    }
}

因此,在您的示例中,您只需替换AudioServicesPlaySystemSound(soundID);playSystemSound(systemSoundID: soundID, count: numOfPlays)

于 2017-09-22T10:37:49.007 回答
0

如果您想决定基于布尔变量播放声音,

private func playSound() {
        if isStarted {
            AudioServicesPlaySystemSoundWithCompletion(kSystemSoundID_Vibrate, {
                if self.isStarted {
                    self.playSound()
                }
            })
        }
    }

于 2019-11-15T05:53:59.653 回答