iosswiftavaudioplayeramr

Can not play amr audio file in iOS


Trying play AMR audio file using this code:

    var player: AVAudioPlayer? = nil
    WebService.shared.download(self.dataSource.object(at: indexPath)) { data in
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)

            player = try AVAudioPlayer(data: data, fileTypeHint: AVFileType.amr.rawValue)
            guard let player = player else { return }

            print("Going to play: \(player.duration) seconds...")
            player.volume = 1.0
            player.prepareToPlay()
            player.play()
        } catch {
            print(error.localizedDescription)
        }
    }

I'm absolutely sure that:

  1. data received is not nil
  2. I can see correct duration time of amr file
  3. amr files contains some voices
  4. I did not get any error's
  5. I did not hear anything

What's up and how fix it?


Solution

  • The problem is with

    guard let player = player else { return }
    

    You are replacing the outer, optional AVAudioPlayer with a non-optional local copy. You call play() on the local copy and then when the closure completes, it goes out of scope and is deleted.

    Try this.

        player = try AVAudioPlayer(data: data, fileTypeHint: AVFileType.amr.rawValue)
        player?.volume = 1.0
        player?.prepareToPlay()
        player?.play()
    } catch {