2016-12-24 100 views
4

目前,這是我在按鈕按下時用於播放聲音的代碼。Swift 3.0 AVAudioPlayer通過音樂播放音頻

var player: AVAudioPlayer? 

    let url = Bundle.main.url(forResource: "Sound/yatch", withExtension: "mp3")! 

    do { 
     player = try AVAudioPlayer(contentsOf: url) 
     guard let player = player else { return } 

     player.prepareToPlay() 
     player.play() 
    } catch let error { 
     print(error.localizedDescription) 
    } 

我試圖讓這個音頻運行在什麼目前播放(等Spotify,潘多拉,音樂)。我會如何去做這件事?

回答

3

設置你的應用程序的音頻會話在當前播放的音頻播放:

try? AVAudioSession.sharedInstance().setActive(true) 
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient) 

按照AVAudioSession頭,AVAudioSessionCategoryAmbient會玩音樂音頻等

/* Use this category for background sounds such as rain, car engine noise, etc. 
Mixes with other music. */ 
public let AVAudioSessionCategoryAmbient: String 
+0

也有任何方式播放聲音而無需切換鈴聲到聲音?只要保持在振動位置。我正在通過蘋果公司的參考AVFoundation,並找不到任何東西 – CrazyCriss

+0

我想從URL http://site4brandz.com/cphp/26/uploads/KaabilHoon.mp3播放聲音,但它給錯誤錯誤域= NSOSStatusErrorDomain代碼= 2003334207「(null) –

+0

@MaheshNarla你應該問一個新的問題。 – JAL