0

Я использую AVAudioPlayer для проигрывания аудио, но вылетает ошибка.

Вот мой код:

var audioPlayer:AVAudioPlayer!
var soundChange = true

  @IBAction func play(_ sender: Any) {


    let url = NSURL(string: "/upload/iblock/f64/f64aa1d14b7fb2fe5de5f68922ee506f.mp3")! as URL

    do {
        audioPlayer = try AVAudioPlayer(contentsOf: url)



        Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateAudioProgressView), userInfo: nil, repeats: true)

        progressView.setProgress(Float(audioPlayer.currentTime/audioPlayer.duration), animated: false)

    } catch {
        print("An error occurred while trying to extract audio file")
    }

Тут выводит ошибку: unexpectedly found nil while unwrapping an Optional value

if !audioPlayer.isPlaying && soundChange == true{
        playChange.setImage(UIImage(named:"Pause.png"), for: UIControlState.normal)
        soundChange = false
        audioPlayer.play()    
    } else {
        playChange.setImage(UIImage(named:"Play.png"), for: UIControlState.normal)
        soundChange = true
        audioPlayer.pause()
    }
}
6
  • а можно настоящий url, чтоб можно было к себе код скопировать, запустить и посмотреть 26 мая 2017 в 12:31
  • @Max Mikheyenko stmegi.com/upload/iblock/f64/…
    – Vasya2014
    26 мая 2017 в 12:39
  • а что за ошибка? 26 мая 2017 в 12:45
  • @Max Mikheyenko fatal error: unexpectedly found nil while unwrapping an Optional value но ссылка не оптиональная в условии if !audioPlayer.isPlaying
    – Vasya2014
    26 мая 2017 в 12:59
  • Я бы не спешил уверять, что audioPlayer не optional, так как он implicity unwrapped optional. У вас падает в catch? Тогда audioPlayer у Вас nil.
    – VAndrJ
    26 мая 2017 в 13:45

1 ответ 1

1

Если вкратце, то AVAudioPlayer не играет url'ы, либо локальные файлы, либо про данные в NSData формате. Что вам надо сделать: сначала взять файл и сконвертировать в Data, и уже потом играть

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var audioPlayer:AVAudioPlayer!

    override func viewDidLoad() {
        super.viewDidLoad()


        let url = URL(string: "https://stmegi.com/upload/iblock/f64/f64aa1d14b7fb2fe5de5f68922ee506f.mp3")

        do {
            let data = try Data(contentsOf: url!)
            self.audioPlayer = try AVAudioPlayer(data: data)
            audioPlayer.play()
        } catch let error as NSError{
            print(error.localizedDescription)
        }   
    }
}
1
  • спасибо тебе, работает
    – Vasya2014
    26 мая 2017 в 15:28

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.