2014-09-09 2 views
11

Я очень начинаю программировать и начинаю изучать Swift, чтобы сделать приложение для фортепиано для удовольствия.Swift, как играть в звук при нажатии кнопки

У меня есть проблема с воспроизведением звука при нажатии кнопки. Я искал какой-то сайт, но я тоже новичок, чтобы понять ...

http://www.tmroyal.com/playing-sounds-in-swift-avaudioplayer.html http://www.rockhoppertech.com/blog/swift-avfoundation/

Не могли бы вы сказать мне, как я могу играть свою «C.m4a» звук при нажатии «PainoC "кнопка?

Вот мой "вид controller.swift"

Спасибо заранее.

import UIKit 

class ViewController: UIViewController { 

override func viewDidLoad() { 
    super.viewDidLoad() 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
} 

@IBAction func PianoC(sender: AnyObject) { 
} 

} 

ответ

21

Я надеюсь, что это вам поможет.

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() 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 

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

} 
+0

Добро пожаловать! Дайте мне знать, если все будет хорошо, поэтому мы можем закрыть этот вопрос. – gabriel

+0

спасибо за ваш ответ, я действительно ценю. извините, я не привык добавлять комментарий ,,, он не работает, и я ответил вам, отвечая ... –

+0

после изучения Xcode и Swift на некоторое время, и теперь я понимаю ваш ответ. Это сработало! Большое спасибо! –

2
import UIKit 
import AVFoundation 

class ViewController: UIViewController { 
    var audioPlayer = AVAudioPlayer() 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    @IBAction func button1Action(sender: AnyObject) { 
     let CatSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Meow-sounds", ofType: "mp3")!) 
     do { 
      audioPlayer = try AVAudioPlayer(contentsOfURL: CatSound) 
      audioPlayer.prepareToPlay() 
     } catch { 
      print("Problem in getting File") 
     } 
     audioPlayer.play() 
    } 
} 
+0

Пожалуйста, не публикуйте [похожие ответы] (http://stackoverflow.com/a/39435255/2227743). В любом случае, если у вопроса уже есть доступный ответ, * вместо вопроса ответьте на вопрос как дубликат *. Благодарю. – Moritz

+0

@ Эрик Айя Посмотрите на мой код .. Он отличается от предыдущего ответа. Я использую метод try и catch для обработки ошибок, который необходим в x-коде Версия 7.1 (7B91b) для нового swift –

+0

Я не говорил о ответы * здесь *. Проблема в том, что вы отправили ответ *, аналогичный тому, который вы уже разместили * на другой странице. Вот почему я сказал вам избегать публикации дубликатов и вместо этого поставить флаг. – Moritz

9

Swift 3

синтаксис теперь выглядит следующим образом: первая добавить import AVFoundation на верхней части кода, чтобы иметь доступ к AVFoundation Framework.

import UIKit 
import AVFoundation 

class ViewController: UIViewController { 
    //this is your audio playback instance 
    var audioPlayer = AVAudioPlayer() 


    override func viewDidLoad() { 
     super.viewDidLoad() 
     // address of the music file. 
     let music = Bundle.main.path(forResource: "Music", ofType: "mp3") 
     // copy this syntax, it tells the compiler what to do when action is received 
     do { 
      audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: music!)) 
      try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient) 
      try AVAudioSession.sharedInstance().setActive(true) 
     } 
     catch{ 
      print(error) 
     } 

    } 
//this runs the do try statement 
    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    @IBAction func play(_ sender: AnyObject) { 
     audioPlayer.play() 
    } 
    @IBAction func stop(_ sender: AnyObject) { 
     audioPlayer.stop() 
    } 
} 
0

В Swift 3:

import UIKit 
import AVFoundation 

class QuestionView: UIViewController { 

    var btnButton = UIButton() 
    var player = AVAudioPlayer() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     btnButton.frame = CGRect(x: 100, y: 100, width: 100, height: 100) 
     btnButton.backgroundColor = UIColor.blue 
     btnButton.addTarget(self, action: #selector(ButtonSound), for: .touchUpInside) 

    } 

    func ButtonSound() { 

     do { 

      // make sure to add this sound to your project 

      let audioPath = Bundle.main.path(forResource: "Click", ofType: "mp3") 

      try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPath!) as URL) 


     } catch { 

      print("Error !") 

     } 

     player.play() 

    } 

} 
1

В Swift 4:

import AVFoundation 
class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate { 
    let popSound = Bundle.main.url(forResource: "Pop", withExtension: "mp3") 
    var audioPlayer = AVAudioPlayer() 

    override func viewDidLoad() { 
     do { 
      audioPlayer = try AVAudioPlayer(contentsOf: popSound!) 
      audioPlayer.play() 
     } catch { 
      print("couldn't load sound file") 
     } 
} 
Смежные вопросы