[英]AVAudioPlayer not playing the MP3
我需要復制一個MP3文件,並且正在使用以下代碼:
import AVFoundation
var player: AVAudioPlayer?
@IBAction func playSound(sender: UIButton) {
//Making the phone vibrate
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
//Playing a sound
let url = Bundle.main.url(forResource: "audio_file_name", withExtension: "mp3")!
do {
self.player = try AVAudioPlayer(contentsOf: url)
self.player?.delegate = self
self.player?.prepareToPlay()
self.player?.play()
} catch let error {
print(error.localizedDescription)
}
}
我沒有任何錯誤,但是沒有聲音被復制。 我還啟用了“應用程序功能”中的應用程序間音頻,在“復制捆綁資源”中添加了MP3文件,並且正在實際設備上進行測試。 有什么建議嗎? 我已經嘗試過此類其他問題中提供的所有其他解決方案...
我解決了
一切都無法正常工作,因為我在后台隊列中重現了這段代碼。 將其移至主隊列即可解決問題。
這段代碼對我來說很好
func playAudio(){
let audioUrl = URL(fileURLWithPath: value, relativeTo: someBasePath)
do{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
audioPlayer = try AVAudioPlayer(contentsOf: audioUrl, fileTypeHint: AVFileTypeMPEGLayer3)
audioPlayer.prepareToPlay()
audioPlayer.play()
}catch{
print(error.localizedDescription)
}
}
並且您必須將audioPlayer
定義為類成員,否則它將超出范圍,並且將無法使用。
var audioPlayer: AVAudioPlayer!
而已
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.