2017-10-16 14 views
1

아래는 오디오 플레이어 용 파일을 나타내는 코드입니다. 내 프로그램에서 사운드를 재생할 때이를 활용하려고합니다. 반복 가능한 사운드를 재생하기 위해 모든 뷰 컨트롤러에 AVPlayer 함수를 넣고 싶지 않으므로 필요한 모든 것을 한 곳에서 처리하고 특정 함수 (음악, 클릭, 소개)를 호출하는 방법을 찾고 있습니다다른 빠른 파일을 사용하여 오디오 재생

import UIKit 
import AVFoundation 

class player: UIViewController 
{ 
var music:Bool = true 
var sound:Bool = true 
var intro:Bool = true 

var soundPlayer: AVAudioPlayer? 
var clickPlayer: AVAudioPlayer? 
var musicPlayer : AVAudioPlayer? 
{ 
    get 
    { 
     let appDelegate = UIApplication.shared.delegate as! AppDelegate 
     return appDelegate.musicPlayer 
    } 
    set 
    { 
     let appDelegate = UIApplication.shared.delegate as! AppDelegate 
     appDelegate.musicPlayer = newValue 
    } 
} 

func playSound(title: String, format: String) 
{ 
    if sound == true 
    { 
     guard let url = Bundle.main.url(forResource: title, withExtension: format) 

      else { return } 

     do 
     { 
      try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) 
      try AVAudioSession.sharedInstance().setActive(true) 

      soundPlayer = try AVAudioPlayer(contentsOf: url) 

      soundPlayer?.play() 
     } 
     catch let error 
     { 
      print(error.localizedDescription) 
     } 
    } 
} 

func playClick() 
{ 
    if sound == true 
    { 
     guard let url = Bundle.main.url(forResource: "click", withExtension: "mp3") 

      else { return } 

     do 
     { 
      try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) 
      try AVAudioSession.sharedInstance().setActive(true) 

      let clickPlayer = try AVAudioPlayer(contentsOf: url) 

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

func playMusic() 
{ 
    if music == true 
    { 
     guard let url = Bundle.main.url(forResource: "ambientMusic", withExtension: "mp3") 

      else { return } 

     do 
     { 
      try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) 
      try AVAudioSession.sharedInstance().setActive(true) 

      musicPlayer = try AVAudioPlayer(contentsOf: url) 

      musicPlayer?.play() 
      musicPlayer?.numberOfLoops = -1 
     } 
     catch let error 
     { 
      print(error.localizedDescription) 
     } 
    } 
} 
} 

다른 파일 :

@IBAction func play(_ sender: Any) 
{ 
    player().playClick() 
    performSegue(withIdentifier: "menuToIntro", sender: self) 
} 

하지만 아무것도 재생되지 않습니다. 그냥 인쇄 AQDefaultDevice 로그 (173) : 토론 here이에서 입력 스트림 0 0 0x0으로

답변

1

를 건너 뛰는 것은 Xcode의 시뮬레이터 버그이며 환경 변수 OS_ACTIVITY_MODE를 추가 계획> 실행> 인수를 수정하려고하고 시도해야한다, 값 비활성화.

+0

글쎄, 콘솔에 로그가 없지만 문제가 해결되지 않습니다. –

1

좋아, 문제가 발생했습니다. 내 경우에는 플레이어를 재산이나 파괴되지 않는 다른 변수로 저장해야합니다. 그래서 로그가 재생되었지만 즉시 종료되었습니다. AppDelegate에서 AVAudioPlayers를 선언하여 수정했습니다.