Playing audio programmatically via NodeJS - javascript

I've spent the whole day trying to get any of the npmpackages related to playing audio from nodejs but couldn't get any to work.
Basically what I need is to play batch audios.
For example:
//files containing the name of the audios
var files = require('./list-of-audios-to-play.json')
var player = require('play-sound')(opts = {})
var counter = 0;
//every 5 seconds, play the referenced audio
setInterval(function(){
counter++;
player.play(files[counter]+'.mp3', function(err){
if (err) throw err
})
},5000)
Tried everything.
When I run the above code, I get this error:
INFORMATION: wasnt possible to locate files for the specified pattern(s)
events.js:183
throw er; // Unhandled 'error' event
^
Error: spawn play ENOENT
at _errnoException (util.js:1022:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:190:19)
at onErrorNT (internal/child_process.js:372:16)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
at Function.Module.runMain (module.js:695:11)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
Can anyone help?

Related

No video id found ytdl

Hello lately ive been developing a music bot on discord and i got it to join and leave perfectly but playing music is just annoying and some reason play and playStream doesnt work. With the bot i would like a person to message the name of a song and it'll get a url out of it but each time is says no video id found here is my code;
client.on("message", (message) => {
if (message.content.startsWith(">p")){
let string = message.content;
let lastWord = string.slice(2);
if (lastWord != ">p"){
const {joinVoiceChannel} = require('#discordjs/voice')
const voice = require('#discordjs/voice')
const connection = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.member.guild.id,
adapterCreator: message.member.guild.voiceAdapterCreator
})
const stream = ytdl(lastWord, {filter: 'audioonly', quality: 'highestaudio'})
stream.pipe(fs.createWriteStream('tmp_buf_audio.mp3')).on('end', () => {
connection.playStream(fs.createReadStream('tmp_buf_audio.mp3'))
}
)};
}
});
here is also the error i get;
/home/runner/Bot-Project/node_modules/ytdl-core/lib/url-utils.js:63
throw Error(`No video id found: ${str}`);
^
Error: No video id found:
at Object.exports.getVideoID (/home/runner/Bot-Project/node_modules/ytdl-core/lib/url-utils.js:63:11)
at Function.exports.<computed> [as getInfo] (/home/runner/Bot-Project/node_modules/ytdl-core/lib/info.js:484:29)
at ytdl (/home/runner/Bot-Project/node_modules/ytdl-core/lib/index.js:19:8)
at Client.<anonymous> (/home/runner/Bot-Project/index.js:83:16)
at Client.emit (node:events:402:35)
at Client.emit (node:domain:475:12)
Hint: hit control+c anytime to enter REPL.
Project is running!
(node:7809) DeprecationWarning: The message event is deprecated. Use messageCreate instead
(Use `node --trace-deprecation ...` to show where the warning was created)
Hint: hit control+c anytime to enter REPL.
Project is running!
(node:7923) DeprecationWarning: The message event is deprecated. Use messageCreate instead
(Use `node --trace-deprecation ...` to show where the warning was created)
/home/runner/Bot-Project/node_modules/ytdl-core/lib/url-utils.js:63
throw Error(`No video id found: ${str}`);
^
Error: No video id found: let it go
at Object.exports.getVideoID (/home/runner/Bot-Project/node_modules/ytdl-core/lib/url-utils.js:63:11)
at Function.exports.<computed> [as getInfo] (/home/runner/Bot-Project/node_modules/ytdl-core/lib/info.js:484:29)
at ytdl (/home/runner/Bot-Project/node_modules/ytdl-core/lib/index.js:19:8)
at Client.<anonymous> (/home/runner/Bot-Project/index.js:83:16)
at Client.emit (node:events:402:35)
at Client.emit (node:domain:475:12)
at MessageCreateAction.handle (/home/runner/Bot-Project/node_modules/discord.js/src/client/actions/MessageCreate.js:34:18)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/Bot-Project/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/Bot-Project/node_modules/discord.js/src/client/websocket/WebSocketManager.js:351:31)
Emitted 'error' event on PassThrough instance at:
repl process died unexpectedly: exit status 1

I see you are using node-ytdl-core. The usage of ytdl('.....'), is wrong, it should be instead used as following : ytdl(url, [options]).
Go through https://www.npmjs.com/package/ytdl-core

Unhandled exception in express

