Need help adding an audio file to a button in swift [closed] - xcode

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 months ago.
Improve this question
can anyone help me get this to work I am a noob programer and I could not find a way to do this.
Code below
import UIKit
class ViewController: UIViewController {
#IBAction func pistolButton(sender: AnyObject) {
}
override func viewDidLoad() { // I want my audio file to play when button is tapped
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

First drag your sound to your project and choose to copy for your destination if needed and check "add to target" to your app. Create a function to play your sound and you need also to add import AVFoundation at the beginning of your code as bellow:
import AVFoundation
let beepSoundURL = NSBundle.mainBundle().URLForResource("beep", withExtension: "aif")!
var beepPlayer = AVAudioPlayer()
func playMySound(){
beepPlayer = AVAudioPlayer(contentsOfURL: beepSoundURL, error: nil)
beepPlayer.prepareToPlay()
beepPlayer.play()
}
#IBAction func pistolButton(sender: AnyObject) {
playMySound()
}

There is a lot of pretty good code on Stack Overflow:
Playing a sound with AVAudioPlayer
Here is some example code:
import AVFoundation
var audioPlayer: AVAudioPlayer?
if let path = NSBundle.mainBundle().pathForResource("mysound", ofType: "aiff") {
audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path), fileTypeHint: "aiff", error: nil)
if let sound = audioPlayer {
sound.prepareToPlay()
sound.play()
}
}
from this location:
http://www.reddit.com/r/swift/comments/28izxl/how_do_you_play_a_sound_in_ios/

Swift 3
the syntax is now as follows:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// address of the music file
let music = Bundle.main.path(forResource: "Music", ofType: "mp3")
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: music! ))
}
catch{
print(error)
}
}
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()
}
}

