There are multiple classes in which the AVAudioPlayer? instances are created like so
var player: AVAudioPlayer?
var player2: AVAudioPlayer?
Now is there a way I can stop these multiple instances in a different class , tried to create a function and stop all sounds but it does not work , can any one suggest a way to stop all sounds in app, but also one that I can disable at viewWillappear so its not permanently stop all sound
func stopAllSounds() {
var demoView1 = Demo1ViewController()
var player1 = demoView1.player
var demoView2 = Demo2ViewController()
var player2 = demoView2.player
var demoView3 = Demo3ViewController()
var player3 = demoView3.player
var allPlayer: [AVAudioPlayer?] = [player1, player2, player3]
for stopData in allPlayer {
stopData?.stop()
stopData?.currentTime = 0
}
}
The function I call on viewDidload
func playSound() {
guard let path = Bundle.main.path(forResource: "demosound", ofType:"wav") else {
return }
let url = URL(fileURLWithPath: path)
do {
player = try AVAudioPlayer(contentsOf: url)
player?.volume = 1.0
player?.play()
Utility.avPLayers.append(player!) <—— add the instance
} catch let error {
print(error.localizedDescription)
}
}
Related
I'm having some difficulty with the following formula in Google Scripts. What I would like to achieve, is:
1- get Number from A1
2- from Number, have multiple returns
3- set those returns in the same row (A) as original Number, in neighboring cells (A2, A3)
What it looks like now:
function GETALLTWO(bid) {
if (input.map) {
return input.map(GETALLTWO)
} else {
return input;
}
var api_str = "client_id=randomstringofnumbers&client_secret=anotherrandomstringofnumbers";
var url= "https://api.untappd.com/v4/beer/info/" + bid + "?" + api_str;
var response = UrlFetchApp.fetch(url);
if (response.getResponseCode() == 200) {
var respObj = JSON.parse(response.getContentText());
var beer = respObj.response.beer;
if (beer.bid == bid) {
return beer.beer_name;
return beer.rating_score;
return beer.stats.total_user_count;
return beer.rating_count;
return beer.stats.monthly_count;
return beer.created_at;
}
}
}
From Code.gs, I can get the first Return to work, but am I combining the different functions correctly? And how would I set the location to return?
Hope someone can help, would love to learn more about scripting.
// Edit for future reference:
function getAll(bid) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Overview')
var row=sh.getActiveCell().getRow();
var bid=sh.getRange(row,3).getValue();
var api_str = "client_id=randomstring&client_secret=randomstring";
var url= "https://api.untappd.com/v4/beer/info/" + bid + "?" + api_str;
var response = UrlFetchApp.fetch(url);
if (response.getResponseCode() == 200) {
var respObj = JSON.parse(response.getContentText());
var beer = respObj.response.beer;
if (beer.bid == bid) {
var rObj= {name:beer.beer_name,rating:beer.rating_score,totalcount:beer.stats.total_user_count,ratingcount:beer.rating_count,monthlycount:beer.stats.monthly_count,createddate:beer.created_at};
values=[[rObj.name,rObj.ratingcount,rObj.rating,rObj.totalcount,rObj.monthlycount,rObj.createddate]];
return values;
}
}
}
With this function you just need to put your cursor on the row that you want to get the bid from. It will put the data back in that row starting at column D
function getAllTwo() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Your Sheet Name')
var row=sh.getActiveCell().getRow();
var bid=sh.getRange(row,3).getValue();
var api_str = "client_id=randomstringofnumbers&client_secret=anotherrandomstringofnumbers";
var url= "https://api.untappd.com/v4/beer/info/" + bid + "?" + api_str;
var response = UrlFetchApp.fetch(url);
if (response.getResponseCode() == 200) {
var respObj = JSON.parse(response.getContentText());
var beer = respObj.response.beer;
if (beer.bid == bid) {
var rObj= {name:beer.beer_name,rating:beer.rating_score,totalcount:beer.stats.total_user_count,ratingcount:beer.rating_count,monthlycount:beer.stats.monthly_count,createdate:beer.created_at};
values=[[rObj.name,rObj.ratingcount,rObj.rating,rObj.totalcount,rObj.monthlycount,rObj.createddate]];
sh.getRange(row,4,values.length,values[0].length).setValues(values);
}
}
}
As I know this is Simple Approch to save it in a Photo Library. But It can save with custom filename.
var someImage = UIImage.FromFile("someImage.jpg");
someImage.SaveToPhotosAlbum((image, error) => {
var o = image as UIImage;
Console.WriteLine("error:" + error);
})
But I want to save it with filename.jpg in the Photo Library.
I try so much code but nothing is getting help to me.
Code 1 :
var imageName = "/" + dicomId.ToString() + ".jpg";
var documentsDirectory = Environment.GetFolderPath
(Environment.SpecialFolder.Personal);
string jpgFilename = System.IO.Path.Combine(documentsDirectory, imageName); // hardcoded filename, overwritten each time
NSData imgData = dicomImage.AsJPEG();
NSError err = null;
if (imgData.Save(jpgFilename, false, out err))
{
Console.WriteLine("saved as " + jpgFilename);
}
else
{
Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
}
This code part goes to if condition but it can not save the Image.
Code 2 :
If using this part of Code
var documentsDirectoryPath = NSSearchPath.GetDirectories(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User, true)[0];
It give you don't have permission to save image.
I try lots of thing on google and SO but nothing could help to me.
Edit :
info.plist
Any Help would be Appreciated.
How about using UIImage.SaveToPhotosAlbum()?
Usage is something like:
image.SaveToPhotosAlbum((uiImage, nsError) =>
{
if (nsError != null)
// do something about the error..
else
// image should be saved
});
Make sure that you have requested permissions before you try to save.
PHPhotoLibrary.RequestAuthorization(status =>
{
switch (status)
{
case PHAuthorizationStatus.Restricted:
case PHAuthorizationStatus.Denied:
// nope you don't have permission
break;
case PHAuthorizationStatus.Authorized:
// yep it is ok to save
break;
}
});
Edit: if you want more control, you need to use PHPhotosLibrary, which is an awful API...
var library = PHPhotoLibrary.SharedPhotoLibrary;
var albumName = "MyPhotos";
var fetchOptions = new PHFetchOptions();
fetchOptions.Predicate = NSPredicate.FromFormat($"title = {albumName}");
var assetsCollections = PHAssetCollection.FetchAssetCollections(
PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, fetchOptions);
var collection = assetsCollections.firstObject as PHAssetCollection;
library.PerformChanges(() => {
var options = new PHAssetResourceCreationOptions();
options.OriginalFilename = "filename.jpg";
var createRequest = PHAssetCreationRequest.CreationRequestForAsset();
createRequest.AddResource(PHAssetResourceType.FullSizePhoto, image.AsJPEG(1), options);
// if you want to save to specific album... otherwise just remove these three lines
var placeholder = createRequest.PlaceholderForCreatedAsset;
var albumChangeRequest = PHAssetCollectionChangeRequest.ChangeRequest(collection);
albumChangeRequest.AddAssets(new PHObject[] { placeholder });
},
(ok, error) => {
if (error != null)
{
// someone set up us the bomb
}
});
I am trying Vision kit for iOS 11. I can use Vision and I can find boundbox values face. But I don't know how can I draw a rectangle using this points. I hope so my question is clear.
Hope you were able to use VNDetectFaceRectanglesRequest and able to detect faces. To show rectangle boxes there are lots of ways to achieve it. But simplest one would be using CAShapeLayer to draw layer on top your image for each face you detected.
Consider you have VNDetectFaceRectanglesRequest like below
let request = VNDetectFaceRectanglesRequest { [unowned self] request, error in
if let error = error {
// somthing is not working as expected
}
else {
// we got some face detected
self.handleFaces(with: request)
}
}
let handler = VNImageRequestHandler(ciImage: ciImage, options: [:])
do {
try handler.perform([request])
}
catch {
// catch exception if any
}
You can implement a simple method called handleFace for each face detected and use VNFaceObservation property to draw a CAShapeLayer.
func handleFaces(with request: VNRequest) {
imageView.layer.sublayers?.forEach { layer in
layer.removeFromSuperlayer()
}
guard let observations = request.results as? [VNFaceObservation] else {
return
}
observations.forEach { observation in
let boundingBox = observation.boundingBox
let size = CGSize(width: boundingBox.width * imageView.bounds.width,
height: boundingBox.height * imageView.bounds.height)
let origin = CGPoint(x: boundingBox.minX * imageView.bounds.width,
y: (1 - observation.boundingBox.minY) * imageView.bounds.height - size.height)
let layer = CAShapeLayer()
layer.frame = CGRect(origin: origin, size: size)
layer.borderColor = UIColor.red.cgColor
layer.borderWidth = 2
imageView.layer.addSublayer(layer)
}
}
More info can be found here in Github repo iOS-11-by-Examples
Here is easy and simple way to draw boxes.
let faceRequest = VNDetectFaceRectanglesRequest(completionHandler:self.faceDetection)
func faceDetection (request: VNRequest, error: Error?) {
guard let observations = request.results as? [VNFaceObservation]
else { print("unexpected result type from VNFaceObservation")
return }
guard observations.first != nil else {
return
}
// Show the pre-processed image
DispatchQueue.main.async {
self.resultImageView.subviews.forEach({ (subview) in
subview.removeFromSuperview()
})
for face in observations
{
let view = self.CreateBoxView(withColor: UIColor.red)
view.frame = self.transformRect(fromRect: face.boundingBox, toViewRect: self.analyzedImageView)
self.analyzedImageView.image = self.originalImageView.image
self.resultImageView.addSubview(view)
}
}
}
//MARK - Instance Methods
func boxView(withColor : UIColor) -> UIView {
let view = UIView()
view.layer.borderColor = withColor.cgColor
view.layer.borderWidth = 2.0
view.backgroundColor = UIColor.clear
return view
}
//Convert Vision Frame to UIKit Frame
func transformRect(fromRect: CGRect , toViewRect :UIView) -> CGRect {
var toRect = CGRect()
toRect.size.width = fromRect.size.width * toViewRect.frame.size.width
toRect.size.height = fromRect.size.height * toViewRect.frame.size.height
toRect.origin.y = (toViewRect.frame.height) - (toViewRect.frame.height * fromRect.origin.y )
toRect.origin.y = toRect.origin.y - toRect.size.height
toRect.origin.x = fromRect.origin.x * toViewRect.frame.size.width
return toRect
}
Struggling with how to iterate through an array of SKShapeNodes. I seem to be able to go through it in DidMoveToView(), but, not WhenTouchesBegan().
From GameScene.swift:
class GameScene: SKScene {
...
var areaTwo = SKShapeNode()
var areaThree = SKShapeNode()
var areaFour = SKShapeNode()
var currentArea = SKShapeNode()
//CGPaths as UIBezierPaths set here
var areas = [SKShapeNode]()
override func didMoveToView(view: SKView) {
...
areaTwo = SKShapeNode(path: areaTwoPath.CGPath)
areaThree = SKShapeNode(path: areaThreePath.CGPath)
areaFour = SKShapeNode(path: areaFourPath.CGPath)
let areas = [areaTwo, areaThree, areaFour]
...
//this works
for area in areas {
area.lineWidth = 4
addChild(area)
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
for touch in touches {
let location = touch.locationInNode(self)
currentArea.fillColor = UIColor.clearColor()
//this does not work! No errors thrown. Just doesn't seem to do anything.
for area in areas{
currentArea = area
if currentArea.containsPoint(location) {
currentArea.fillColor = UIColor.redColor()
}
}
}
}
What is frustrating is if I use a series of if...else if...else if I can check every single area, but, can't check them through the array.
not quite clear about your target. if you simply want a way to iterate child nodes, you can try
//init child nodes
for i in 1...2{
let areaNode = SKShapeNode()
...
areaNode.name = "area"
parentNode.addChild(areaNode)
}
//iteration
for node in parentNode.children{
if node.name == "area"{
print("here we find a child area")
}else{
print("some irrelevant node found")
}
}
Btw, the reason why your code in didMoveToView() work is you declared an new areas array, which in fact is an in-method variable replaced the role of previous class property areas
I’m new to Backbone, but I’ve successfully been able to define an array like this on one of my models:
buildMyArray: function() {
var self = this;
var myArray = {};
window.myLibrary.getStuff('myParameter', function(myStuff) {
for (var myKey in myStuff) {
if (myStuff.hasOwnProperty(myKey)) {
var myValue = myStuff[myKey];
myArray[myKey] = myValue;
}
}
self.set({ myArray: myArray });
});
}
However, how can I access that array from other properties? In other words, I want to do something like this:
checkArrayStuff: function(arrayKey) {
//loop through myArray and check value for arrayKey.
//var myArray1 = self.get(myArray);
//var myArray2 = this.get(myArray);
//var myArray3 = myArray;
//var myArray4 = this.myArray;
//var myArray5 = self.get('myArray');
//var myArray6 = this.get('myArray');
var myArray7 = self.myArray;
var can = myArray7[arrayKey];
return can;
}
I’ve tried several variations of self, this, with-and-without-quotes, with-and-without get-method, etc.
I guess you would have to do this
checkArrayStuff: function(arrayKey) {
return this.get('myArray')[arrayKey];
}
this.get('myArray') should work but it looks like your window.myLibrary.getStuff function is asynchronous. That means myArray won't be set until some time after buildMyArray returns. If you give us more context we can make a better recommendation of how to address this such as having buildMyArray call checkArrayStuff after it's done the .set(..) or having buildMyArray return a promise