olle
olle

Reputation: 144

Swift5 Play aac file AvAudioPlayer

I currently play a wav file with the code below. But now i have compressed the files to aac-files and i can't figure out how to play them? I tried to change the withExtension to "aac" instead but no sound. Any ideas?

guard let url = Bundle.main.url(forResource: fileName, withExtension: "aac") else { return }

    do {
        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
        try AVAudioSession.sharedInstance().setActive(true)

        let audioPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.ac3.rawValue)
        audioPlayer.volume = currentVolume
        newAudioPlayer.audioPlayer.play()

    } catch let error {
        print(error.localizedDescription)
    }

Upvotes: 6

Views: 1965

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236275

If you need to play AAC files you can use AVAudioEngine audio player node:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    let audioEngine = AVAudioEngine()
    let player = AVAudioPlayerNode()

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = Bundle.main.url(forResource: "audio_name", withExtension: "aac")!
        do {
            let audioFile = try AVAudioFile(forReading: url)
            guard let buffer = AVAudioPCMBuffer(pcmFormat: audioFile.processingFormat, frameCapacity: .init(audioFile.length)) else { return }
            try audioFile.read(into: buffer)
            audioEngine.attach(player)
            audioEngine.connect(player, to: audioEngine.mainMixerNode, format: buffer.format)
            try audioEngine.start()
            player.play()
            player.scheduleBuffer(buffer, at: nil, options: .loops)

        } catch {
               print(error)
        }
    }
}

Upvotes: 9

Related Questions