【问题标题】:Play specific sound when specific button is pressed in iOS在 iOS 中按下特定按钮时播放特定声音
【发布时间】:2017-05-14 03:21:12
【问题描述】:

我是 iOS 开发的初学者,我正在尝试制作一个简单的应用程序,该应用程序在按下特定按钮时播放特定声音,并带有两个分段控制选项(如下图所示)。我在 YouTube、stack 和其他网站上查找了很多教程,但它们似乎都给了我很多错误,或者对我来说太难理解了(因为我太没有经验了)。

我的一些尝试,但这仅适用于 1 个按钮和 1 个声音。

import UIKit
import AVFoundation

class ViewController: UIViewController {
    // make sure to add this sound to your project
    var pianoSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("C", ofType: "m4a"))
    var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()
        audioPlayer = AVAudioPlayer(contentsOfURL: pianoSound, error: nil)
        audioPlayer.prepareToPlay()
    }

    @IBAction func PianoC(sender: AnyObject) {
        audioPlayer.play()
    }
}

请教我如何制作这个应用程序,如下图所示?

http://imgur.com/tWgCDWD

必选:三个按钮(猫、狗、鸟),每个按钮都有自己的声音。和第一个分段(声音)用于启用或禁用声音,例如。当用户选择关闭声音选项时,即使单击按钮也不会发出声音,第二个分段用于启用或禁用背景音乐。

【问题讨论】:

  • 不清楚你想做什么。您的分段控件和 3 个按钮有 4 种可能的组合。在 4 种不同的可能状态下,每个按钮应该播放什么声音?

标签: ios swift audio


【解决方案1】:

因此,创建一个按名称播放声音的方法,并让每个按钮操作调用该方法。还让每个方法在开始播放该声音之前检查您的播放声音开关的状态。

@IBOutlet weak playSoundSwitch: UISwitch!

var backgroundMusicPlayer: AVAudioPlayer?

@discardableResult func playSound(named soundName: String) -> AVAudioPlayer {
    var soundURL = NSURL(fileURLWithPath: 
      NSBundle.mainBundle().pathForResource(soundName, ofType: "m4a"))
    audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil)
    ( it MUST be a class variable )
    audioPlayer.play()
    return audioPlayer
}

@IBAction func catButtonPressed(sender: AnyObject) {
  if playSoundSwitch.isOn {
    playSound("catSound")
  }
}

@IBAction func dogButtonPressed(sender: AnyObject) {
  if playSoundSwitch.isOn {
    playSound("dogSound")
  }
}

@IBAction func birdButtonPressed(sender: AnyObject) {
  if playSoundSwitch.isOn {
    playSound("birdSound")
  }
}

@IBAction func playBackgroundMusicSwitchChanged(sender: UISwitch) {
  if sender.isOn {
    backgroundMusicPlayer = playSound("backgroundSound")
  } else {
    backgroundMusicPlayer?.stop()
    backgroundMusicPlayer = nil
  }
}

以上假设您的背景音乐声音足够长,可以持续整个会话。如果您需要在每次结束时重复声音,那将更加复杂。您必须将自己设置为声音播放器的代表,并在每次结束时重新启动它。您将使用 audioPlayerDidFinishPlaying(_:successfully:) 委托方法。

如果您希望播放声音开关提前终止当前声音,您需要添加逻辑来处理它。同样,如果您想一次只允许一种动物的声音,则必须为 that 添加逻辑。

(上面的代码在 SO 编辑器中被打掉了。它可能包含需要清理的小语法错误。它仅作为指导,而不是复制/粘贴代码。)

最新语法..

import AVFoundation
class yourClass {
    var _sfx: AVAudioPlayer? // IT >MUST< BE a class variable
    func sound(named: String) {

        let u = Bundle.main.path(forResource: named, ofType: "m4a")!
        let s = URL(fileURLWithPath:u)
        do {
            _sfx = try AVAudioPlayer(contentsOf: s)
            _sfx.play()

            // note, you >CAN NOT< say here ..
            // let variable = try AVAudioPlayer(contentsOf: s)
            // IT >MUST< BE a class variable
        }
        catch { print("WOE!"); return }
        print("PLAYED \(named)")
    }

【讨论】:

  • 谢谢!我对代码做了一点修改,现在可以正常工作了。
  • 我弹出了最新的语法,帮派(随意编辑!)
【解决方案2】:
import UIKit
import AVFoundation

class ViewController: UIViewController {

    @IBOutlet weak var playSoundSwitch: UISegmentedControl!

    var backgroundMusicPlayer: AVAudioPlayer?

    var player:AVAudioPlayer = AVAudioPlayer()

    @discardableResult func playSound(named soundName: String) -> AVAudioPlayer {


        let audioPath = Bundle.main.path(forResource: soundName, ofType: "wav")
        player = try! AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
        player.play()
        return player
    }


    @IBAction func catButtonPressed(_ sender: Any) {

        if playSoundSwitch.selectedSegmentIndex == 0 {
            playSound(named: "catSound")
        }


    }

    @IBAction func dogButtonPressed(_ sender: Any) {
        if playSoundSwitch.selectedSegmentIndex == 0 {
            playSound(named: "dogSound")
        }
    }

    @IBAction func birdButtonPressed(_ sender: Any) {

        if playSoundSwitch.selectedSegmentIndex == 0 {
            playSound(named: "birdSound")
            print("bird sound")
        }
    }

    @IBAction func playBackgroundMusicSwitchChanged(_ sender: Any) {


        if (sender as AnyObject).selectedSegmentIndex == 0 {
            backgroundMusicPlayer = playSound(named: "backgroundSound")
        } else {
            backgroundMusicPlayer?.stop()
            backgroundMusicPlayer = nil
        }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多