I need to create a button where when I press it, just one sounds gets played. When I press it again, I want a different sound to get play. I have 4 sounds that I want to get played randomly. Therefor when I press the button let's say 8 times, I will hear 8 sounds, randomly.
I put the sound file names in an array and implemented the arc4random to randomise. I am working with AVFoundation and that's where I get stuck. I do not know how to play this array.
I know how to play 1 sound, but not how to implement this in the button. Anyone any idea?
import UIKit
import AVFoundation
class ViewController: UIViewController {
let soundFilenames = ["sound_1.mp3", "sound_2.mp3"]
let randomIndex = Int(arc4random_uniform(UInt32(soundFilenames.count)))
let selectedFilename = soundFilenames[randomIndex]
#IBAction func tap(sender: UIButton) {
// Audio code?
}
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.
}
}
Edit :
#IBAction func tap(sender: UIButton) {
let soundFilenames = ["Sound1.mp3", "Sound2.mp3"]
let randomIndex = Int(arc4random_uniform(UInt32(soundFilenames.count)))
let selectedFilename = soundFilenames[randomIndex]
let sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("selectedFilename", ofType: "mp3")!)
var audioPlayer : AVAudioPlayer?
audioPlayer = AVAudioPlayer(contentsOfURL: sound, error: nil)
audioPlayer!.prepareToPlay()
audioPlayer!.play()
}
Edit 2 :
var audioPlayer : AVAudioPlayer?
#IBAction func tap(sender: UIButton) {
let soundFilenames = ["Sound1", "Sound2"]
let randomIndex = Int(arc4random_uniform(UInt32(soundFilenames.count)))
let selectedFilename = soundFilenames[randomIndex]
let sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("selectedFilename", ofType: "mp3")!)
audioPlayer = AVAudioPlayer(contentsOfURL: sound, error: nil)
audioPlayer!.prepareToPlay()
audioPlayer!.play()
}
If that is your exact copy/pasted code, your let sound statement could use a proofread.
let sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("selectedFilename", ofType: "mp3")!)
not
let sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("selectedFilemane", ofType: "mp3")!)
You mentioned you know how to play a sound, but have you done that yet with this code?
Related
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()
})
}
}
how would I go about using Swift & AppleTV4 to display a video that is inside the XcodeProj? Can I use the AVPlayer to also play an Mp3 later?
This is what I have:
import UIKit
import AVFoundation
import AVKit
import MediaPlayer
class ViewController: UIViewController {
let videoplayer = AVPlayer(URL: NSURL(string: "file.mp4")!)
let audioplayer = AVPlayer(URL: NSURL(string: "file.mp3")!)
#IBOutlet weak var Buttonizer: UIButton!
#IBAction func ButtonPressed(sender: AnyObject) {
videoplayer.play()
audioplayer.play()
// let videoplayer = AVPlayer(URL: NSURL(string: "https://clips.vorwaerts-gmbh.de/VfE_html5.mp4")!)
}
and the rest.. (viewDidLoad stuff)
I tried to run AVPlayer with an external mp4, but the videoplayer.play() simply crashes with a breakcode.
Try this to play a video in AVPlayer:
let path = NSBundle.mainBundle().pathForResource("test", ofType:"mp4")!
let videoURL = NSURL(fileURLWithPath: path)
let player = AVPlayer(URL: videoURL)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()
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.
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")
}
}
}
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()
}
}