im getting the following error issue throw er; // Unhandled 'error' event
Here is my Controler.js
const router = require('express').Router();
router.post('/api/sendMail', async (req,res) => {
console.log("yes")
});
module.exports = router;
Here is my index.js
const cont = require('./controllers/Controler');
app.use(cont);
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::5000
at Server.setupListenHandle [as _listen2] (net.js:1286:14)
at listenInCluster (net.js:1334:12)
at Server.listen (net.js:1421:7)
at Function.listen (/Users/user/folder/node_modules/express/lib/application.js:618:24)
at Object.<anonymous> (/Users/user/folder/server.js:24:5)
at Module._compile (internal/modules/cjs/loader.js:688:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Module.load (internal/modules/cjs/loader.js:598:32)
at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
at Function.Module._load (internal/modules/cjs/loader.js:529:3)
Emitted 'error' event at:
at emitErrorNT (net.js:1313:8)
at process._tickCallback (internal/process/next_tick.js:63:19)
at Function.Module.runMain (internal/modules/cjs/loader.js:744:11)
at startup (internal/bootstrap/node.js:285:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)
Im not sure what im missing but im gettng unhandled error isssue.
It seems like something already uses 5000 port.
If you use *nix based OS, you can get list of processes like this:
netstat -tulpn | grep 5000
and then, kill particular process:
kill -9 PID
Use try/catch:
try {
app.use(cont);
} catch(er) {
console.log(er);
}
Also note that port 5000 is already in use (EADDRINUSE) - try changing your port to something else.
Try running your app using a different port or kill the process in the current port 5000
To kill a task in windows
//get process running in port 5000
netstat -ano | findstr :5000
//enter your pid and force kill
//replace <pID> with your process id
taskkill /PID <pID> /F

Get a file without name in url

I would like to get the file from this url : https://donnees.roulez-eco.fr/opendata/instantane
As you can see there's no file name in the URL.
My problem is with this simple code :
var file = fs.createWriteStream('./myFile.zip')
http.get(url, function(response) {
response.pipe(file);
}
This code works well if you got an url like https://someurl.com/filename.zip.
The file is downloaded and can be use but this response.pipe(file) line throw me this error:
events.js:163
throw er; // Unhandled 'error' event
^
Error: Parse Error
at TLSSocket.socketOnData (_http_client.js:411:20)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:178:18)
at TLSSocket.Readable.push (_stream_readable.js:136:10)
at TLSWrap.onread (net.js:559:20)
What should / can i do to fix this?

Videoshow NPM module with ffmpeg

I'm trying to use videoshow to convert multiple images to video, I have tried to change my code multiple times but now as you can see this is basically the same as in the module's description page. Still I am receiving the following error as stated below.
videoshow(images)
.save('video.mp4')
.on('start', function (command) {
console.log('ffmpeg process started:', command)
})
.on('error', function (err) {
console.error('Error:', err)
})
.on('end', function (output) {
console.log('Video created in:', output)
})
Error: Error: ffmpeg exited with code 1: Error reinitializing filters!
Failed to inject frame into filter network: Invalid argument
Error while processing the decoded data for stream #2:0
Conversion failed!
at ChildProcess.<anonymous> (C:\Users\xxxxxx\Documents\Visual Studio 2017\Projects\Frame\Frame\server-side\node_modules\fluent-ffmpeg\lib\processor.js:182:22)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
Check aspect ratio and resolution of images, if your all images or any one have different resolution and aspect ratio then it will give you error. try with all same resolution images.

Error: Unable to capture screenshot - Android hybrid app using Protractor and Appium

I'm using Protractor for test automation. I tested my hybrid Android app perfectly using Protractor (jasmine) and Appium. But I can not get the browser.takeScreenshot() function to work properly. All other test work perfectly like clicking buttons or stuff like that.
I created a new blank app to rule out that a plugin causes this problem. No Cordova Plugin prevents the screenshot capability and I am able to take screenshots with the android device itself.
I tried this StackOverflow answer (and many many more), but with no success (and it seems like nobody ever experienced this issue).
I also used the protractor-jasmin2-screenshot-reporter to rule out, that my code for taking the screenshot is not working, but I get the same result. Intresstingly, when I use browserName: 'Chrome' and let the test open Chrome on my device and call www.google.com and let my code take a screenshot, it works fine. Only in my hybrid app, taking a screenshot does not work.
(The browser.takeScreenshot().then(function (png) {... code is from the official protractor page and other reliable sources).
My Specs
Protractor: 5.0.0
Appium (Desktop Client): 1.4.16.1 (latest version)
Windows 10 Enterprise 64 Bit
Chromedriver: 2.27 (latest version)
Angular: 1.5.3
Node.js: 6.9.1
Android: 6.0.1 and 4.4.2 (Galaxy S6 and Alcatel Pixi)
Cordova 6.4.0
My Protractor config.js
exports.config = {
seleniumAddress : 'http://localhost:4723/wd/hub',
// Reference: https://github.com/appium/sample-code/blob/master/sample-code/examples/node/helpers/caps.js
capabilities : {
// needed by local appium
platformVersion : '',
platformName : '',
deviceName : '',
// needed by protractor
browserName : '',
autoWebview : true,
// CHANGE THIS TO YOUR ABSOLUTE PATH OR SET IT IN APPIUM CLIENT
app : 'C:/Projekte/WifiWizardTestApp/platforms/android/build/outputs/apk/android-debug.apk',
newCommandTimeout : 60
},
//needed for local appium
baseUrl : 'http://localhost:8080',
//configuring wd in onPrepare
//wdBridge helps to bridge wd driver with other selenium clients
//See https://github.com/sebv/wd-bridge/blob/master/README.md
onPrepare : function () {
var wd = require('wd');
var protractor = require('protractor');
var wdBridge = require('wd-bridge')(protractor, wd);
wdBridge.initFromProtractor(exports.config);
},
};
My test.spec.js
var fs = require('fs');
describe('Testing the browse state', function () {
it('should be able to take a screenshot', function (done) {
browser.sleep(2000);
browser.takeScreenshot().then(function (png) {
console.log('browser.takeScreenshot()');
var stream = fs.createWriteStream('screenshot.png');
stream.write(new Buffer(png, 'base64'));
stream.end();
done();
});
});
it('should be able to take an other screenshot', function () {
browser.takeScreenshot().then(function (png) {
console.log('browser.takeScreenshot()');
var stream = fs.createWriteStream('screenshot2.png');
stream.write(new Buffer(png, 'base64'));
stream.end();
});
});
});
My console output (Android 6.0.1)
C:\Projekte\WifiWizardTestApp>protractor protractor.config.js --specs tests/browse.spec.js
[09:27:44] I/hosted - Using the selenium server at http://localhost:4723/wd/hub
[09:27:44] I/launcher - Running 1 instances of WebDriver
Started
A Jasmine spec timed out. Resetting the WebDriver Control Flow.
FA Jasmine spec timed out. Resetting the WebDriver Control Flow.
F
Failures:
1) Testing the browse state should be able to take a screenshot
Message:
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
Stack:
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
at ontimeout (timers.js:365:14)
at tryOnTimeout (timers.js:237:5)
at Timer.listOnTimeout (timers.js:207:5)
2) Testing the browse state should be able to take an other screenshot
Message:
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
Stack:
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
at ontimeout (timers.js:365:14)
at tryOnTimeout (timers.js:237:5)
at Timer.listOnTimeout (timers.js:207:5)
2 specs, 2 failures
Finished in 60.04 seconds
My console output (Android 4.4.2)
C:\Projekte\WifiWizardTestApp>protractor protractor.config.js --specs tests/browse.spec.js
[15:15:49] I/hosted - Using the selenium server at http://localhost:4723/wd/hub
[15:15:49] I/launcher - Running 1 instances of WebDriver
Started
FF
Failures:
1) Testing the browse state should be able to take a screenshot
Message:
Failed: unknown error: unhandled inspector error: {"code":-32603,"message":"Unable to capture screenshot"}
(Session info: webview=30.0.0.0)
(Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Windows NT 10.0.10586 x86_64)
Stack:
WebDriverError: unknown error: unhandled inspector error: {"code":-32603,"message":"Unable to capture screenshot"}
(Session info: webview=30.0.0.0)
(Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Windows NT 10.0.10586 x86_64)
at WebDriverError (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\error.js:27:5)
at Object.checkLegacyResponse (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\error.js:505:15)
at parseHttpResponse (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\http.js:509:13)
at doSend.then.response (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\http.js:440:13)
at process._tickCallback (internal/process/next_tick.js:103:7)
From: Task: WebDriver.takeScreenshot()
at WebDriver.schedule (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\webdriver.js:816:17)
at WebDriver.takeScreenshot (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\webdriver.js:1092:17)
at ProtractorBrowser.to.(anonymous function) [as takeScreenshot] (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\lib\browser.ts:94:25)
at Object.<anonymous> (C:\Projekte\WifiWizardTestApp\tests\browse.spec.js:14:17)
at C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:98:15
at new ManagedPromise (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:1067:7)
at controlFlowExecute (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:87:18)
at TaskQueue.execute_ (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2970:14)
at TaskQueue.executeNext_ (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2953:27)
at asyncRun (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2813:27)
From: Task: Run it("should be able to take a screenshot") in control flow
at Object.<anonymous> (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:86:14)
From asynchronous test:
Error
at Suite.<anonymous> (C:\Projekte\WifiWizardTestApp\tests\browse.spec.js:8:5)
at Object.<anonymous> (C:\Projekte\WifiWizardTestApp\tests\browse.spec.js:4:1)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
2) Testing the browse state should be able to take an other screenshot
Message:
Failed: unknown error: unhandled inspector error: {"code":-32603,"message":"Unable to capture screenshot"}
(Session info: webview=30.0.0.0)
(Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Windows NT 10.0.10586 x86_64)
Stack:
WebDriverError: unknown error: unhandled inspector error: {"code":-32603,"message":"Unable to capture screenshot"}
(Session info: webview=30.0.0.0)
(Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Windows NT 10.0.10586 x86_64)
at WebDriverError (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\error.js:27:5)
at Object.checkLegacyResponse (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\error.js:505:15)
at parseHttpResponse (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\http.js:509:13)
at doSend.then.response (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\http.js:440:13)
at process._tickCallback (internal/process/next_tick.js:103:7)
From: Task: WebDriver.takeScreenshot()
at WebDriver.schedule (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\webdriver.js:816:17)
at WebDriver.takeScreenshot (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\webdriver.js:1092:17)
at ProtractorBrowser.to.(anonymous function) [as takeScreenshot] (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\lib\browser.ts:94:25)
at Object.<anonymous> (C:\Projekte\WifiWizardTestApp\tests\browse.spec.js:26:17)
at C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:102:25
at new ManagedPromise (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:1067:7)
at controlFlowExecute (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:87:18)
at TaskQueue.execute_ (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2970:14)
at TaskQueue.executeNext_ (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2953:27)
at asyncRun (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2860:25)
From: Task: Run it("should be able to take an other screenshot") in control flow
at Object.<anonymous> (C:\Users\mkaiser\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:86:14)
From asynchronous test:
Error
at Suite.<anonymous> (C:\Projekte\WifiWizardTestApp\tests\browse.spec.js:24:5)
at Object.<anonymous> (C:\Projekte\WifiWizardTestApp\tests\browse.spec.js:4:1)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
2 specs, 2 failures
Finished in 2.258 seconds
[15:17:49] I/launcher - 0 instance(s) of WebDriver still running
[15:17:49] I/launcher - #01 failed 2 test(s)
[15:17:49] I/launcher - overall: 2 failed spec(s)
[15:17:49] E/launcher - Process exited with error code 1
wdBrowser.context('NATIVE_APP').then(() => {
browser.takeScreenshot().then(function (png) {
console.log('browser.takeScreenshot()');
var stream = fs.createWriteStream('screenshot.png');
stream.write(new Buffer(png, 'base64'));
stream.end(function(){
wdBrowser.context(<Your webview>).then(done);
});
})
});
Where wdBrowser is a global variable set by wdBridge. Should work - been having a similar issue (unable to take screenshot but no error message like you have)
You can grab your webview name/id from the appium logs.
the wdBrowser.context('NATIVE_APP') didn't work for me.
It took the pictures, but afterwards each testcase failed.
I found a different solution to take screenshots.
I replaced the takeScreenshots() method with following code:
var exec = require('child_process').exec;
exec('adb shell /system/bin/screencap -p /sdcard/' + filename); // Take a screenshot and store it on the internal storage.
// Wait until the screenshot is created on android
var date = new Date();
var curDate = null;
do {
curDate = new Date();
}
while (curDate - date < 1000);
var command = 'adb pull /sdcard/'+ filename + ' ' + screenshotPath;
exec(command, function (err, stdout, stderr) { // Copy the screenshot from the internal storage to the local computer.
if(err){
console.error('The screenshot could not be copied from the ANDROID device: ' + stdout);
console.log('The screenshot is stored on the ANDROID device with the name: ' + filename);
}
});
I had following problems:
The screenshot was not created until I wanted to pull it.
The screenshot file existed during the pull, but it only pulled 0kb files.
Therefore I implemented a one second sleep between taking the screenshot and pulling it to the computer.

Categories