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.
Related
I currently have my app linking to a certain URL upon opening the app, and this obviously can have a delay between opening it and the webView actually loading, so I want it to display an activity indicator whenever the webView is loading, I have the following code in my ViewController.swift:
class ViewController: UIViewController, UIWebViewDelegate {
#IBOutlet weak var webView: UIWebView!
#IBOutlet weak var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
let url = URL(string: "url to site")
webView.loadRequest(URLRequest(url: url!)
}
func webViewDidStartLoad(webView: UIWebView){
activityIndicator.startAnimating()
}
func webViewDidFinishLoad(webView: UIWebView){
activityIndicator.stopAnimating()
}
The activity indicator shows up from the beginning but it does not disappear once the webView loads and stays their forever.
The way you have your code organized is a bit confusing. It appears you are declaring your funcs inside the #IBAction function. If this is the case, this will not work.
Try this instead
class ViewController: UIViewController, UIWebviewDelegate {
override func viewDidLoad() {
...
webView.delegate = self
// You should add this to your Storyboard, above the webview instead of here in the code
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
// I forget the actual method name - look it up
view.insertSubview(activityIndicator, above: webView)
}
#IBAction func openButton(_ sender: Any) {
let url = URL(string: "websiteURL")
webView.loadRequest(URLRequest(url: url!))
}
func webViewDidStartLoad(webView: UIWebView){
activityIndicator.startAnimating()
}
func webViewDidFinishLoad(webView: UIWebView){
activityIndicator.stopAnimating()
}
// You'll also want to add the "didFail" method
}
The issue is a syntax issue, you have to add an underscore in the functions.
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
let url = URL(string: "your URL")
webView.loadRequest(URLRequest(url: url!))
}
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool{
activityIndicator.startAnimating()
return true
}
func webViewDidStartLoad(_ webView: UIWebView){
activityIndicator.startAnimating()
}
func webViewDidFinishLoad(_ webView: UIWebView){
activityIndicator.stopAnimating()
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error){
activityIndicator.stopAnimating()
}
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()
})
}
}
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()
}
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")
}
}
}
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()
}