2017-10-09 64 views
0

我在它與我的音頻播放器的結構體:斯威夫特3:AVAudioPlayer沒有播放聲音

struct MT_Audio { 

    func playAudio(_ fileName:String, _ fileExtension:String, _ atVolume:Float) { 
     var audioPlayer = AVAudioPlayer() 
     if let audioPath = Bundle.main.path(forResource: fileName, ofType: fileExtension) { 
      let audioURL = URL(string:audioPath) 
      do { 
       audioPlayer = try AVAudioPlayer(contentsOf: audioURL!) 
       audioPlayer.volume = atVolume 
       audioPlayer.prepareToPlay() 
       audioPlayer.play() 
      } catch { 
       print(error) 
      } 
     } 
    } 
} 

//I'm calling it in viewDidLoad like this: 

    guard let fileURL = Bundle.main.url(forResource:"heartbeat-01a", withExtension: "mp3") 
     else { 
       print("can't find file") 
       return 
      } 

     let myAudioPlayer = MT_Audio() //<--RESOLVED THE ISSUE BY MAKING THIS A PROPERTY OF THE VIEWCONTROLLER 
     myAudioPlayer.playAudio("heartbeat-01a", "mp3", 1.0) 

因爲它不和好如初的,我知道該文件的後衛是存在的。在嘗試之後,我也提出了一個突破點,並且我正在接觸音頻播放器。當我去實際的文件,並在Xcode中點擊它播放。這在模擬和設備上都會失敗。任何幫助,將不勝感激。

+0

,看一下在Xcode右側面板中。選擇文件時,應檢查目標成員資格。如果沒有,請檢查並重試。 –

+0

我在發帖前檢查過。但謝謝你的建議。 – PruitIgoe

+0

_注意_你應該避免在'audioURL!'中包含''隱含的解包可選''。 Bundle.main提供了一個url方法,它返回一個可選的url使用,而不是'if let audioUrl = Bundle.main.url(forResource:fileName,withExtension:fileExtension)' – Lamar

回答

1

看起來像你的audioPlayer只存儲在你的playAudio功能。

儘量保持audioPlayer因爲這樣你的類內的變量:

struct MT_Audio { 

    var audioPlayer: AVAudioPlayer? 

    mutating func playAudio(_ fileName:String, _ fileExtension:String, _ atVolume:Float) { 

     // is now member of your struct -> var audioPlayer = AVAudioPlayer() 
     if let audioPath = Bundle.main.path(forResource: fileName, ofType: fileExtension) { 
      let audioURL = URL(string:audioPath) 
      do { 
       let audioPlayer = try AVAudioPlayer(contentsOf: audioURL!) 
       audioPlayer.volume = atVolume 
       audioPlayer.prepareToPlay() 
       audioPlayer.play() 
      } catch { 
       print(error) 
      } 
     } 
    } 
} 
+0

感謝您的建議。仍然沒有獲得音頻。不知道爲什麼將audioPlayer轉換爲結構中的全局變量對於播放音頻是否重要。我在我的代碼中檢查過它,它被實例化了。文件路徑是正確的。在Xcode中選擇時播放mp3文件。這正成爲grrrrr的一個早晨。 – PruitIgoe

+0

得到它的工作,你把我放在正確的軌道 - 看到我上面的評論和更改我的代碼。 – PruitIgoe