2016-09-19 3 views
2

스위프트에서 AVPlayer을 사용하여 mp3 오디오 파일을 재생하는 아주 간단한 방법이 있습니다.AVPlayer를 사용하여 Swift에서 오디오 파일 재생

문제는 너무 단순 해 보입니다. 예를 들어 재생 문제, 파일 문제, 장치 오디오 문제, 앱 충돌 대신 정상적으로 재생이 실패 할 수있는 경우를들 수 있습니다.

아래의 재생 코드는 안전합니까?

import UIKit 

import AVFoundation 

var audioPlayer:AVPlayer! 

class ViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     audioPlayer = AVPlayer(URL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("myResourceFileName", ofType: "mp3")!)) 
     audioPlayer.play() 

    } 

} 
+1

if 문을 사용하여 pathForResource를 테스트하십시오. 힘을 풀지 마십시오. – pedrouan

답변

-1

"할"과 "캐치"를 시도해보십시오.

do {let path = NSBundle.mainBundle().pathForResource("myResourceFileName", ofType: "mp3") 
    let soundUrl = NSURL(fileURLWithPath: path!) 
    try audioPlayer = AVAudioPlayer(contentsOfURL: soundUrl) 
     audioPlayer.prepareToPlay()    
    } catch let err as NSError { 
     print(err.debugDescription) 
    } 

및 배치 audioPlayer.play() 재생하고자하는 기능에 .

관련 문제