2013-07-12 225 views
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); 
} 

這個問題是,我不知道如何以後停止聲音或使聲音永久播放直到它停止。我會如何去做這件事?我可能會讓該方法返回聲音,然後將其放入一個變量中以便稍後進行修改?

+1

我一直親自使用AVAudioPlayer對象來處理聲音取代AudioServicesPlaySystemSound(soundID);,但我發現一個話題討論類似的東西在這裏使用AudioServices。 http://iphonedevsdk.com/forum/iphone-sdk-development/4446-simple-sound-question.html - 希望它有幫助 – Phas1c

+0

問題還在於,如果您不需要它,就必須發佈聲音(AudioServicesDisposeSystemSoundID) 。所以它需要你管理資源。 – Andy

回答

1

我怕我不知道如何阻止它,但嘗試一下本作循環:

soundFile = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:@"AudioName" ofType:@"wav"]]; 
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil]; 
sound.numberOfLoops = -1; //infinite 
[sound play]; 
+0

[聲音暫停]停止。 – Andy

0

系統聲音服務通常用於播放簡短的聲音/提醒/等等,可能應該避免暫停/停止。如果真的需要這個,你可以試試AudioServicesDisposeSystemSoundID(systemSoundID)來停止聲音。 至於循環,你可以創建遞歸函數來使用AudioServicesPlaySystemSoundWithCompletion循環聲音。

例(SWIFT 3):

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

因此,在你的榜樣,你會只是playSystemSound(systemSoundID: soundID, count: numOfPlays)