How to write code to stop multiple audio files swift? - iphone

good morning
How to write code to stop multiple audio files in this code
I looked for it and did not find anything useful please help me
import UIKit
import AVFoundation
class ViewController: UIViewController {
let soundFilenames = ["001" , "002" , "003" , "004" , "005" , "006" , "007" , "008"]
var Audios = [AVAudioPlayer]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for sound in soundFilenames {
do {
let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(sound, ofType: "mp3")!)
let audioPlayer = try AVAudioPlayer(contentsOfURL: url)
Audios.append(audioPlayer)
}catch{
Audios.append(AVAudioPlayer())
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func buttun001(sender: UIButton) {
let audioplayer = Audios [sender.tag]
audioplayer.play()
}
}

Use a normal loop, check if is playing and stop the ones playing
func stopAudios(){
for audioPLayer in Audios{
if audioPLayer.playing{
audioPLayer.stop()
}
}
}
Also don't forget to prepare your AVAudioPlayer
audioPlayer.prepareToPlay()

Related

Do you need to ask for permission to use the microphone when running an app in simulator?

I Created a simple audio player/recorder player using AVAudioPlayer and AVAudioRecorder. The audio player works as expected but the audio recorder doesn't seem to record or playback the recording even though it builds successfully without any errors. Im wondering if it needs permission to the mic? I'm using version 11.X The code is below any help is much appreciated.
import UIKit
import AVFoundation //must import AVFoundation
class ViewController: UIViewController {
// create property called audioPlayer equal to player
var audioPlayer : AVAudioPlayer?
var audioRecorder : AVAudioRecorder?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//create the audio session
let session = AVAudioSession.sharedInstance()
//set category where we want it to happen (PlayAndRecord) try? = if it doesnt work then set it nil
try? session.setCategory(AVAudioSession.Category.playAndRecord)
//play any audio through device speaker
try? session.overrideOutputAudioPort(.speaker)
// set the session to active, if it doesnt work se it to nil
try? session.setActive(true)
//setup the recording and settings to where audio will be saved (Document folder on device) and set the name and file type (iloveaudio.mp3)
if let basePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
let paths = [basePath, "iloveaudioios.mp3"]
if let audioURL = NSURL.fileURL(withPathComponents: paths) {
//create a settings dictionary> orignally it's set to empty using ([:])
var settings : [String : Any] = [:]
//set the file type to mp3
settings[AVFormatIDKey] = Int(kAudioFileMP3Type)
//set the sample rate
settings[AVSampleRateKey] = 44100.0
//set number of channels
settings[AVNumberOfChannelsKey] = 2
// specify the path and settings using var and try to run the recorder if it faile set it to nil
audioRecorder = try? AVAudioRecorder(url: audioURL, settings: settings)
//prepare the recorder of ot fails set it to nil
audioRecorder?.prepareToRecord()
}
}
playerSetup(audioURL: nil)
}
//which file to play if something is recorded
func playerSetup(audioURL:URL?) {
if audioURL == nil {
if let audioPath = Bundle.main.path(forResource: "testaudio", ofType: "mp3") {
let tempAudioURL = URL(fileURLWithPath: audioPath)
audioPlayer = try? AVAudioPlayer(contentsOf: tempAudioURL)
}
} else {
audioPlayer = try? AVAudioPlayer(contentsOf: audioURL!)
}
//check if our audio fille exist? and set it to the proerty audioPath
audioPlayer?.prepareToPlay()
//create audio player, make sure it not nil and if its not the prepare to play, then play
}
#IBAction func PlayPressed(_ sender: Any) {
audioPlayer?.play()
}
#IBAction func Pausedpressed(_ sender: Any) {
audioPlayer?.pause()
}
#IBAction func Stop(_ sender: Any) {
audioPlayer?.stop()
audioPlayer?.currentTime = 0
}
#IBAction func Record(_ sender: Any) {
if let recorder = audioRecorder {
if !recorder.isRecording {
recorder.record()
}
}
}
#IBAction func StopRecord(_ sender: Any) {
if let recorder = audioRecorder {
if recorder.isRecording {
recorder.stop()
playerSetup(audioURL: recorder.url)
}
}
}
}
Yes , You need to add Permission in info.plist
Go to info.plist of your project
Add Privacy - Microphone Usage Description and set it's Value YES(true)
After Setting , when you'll start recording in your app for the first time it will ask for permission , Allow that and you're all set !

Play sound with AKAudioPlayer - iOS

How to declare AKAudioPlayer?
I'm using AudioKit Lib and I just need help to play .wav file with change file button.
import UIKit
import AudioKit
class ViewController: UIViewController {
let file = NSBundle.mainBundle().pathForResource("song", ofType: "wav")
let song = AKAudioPlayer(file!) // <--- ERROR = instance member 'file' cannot be used on type
override func viewDidLoad() {
super.viewDidLoad()
AudioKit.output = song
AudioKit.start()
song.play()
}
#IBAction func btn(sender: AnyObject) {
song.replaceFile("NewFile")
song.play()
}
}
This is a very fast solution to your problem. It can be done better but at least you can get the idea.
First try to make a new class with a function to play your file and then another function to reload your new replacement file like this.
class PlayMyMusic {
var songFile = NSBundle.mainBundle()
var player: AKAudioPlayer!
func play(file: String, type: String) -> AKAudioPlayer {
let song = songFile.pathForResource(file, ofType: type)
player = AKAudioPlayer(song!)
return player
}
func rePlay(file: String, type: String, curPlay: AKAudioPlayer) {
let song = songFile.pathForResource(file, ofType: type)
curPlay.stop()
curPlay.replaceFile(song!)
curPlay.play()
}
}
Initiate the class inside your view
class testViewController: UIViewController {
let doPlay = PlayMyMusic().play("A", type: "wav")
.........
.........
Play your music inside your view
override func viewDidLoad() {
super.viewDidLoad()
AudioKit.output = self.doPlay
AudioKit.start()
doPlay.looping = true
doPlay.play()
}
Then when you want to reload a new file use the rePlay function
#IBAction func btn(sender: AnyObject) {
PlayMyMusic().rePlay("C", type: "wav", curPlay: self.doPlay)
}
take look on AudioKit playground
update
AKAudioPlayer is deprecated, use AudioPlayer insted and check AudioKit v5 Migration Guide

