2014-09-09 22 views
11

Sono molto principiante della programmazione e inizio a studiare Swift per creare un'app per pianoforte per divertimento.Swift, come riprodurre il suono quando si preme un pulsante

Ho difficoltà a riprodurre un suono quando si preme un pulsante. Ho cercato qualche sito, ma sto troppo principiante a capire ...

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

per favore potete dirmi come posso giocare il mio suono "C.m4a" quando si preme un "PainoC "pulsante?

Qui è la mia "vista controller.swift"

Grazie in anticipo.

import UIKit 

class ViewController: UIViewController { 

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

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

@IBAction func PianoC(sender: AnyObject) { 
} 

} 

risposta

21

Spero che ti possa aiutare.

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

siete i benvenuti! Fammi sapere se funziona bene, quindi possiamo chiudere questa domanda. – gabriel

+0

grazie per la tua risposta, apprezzo molto. scusa non sono abituato ad aggiungere commenti ,,, non funziona e ti ho risposto rispondendo ... –

+0

dopo aver studiato Xcode e Swift per un po 'e ora capisco la tua risposta. Ha funzionato! Grazie mille! –

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

Si prega di non pubblicare [risposte simili] (http://stackoverflow.com/a/39435255/2227743). Ad ogni modo, se una domanda ha già una risposta disponibile, * contrassegna la domanda come duplicata * invece di rispondere. Grazie. – Moritz

+0

@Eric Aya Guarda il mio codice .. È diverso dalla risposta di cui sopra .. Io uso il metodo try and catch per la gestione degli errori che è necessario in x-code Versione 7.1 (7B91b) per il nuovo swift –

+0

Non stavo parlando del risposte * qui *. Il problema è che hai postato una risposta * simile a quella che hai già pubblicato * sull'altra pagina. Ecco perché ti ho detto di evitare di postare duplicati e di segnalare invece la domanda. – Moritz

9

Swift 3

la sintassi è la seguente: prima aggiungere import AVFoundation sulla parte superiore del codice di accesso alla 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

In 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

a 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") 
     } 
} 
Problemi correlati