Swift 5.5 version syntax.`
import AVFoundation
let beepSoundURL = Bundle.main.url(forResource: "gosound", withExtension: "wav")
var beepPlayer = AVAudioPlayer()
func playMySound(){
if let soundGo = beepSoundURL {
do {
try beepPlayer = AVAudioPlayer(contentsOf: soundGo, fileTypeHint: nil)
}
catch {
print ("error")
}
}
beepPlayer.prepareToPlay()
beepPlayer.play()
}
#IBAction func pistolButton(sender: AnyObject) {
playMySound()
}

Related

Need to press 2 times a button to have the right video playing

I have a view with a series of action buttons. All these buttons are connected to a function that allows me to play a video. I retrieve the name of the video in the button title. The problem is that I need to press the button twice to get the right video, otherwise the last video is playing
Here is the code that is associated.
import UIKit
import AVKit
import AVFoundation
class levresViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var varVue2="toto"
var playerController = AVPlayerViewController()
var player:AVPlayer?
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let videoString:String? = Bundle.main.path(forResource: varVue2, ofType: ".mp4")
if let url = videoString {
let videoURL=NSURL(fileURLWithPath: url)
self.player = AVPlayer(url: videoURL as URL)
self.playerController.player = self.player
}
// Do any additional setup after loading the view.
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func playVideo(_ sender: UIButton) {
varVue2=sender.currentTitle!
self.present(self.playerController,animated:true,completion:{
self.playerController.player?.play()
})
}
}

two sounds play on one button in swift

i have three buttons and each are supposed to play a different sound which they do. My problem is that the second button once clicked also plays the first sound.
is there something i could do to fix this?
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
var audioPlayer1 = AVAudioPlayer()
var audioPlayer2 = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "OhNo", ofType: "mp3")! ))
audioPlayer.prepareToPlay()
}
catch{
print(error)
}
do {
audioPlayer1 = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "beep2", ofType: "mp3")! ))
audioPlayer1.prepareToPlay()
}
catch{
print(error)
}
do {
audioPlayer2 = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "beep10", ofType: "mp3")! ))
audioPlayer2.prepareToPlay()
}
catch{
print(error)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func catSound(_ sender: UIButton) {
audioPlayer.play()
}
#IBAction func beep(_ sender: UIButton) {
audioPlayer1.play()
}
#IBAction func beep10(_ sender: UIButton) {
audioPlayer2.play()
}
}
Check your storyboard and make sure you haven't connected the second button to both the first and second #IBAction.
Do this buy right-clicking on the second button in the storyboard. On the Touch up Inside-event there should be only one connection, the beep. On the one where it says catSound, click the little x to remove it.
Can you try stopping the other AudioPlayers?
#IBAction func beep(_ sender: UIButton) {
audioPlayer.stop()
audioPlayer2.stop()
audioPlayer1.play()
}

Playing Audio in Xcode7

I'm simply trying to play audio when I tap a button, but I get an error with this line of code.
ButtonAudioPlayer = AVAudioPlayer(contentsOfURL: ButtonAudioURL, error: nil)
This is my whole code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var ButtonAudioURL = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource("Audio File 1", ofType: "mp3")!)
var ButtonAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
ButtonAudioPlayer = AVAudioPlayer(contentsOfURL: ButtonAudioURL, error: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func playAudio1(sender: UIButton) {
}
}
The error is
Incorrect argument label in call (have 'contentsOfURL:error:', expected 'contentsOfURL:fileTypeHint:').
When I change error to fileTypeHint, it still does not work.
You need to use the new Swift 2 syntax by changing that line to
ButtonAudioPlayer = try! AVAudioPlayer(contentsOfURL: ButtonAudioURL)
The AVAudioPlayer class can throw an error, You need to take this into consideration. I personally prefer a do statement which gives the opportunity to catch and handle the error.
This code worked fine for me:
import UIKit
import AVFoundation
class ViewController: UIViewController {
let ButtonAudioURL = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource("test", ofType: "mp3")!)
let ButtonAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
do {
ButtonAudioPlayer = try AVAudioPlayer(contentsOfURL: ButtonAudioURL, fileTypeHint: ".mp3")
ButtonAudioPlayer.play()
} catch let error {
print("error loading audio: Error: \(error)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You could also make this to an optional, like this:
ButtonAudioPlayer = try AVAudioPlayer(contentsOfURL: ButtonAudioURL, fileTypeHint: ".mp3")
ButtonAudioPlayer?.play()
Using this method it will only attempt to play the file if no error was thrown in the previous statement, but will prevent a runtime error.

Many errors when trying to play video in xcode 7 / Swift 2

I am having trouble playing a video in my view controller. I have a play button and when I press it, I want the video which I imported into xcode to play. Having some errors come up and I am stumped. Any ideas?
import UIKit
import MediaPlayer
import AVFoundation
class AuroraViewController: UIViewController {
var moviePlayer: AVPlayer?
#IBOutlet var AuroraViewController: UIView!
#IBAction func playButtonPressed(sender: AnyObject) {
playVideo()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func playVideo() {
if let path = NSBundle.mainBundle().pathForResource("Aurora", ofType:"mp4") {
let url = NSURL(fileURLWithPath: path)
Here I begin to get errors and need help with what it is complaining about
moviePlayer = AVPlayer(contentURL: url)
self.moviePlayer = moviePlayer
moviePlayer.view.frame = self.view.bounds
moviePlayer.prepareToPlay()
moviePlayer.scalingMode = .AspectFill
view.addSubview(moviePlayer.view)
} else {
debugPrint("oops, something wrong when playing video.m4v")
}
}
}

Swift - Can't Dismiss MPMoviePlayerViewController

I have a video which opens in an MPMoviePlayerController in my app. It all works great except for the Done button which should close the player. The first time that the video is played the Done button works great. But if you pause it when you are watching it, then hit Done the second time you try to play the video, the Done button doesn't work. I have made a screen recording here to make it a bit simpler to understand:
http://1drv.ms/1Jcdodc
Can anyone help?
This is my code that I am using:
import UIKit
import MediaPlayer
class MainContent: UIViewController {
//Movie Player variables
var movieViewController : MPMoviePlayerViewController?
var movieplayer : MPMoviePlayerController!
override func viewDidLoad() {
super.viewDidLoad()
//Video Player setup
NSNotificationCenter.defaultCenter().addObserver(self, selector: "doneButtonClick:", name: MPMoviePlayerPlaybackDidFinishNotification, object: nil)
var url = NSURL(string: "http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v")!
movieViewController = MPMoviePlayerViewController(contentURL: url)
}
func doneButtonClick(sender:NSNotification?){
let value = UIInterfaceOrientation.Portrait.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
}
//when watch button is pressed, present the movie player
#IBAction func watchPressed(sender: AnyObject)
{self.presentMoviePlayerViewControllerAnimated(movieViewController)}
}
To fix this issue, I added the myMoviePlayerViewController.moviePlayer.stop() to the 'doneButtonClick' function. I then added the myMoviePlayerViewController.moviePlayer.play() again to the
#IBAction func watchPressed(sender: AnyObject)
{self.presentMoviePlayerViewControllerAnimated(movieViewController)}
}
So all in all a simple fix! Code is below:
import UIKit
import MediaPlayer
class MainContent: UIViewController {
//Movie Player variables
var movieViewController : MPMoviePlayerViewController?
var movieplayer : MPMoviePlayerController!
override func viewDidLoad() {
super.viewDidLoad()
//Video Player setup
NSNotificationCenter.defaultCenter().addObserver(self, selector: "doneButtonClick:", name: MPMoviePlayerPlaybackDidFinishNotification, object: nil)
var url = NSURL(string: "http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v")!
movieViewController = MPMoviePlayerViewController(contentURL: url)
}
func doneButtonClick(sender:NSNotification?){
let value = UIInterfaceOrientation.Portrait.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
movieViewController?.moviePlayer.stop()
}
#IBAction func watchPressed(sender: AnyObject){
self.presentMoviePlayerViewControllerAnimated(movieViewController)
movieViewController?.moviePlayer.play()
}
}

Resources