2017-10-16 123 views
1

下面是代表音频播放器文件的代码。我正在试图利用它在我的程序中播放声音。我不想在每个视图控制器中放置AVPlayer功能来播放可重复的声音,所以我正在寻找一种方法将所有内容放在一个地方,并在需要时调用特定功能(音乐,点击,介绍)使用不同的swift文件播放音频

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):跳过输入流中0 0为0x0

回答

1

从讨论here这是与Xcode的模拟器中的错误,你应该尝试去修改方案>“运行参数和 加入环境变量OS_ACTIVITY_MODE,值禁用。

+0

好吧,我摆脱了控制台内的日志是的,但它不能解决问题 –

1

好的,发现一个问题。在我的情况下,需要将玩家存储为不会被破坏的属性或其他变量。这就是为什么日志 - 播放声音,但立即终止。我通过在AppDelegate中声明AVAudioPlayers来修复它