Incorrect argument label in call?

Help me, please!!! I've only recently started programming in Swift. This is my first project. I get the errormessage: "Incorrect argument label in call". This is my code:
import UIKit
import AVFoundation
class PlaySoundsViewController: UIViewController {
var audioPlayer:AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if var filePath = NSBundle.mainBundle().pathForResource("psl",ofType: "mp3"){
var filePathUrl = NSURL.fileURLWithPath(filePath)
audioPlayer = AVAudioPlayer(contentsOfURL: filePathUrl, error: nil)
}else {
print("the filepath is empty")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func playSoundSlow(sender: UIButton) {
audioPlayer.play()
I'm not sure what went wrong here is another picture of my code so you can also see the errormessage.My Code
I'm trying to get it to play a mp3 called psl.mp3.
Please, help me!!! I just started and don't know what to do.
P.S. Not a native Englishspeaker, so sorry for mistakes.
Swift 2 adds new error handling, meaning you don't even have to pass in an error parameter:
audioPlayer = try! AVAudioPlayer(contentsOfURL: filePathUrl)
This initializer throws, meaning if there is an error, you can catch it in a do-catch statement. However, since you passed nil for the error parameter, I'm assuming you are sure the player is there. That's why I used try! without a do-catch instead of try in a do-catch.
Read about the new error handling here.
Try this
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL.fileURLWithPath(path))
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch {
print("Catch error in playUsingAudioPlayer")
}

Integrate iAd pre-roll video integration in my app?

I want to integrate an iAd Pre-Roll video Ad to my application. When I run this application, it gives me this error:
Domain=ADErrorDomain Code=0 "The operation couldn’t be completed. (ADErrorDomain error 0.)
I want to know if this code is correct or incorrect. Thanks for your help.
import UIKit
import MediaPlayer
import iAd
class ViewController: UIViewController {
var moviePlayer : MPMoviePlayerController!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSBundle.mainBundle().URLForResource("intro", withExtension: "mp4")
moviePlayer = MPMoviePlayerController(contentURL: url)
moviePlayer!.view.frame = view.frame
moviePlayer!.prepareToPlay()
view.addSubview(moviePlayer!.view!)
moviePlayer.playPrerollAdWithCompletionHandler { (error) -> Void in
NSLog("\(error)")
self.moviePlayer.play()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This is one of my modified App Delegate function:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
MPMoviePlayerController.preparePrerollAds()
return true
}
You're trying to display your Pre-Roll Video Ad before your application has had any time to download it. Fire your moviePlayer.playPrerollAdWithCompletionHandler after a few seconds or move the video to a later point in your intro so your application has time to download the ad. Check my example:
import UIKit
import MediaPlayer
import iAd
class ViewController: UIViewController {
// Create our MPMoviePlayerController
var moviePlayer = MPMoviePlayerController()
override func viewDidLoad() {
super.viewDidLoad()
// Preload ad
MPMoviePlayerController.preparePrerollAds()
// Setup our MPMoviePlayerController
moviePlayer.view.frame = self.view.bounds
moviePlayer.setFullscreen(true, animated: true)
}
#IBAction func playVideoButton(sender: AnyObject) {
// Add our MPMoviePlayerController to our view
self.view.addSubview(moviePlayer.view)
// Path of video you want to play
let videoURL = NSBundle.mainBundle().URLForResource("videoName", withExtension:"MOV")
// Set the contents of our MPMoviePlayerController to our video path
moviePlayer.contentURL = videoURL
// Prepare our movie for playback
moviePlayer.prepareToPlay()
// Play our video with a prerolled ad
moviePlayer.playPrerollAdWithCompletionHandler { (error) -> Void in
if (error) != nil {
NSLog("\(error)")
}
self.moviePlayer.play()
}
}
Tapping the UIButton playVideoButton a few seconds after application launch will play the prerolled video advertisement and then the desired video.
Also, If you're testing on your device go to Settings>Developer>Fill Rate> and make sure it is set to 100%.

Streaming .m3u8 using MPMoviePlayerController does not work

I used the example in how to play a local video and tried to modify for use on .m3u8 file. I am unable to make it work. I get a blank screen. I confirmed that the file was ok by testing on VLC. Any help would be appreciated.
Here is the code:
import UIKit
import MediaPlayer
class ViewController: UIViewController {
var moviePlayer : MPMoviePlayerController?
override func viewDidLoad() {
super.viewDidLoad()
playVideo()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func playVideo() {
let path = "http://qthttp.apple.com.edgesuite.net/1010qwoeiuryfg/sl.m3u8"
if let
//path = NSBundle.mainBundle().pathForResource("movie", ofType:"m4v"),
url = NSURL(fileURLWithPath: path),
moviePlayer = MPMoviePlayerController(contentURL: url) {
self.moviePlayer = moviePlayer
moviePlayer.view.frame = self.view.bounds
moviePlayer.prepareToPlay()
moviePlayer.scalingMode = .AspectFill
self.view.addSubview(moviePlayer.view)
} else {
debugPrintln("Ops, something wrong when playing .m3u8 file")
}
}
}
You've specified your url incorrectly. Change it to this:
url = NSURL(string:path)