I´ve already made an app but now I want to play background audio in my app when it launch with endless loop. I know it´s a dumb question but I would be happy if anybody can help me. Thanks in advance. :)
This is a broad question, but here is one example of what you can do.
Make sure you, above your class declaration, import the AVFoundation framework, like so:
import AVFoundation
If you have a .mp3 file and you want to play it and loop it endlessly, you can use the following code to do so:
var audioPlayer = AVAudioPlayer()
func startAudio() {
let filePath = NSBundle.mainBundle().pathForResource("fileName", ofType: "mp3")
let fileURL = NSURL.fileURLWithPath(filePath!)
do {
audioPlayer = try AVAudioPlayer.init(contentsOfURL: fileURL, fileTypeHint: AVFileTypeMPEGLayer3)
audioPlayer.numberOfLoops = -1
audioPlayer.volume = 1
} catch {
self.presentViewController(UIAlertController.init(title: "Error", message: "Error Message", preferredStyle: .Alert), animated: true, completion: nil)
}
audioPlayer.play()
}
Call this function wherever you want in your controller and the audio should start playing. Hope this helps.
Related
I'm building a small app in node.js that uses execa to read print statements coming from a compiled Swift application. The idea is similar to Sindre Sorhus' (who else!?) do-not-disturb
Although I'm no Swift-programmer, I put together a pretty straightforward solution. The binary is compiled by running swift build --configuration=release from the CL to be used in a node-app. It also compiles fine (without the CLI-part) in a Swift playground from XCode and I can see the correct print statements coming in.
import Cocoa
var isLocked:Bool = false
DistributedNotificationCenter.default().addObserver(forName: .init("com.apple.isScreenLocked"), object: nil, queue: nil) { notification in
print("Screen is locked")
isLocked = true
}
DistributedNotificationCenter.default().addObserver(forName: .init("com.apple.isScreenUnlocked"), object: nil, queue: nil) { notification in
print("Screen is unlocked")
isLocked = false
}
struct CLI {
static var standardInput = FileHandle.standardInput
static var standardOutput = FileHandle.standardOutput
static var standardError = FileHandle.standardError
static let arguments = Array(CommandLine.arguments.dropFirst(1))
}
switch CLI.arguments.first {
case "status":
print(isLocked)
default:
print("Unsupported command", to: .standardError)
exit(1)
}
// Some other functions omitted for brevity
Now, when I run the code below from Node.js, everything seems to be working fine. However for some reason, the observer doesn't receive the notification.
'use strict';
const execa = require('execa');
const electronUtil = require('electron-util/node');
const binary = path.join(electronUtil.fixPathForAsarUnpack(__dirname), 'IsLockedOrNot');
setInterval(async () => {
const {stdout} = await execa(binary, ['status']);
console.log(stdout) // keeps logging false, also when screen is locked
}, 1000)
Does anyone have any idea WHY the notifications are not being received in this scenario? I tried various things, like explicitly disabling sleep mode shell.exec('sudo pmset -a disablesleep 1')and compiling the app with the --disable-sandbox flag. No luck however until know..
Use spawn from the base child_process library not execa, make sure you are following stdout, and the most important part for nodejs and swift is that you flush the buffer after every line. Otherwise you have to wait for the program to die before you receive any output. Use "import Darwin.C" and "fflush(stdout)" after every "print" where you want a 'newline'
I am still new to Vibe.d so forgive me if I am missing something obvious.
I want to upload a file in Vibe.d using the web framework. However, all the examples I find, including the one in the book 'D Web Development', are not using the web framework. If I insert the non-web-framework example to my app, it crashes. It would suck if I have to abandon the web framework just for the sake of one feature, which is file upload.
The Vibe.d documentation is a good effort and I appreciate it but until now it is rather sparse and the examples are few and far between.
Here are some snippets of my code:
shared static this()
{
auto router = new URLRouter;
router.post("/upload", &upload);
router.registerWebInterface(new WebApp);
//router.get("/", staticRedirect("/index.html"));
//router.get("/ws", handleWebSockets(&handleWebSocketConnection));
router.get("*", serveStaticFiles("public/"));
auto settings = new HTTPServerSettings;
settings.port = 8080;
settings.bindAddresses = ["::1", "127.0.0.1"];
listenHTTP(settings, router);
conn = connectMongoDB("127.0.0.1");
appStore = new WebAppStore;
}
void upload(HTTPServerRequest req, HTTPServerResponse res)
{
auto f = "filename" in req.files;
try
{
moveFile(f.tempPath, Path("./public/uploaded/images") ~ f.filename);
}
catch(Exception e)
{
copyFile(f.tempPath, Path("./public/uploaded/images") ~ f.filename);
}
res.redirect("/uploaded");
}
Can I still access the HTTPServerRequest.files using the web framework? How? Or do I still need it? Meaning, is there another way without using HTTPServerRequest.files?
Thanks a lot!
I have totally forgotten about this question. I remember how frustrating it was when you cannot readily find an answer to a question that seems to be elementary to those who already know.
Make sure you state 'multipart/form-data' in the enctype of your form:
form(method="post", action="new_employee", enctype="multipart/form-data")
Then a field in that form should include an input field of type 'file', something like this:
input(type="file", name="picture")
In the postNewEmployee() method of your web framework class, get the file through request.files:
auto pic = "picture" in request.files;
Here is a sample postNewEmployee() method being passed an Employee struct:
void postNewEmployee(Employee emp)
{
Employee e = emp;
string photopath = "No photo submitted";
auto pic = "picture" in request.files;
if(pic !is null)
{
string ext = extension(pic.filename.name);
string[] exts = [".jpg", ".jpeg", ".png", ".gif"];
if(canFind(exts, ext))
{
photopath = "uploads/photos/" ~ e.fname ~ "_" ~ e.lname ~ ext;
string dir = "./public/uploads/photos/";
mkdirRecurse(dir);
string fullpath = dir ~ e.fname ~ "_" ~ e.lname ~ ext;
try moveFile(pic.tempPath, NativePath(fullpath));
catch (Exception ex) copyFile(pic.tempPath, NativePath(fullpath));
}
}
e.photo = photopath;
empModel.addEmployee(e);
redirect("list_employees");
}
When I tried to learn Vibe.d again, I again became aware of the dearth of tutorials, so I wrote a tutorial myself while everything is fresh as a learner:
https://github.com/reyvaleza/vibed
Hope you find this useful.
Put the upload function inside the WebApp class and use it to handle the form post form(action="/upload", method ="post")
class WebApp {
addUpload(HTTPServerRequest req, ...)
{
auto file = file in req.files;
...
}
}
You can try hunt-framework, Hunt Framework is a high-level D Programming Language Web framework that encourages rapid development and clean, pragmatic design. It lets you build high-performance Web applications quickly and easily.
Sample code for action:
#Action
string upload()
{
string message;
if (request.hasFile("file1"))
{
auto file = request.file("file1");
if (file.isValid())
{
// File save path: file.path()
// Origin name: file.originalName()
// File extension: file.extension()
// File mimetype: file.mimeType()
if (file.store("uploads/myfile.zip"))
{
message = "upload is successed";
}
else
{
message = "save as error";
}
}
else
{
message = "file is not valid";
}
}
else
{
message = "not get this file";
}
return message;
}
Before the iOS8 will be released, I downloaded iOS8 SDK to watch how my application will be work. Sometimes my app need to download data from server and I use NSUrlSession for it. And now, when app preparing session for downloading, appears the next warning:
+backgroundSessionConfiguration: is deprecated. Please use +backgroundSessionConfigurationWithIdentifier: instead.
After it my app crashes with the next exception:
Unable to cast object of type 'MonoTouch.Foundation.NSUrlSessionTask' (Objective-C type: '__NSCFBackgroundDownloadTask') to type 'MonoTouch.Foundation.NSUrlSessionDownloadTask'.
Additional information:
Selector: URLSession:downloadTask:didFinishDownloadingToURL:
Method: Microsoft.Synchronization.ClientServices.NSUrlDownloadDelegate:DidFinishDownloading (MonoTouch.Foundation.NSUrlSession,MonoTouch.Foundation.NSUrlSessionDownloadTask,MonoTouch.Foundation.NSUrl)
Code for creating NSUrlSession:
NSUrlSessionConfiguration sessionConfiguration = NSUrlSessionConfiguration.BackgroundSessionConfiguration(urlSessioinId);
NSUrlDownloadDelegate downloadDelegate = new NSUrlDownloadDelegate();
NSUrlSession downloadSession = NSUrlSession.FromConfiguration(sessionConfiguration, downloadDelegate, new NSOperationQueue());
Thanks for any help!
I have use following to solve this error in Objective-C :
NSURLSessionConfiguration *sessionConfig;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >=8.0f)
{
sessionConfig =[NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:#"downloads"];
}
else
{
sessionConfig = [NSURLSessionConfiguration backgroundSessionConfiguration:#"downloads"];
}
This should work.
if(UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
configDownload = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(sessionId);
}
else
{
configDownload = NSUrlSessionConfiguration.BackgroundSessionConfiguration(sessionId);
}
As an experiment, I'm trying some stuff out with dart and easyrtc. I started at porting this (it is normally served through a nodejs server, found here) to a dart version and this is what I made from it
EDIT: I found out which part of the code is causing the error. It is the data object proxy which the for loop is unable to run through. Normally, the setRoomOccupantListener function gives as parameters the name of the room and an object with all the peers connected to the room. I have made a screenshot of the object layout in normal javascript as how it looks when I debug in chrome, found here.
function connect() {
easyrtc.setRoomOccupantListener(convertListToButtons);
}
function convertListToButtons (roomName, data, isPrimary) {
clearConnectList();
var otherClientDiv = document.getElementById("otherClients");
for(var easyrtcid in data) {
var button = document.createElement("button");
button.onclick = function(easyrtcid) {
return function() {
performCall(easyrtcid);
};
}(easyrtcid);
var label = document.createTextNode(easyrtc.idToName(easyrtcid));
button.appendChild(label);
otherClientDiv.appendChild(button);
}
}
And here is the screenshot when i debug the dart code in chromium
void connect() {
easyrtc.setRoomOccupantListener(convertListToButtons);
}
void convertListToButtons(roomName, data, isPrimary) {
clearConnectList();
var otherClientDiv = querySelector("#otherClients");
for (var easyrtcid in data) {
var button = document.createElement("button");
button.onClick.listen((event) {
performCall(easyrtcid);
});
button.appendText(easyrtc.idToName(easyrtcid));
otherClientDiv.append(button);
}
}
This is the error I get:
Class 'Proxy' has no instance getter 'iterator'.
NoSuchMethodError: method not found: 'iterator' Receiver: Instance of 'Proxy' Arguments: []
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:45)
#1 P...<omitted>...7)
Am I missing something simple here or is this some kind of incompatibility? Thank you.
I see you can use import package:js/js.dart'; too. I don't know how to use it
You could try
import 'dart:js' as js;
https://www.dartlang.org/articles/js-dart-interop/
This looks weird too
easyrtc = js.context.easyrtc; // <== here you have context 'easyrtc'
easyrtc.easyApp('easyrtc.audioVideo', 'selfVideo', new js.JsObject.jsify(['callerVideo']), loginSuccess, loginFailure);
// and here again 'easyrtc.audioVideo', I guess this is one to much
try
easyrtc.easyApp.callMethod('audioVideo', ['selfVideo', js.JsObject.jsify(['callerVideo']), loginSuccess, loginFailure]);
where 'audioVideo' is the called method and the rest are arguments
easyrtc.callMethod('easyApp', ['audioVideo', 'selfVideo', js.JsObject.jsify(['callerVideo']), loginSuccess, loginFailure]);
where 'easyApp' is the called method and the rest are arguments.
If you can add how the code would look in JavaScript I could create better examples.
Like dart:js package:js doesn't handle directly Dart List. So the following line :
easyrtc.easyApp('easyrtc.audioVideo', 'selfVideo',
['callerVideo'], loginSuccess, loginFailure);
should be :
easyrtc.easyApp('easyrtc.audioVideo', 'selfVideo',
js.array(['callerVideo']), loginSuccess, loginFailure);
See also What is a difference between dart:js and js package?
I'm trying to split some client-side-only code into several files in a Derby.js project. It has to be client-side only since it's interacting with the TinyMCE editor. So I tried:
app.ready(function(model) {
var tiny = derby.use(require('../../lib/app/TinyMCE'))
//other client-side code
}
and put the following into lib/app/TinyMCE.js:
var derby = require('derby')
module.exports.decorate = 'derby'; //because before I got an 'decorate' is undefined error...
module.exports.TinyMCE = function() {
//code
}
But now I'm getting a object is not a function error.
Am I even on the right track? I also considered putting the code in the public directory, but the cache-expiration of one year makes this rather inconvenient.
Also, is there really no isServer or isClient method to query?
Okay, I don't know whether that's a good way, but I got it working:
module.exports = tiny
tiny.decorate = 'derby'
function tiny() {
//code
}