ios - AVAudioPlayer 不播放 MP3

标签 ios swift audio avaudioplayer

我需要复制一个 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)
   }
}

我没有收到任何错误,但没有声音被再现。我还在 App Capabilities 中启用了 Inter-App 音频,在“Copy Bundle Resources”中添加了 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!

就是这样

关于ios - AVAudioPlayer 不播放 MP3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43711718/

相关文章:

ios - Xcode8.3-无效的位码签名

ios - NSArray代码未运行

ios - 当 TextView 中没有文本时,如何让 TableView 不保存笔记?

ios - Swift:创建 iOS 框架并导入框架错误:Variable used within its own initial value

ios - Xcode 11.4 编译错误 'Missing package product <package name>'

android - 如何将音频流传输到Android设备?

iphone - 使用音频队列服务将音频录制到数据

ios - 将 cocoapods 引入协作 iOS 项目有哪些复杂之处?

ios - 带有 EKEventStoreChanged 通知的 NotificationCenter 使用不同的通知多次调用

javascript - 选中或单击单选按钮时播放音频