[英]How to playback an audio file with TheAmazingAudioEngine with Swift?
[英]how do I set my Audio Session Default Behavior to Playback in swift?
我的應用程序具有“點擊”聲音功能。 我用了
import AVFoundation
然后通過以下功能運行“咔嗒”聲:
var audioPlayer = AVAudioPlayer()
func playSound() {
var soundPath = NSBundle.mainBundle().pathForResource("tick", ofType: "wav")
var soundURL = NSURL.fileURLWithPath(soundPath!)
self.audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil)
self.audioPlayer.play()
}
現在,如果用戶正在運行音樂播放器,則我的應用程序將導致音樂播放器停止運行。 我在文檔中閱讀了有關音頻會話默認行為的信息,但是我不知道如何應用它。
你能幫忙嗎?
謝謝!
如果您想知道swift 2的語法,這里是:
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: .DuckOthers)
} catch {
print("AVAudioSession cannot be set: \(error)")
}
根據您希望應用程序的行為,即您的應用程序的聲音效果或音樂應如何與其他應用程序的背景音頻會話進行交互,您可能需要同時調整音頻會話類別和categoryOption。
如果您只想播放聲音,例如“滴答”聲,則應分別使用AVAudioSessionCategoryAmbient和DuckOthers,例如:
let audioSession = AVAudioSession.sharedInstance()
var error: NSErrorPointer = nil
audioSession.setCategory(AVAudioSessionCategoryAmbient, withOptions: .DuckOthers, error: error)
但是,我想您實際上是在嘗試播放聲音效果,在這種情況下,AudioServices API是更合適的選擇。 您可以在AudioToolbox框架中檢查func AudioServicesPlaySystemSound(inSystemSoundID:SystemSoundID),以了解更多詳細信息。
另一個常見的情況。 如果要讓您的應用專門播放音頻,即使其他應用在后台播放音樂,則需要將類別設置為AVAudioSessionCategorySoloAmbient,例如:
let audioSession = AVAudioSession.sharedInstance()
var error: NSErrorPointer = nil
audioSession.setCategory(AVAudioSessionCategorySoloAmbient, error: error)
希望您有想要的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.