1.必须要用 AVAudioSession,否则木有声音啊。2.不要把 AVAudioPlayer 当做局部变量,要定义成全局变量3.要找好路径,这里用 mainBundle,不要搞错。复制代码
private func playMusic() { let musicPath = Bundle.main.path(forResource: "money", ofType: "mp3") let fileUrl = NSURL.fileURL(withPath: musicPath ?? " ") do { let session = AVAudioSession.sharedInstance() try session.setCategory(AVAudioSessionCategoryPlayback) try session.setActive(true) audioPlay = try AVAudioPlayer.init(contentsOf: fileUrl) audioPlay.numberOfLoops = 0 audioPlay.volume = 0.5 audioPlay.currentTime = 0 audioPlay.prepareToPlay() audioPlay.play() } catch { debugLog(error) } }复制代码