I am getting no audio for Watson TTS - watson

This is my java code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.ibm.watson.developer_cloud.text_to_speech.v1.TextToSpeech;
import com.ibm.watson.developer_cloud.text_to_speech.v1.model.AudioFormat;
import com.ibm.watson.developer_cloud.text_to_speech.v1.model.Voice;
public static void main(String[] args) {
TextToSpeech textService = new TextToSpeech(IBM_WATSON_USERNAME, IBM_WATSON_PASSWORD);
String text = "Show me the meaning of being lonely";
try {
InputStream in = textService.synthesize(text, Voice.EN_ALLISON, AudioFormat.WAV)
.execute();
System.out.println(in.available());
byte[] buffer = new byte[in.available()];
in.read(buffer);
File targetFile = new File("local_path/Aud.wav");
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
outStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
When i run the code i am getting the response in Eclipse Console as:
Dec 13, 2017 5:38:35 PM okhttp3.internal.platform.Platform log
INFO: --> POST https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize?voice=en-US_AllisonVoice&accept=audio/wav http/1.1 (71-byte body)
Dec 13, 2017 5:38:35 PM okhttp3.internal.platform.Platform log
INFO: <-- 200 OK https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize?voice=en-US_AllisonVoice&accept=audio/wav (501ms, unknown-length body)
Value of in.available() is 0
I am getting no audio generated. So as per the code flow i am getting a .wav file of 0kB getting generated. What am i getting no Audio?

Try this simple method
public class tts
{
public static void main( String[] args ) throws Exception
{
TextToSpeech service = new TextToSpeech();
service.setUsernameAndPassword();
String text = "Show me the meaning of being lonely";
InputStream stream =service.synthesize(text, Voice.EN_ALLISON, AudioFormat.WAV).execute();
AudioPlayer.player.start(WaveUtils.reWriteWaveHeader(stream));
}}
catch (Exception e) {
e.printStackTrace();
}
}
}

Related

How to successfully perform file I/O with asynchronous input in Dart using Streams

I was wondering if anyone knew how to correctly perform asynchronous file I/O in Dart using Streams, because clearly my method is not working. I have seen other people's solutions by converting the stream to a list, but I don't really want to do that because of speed concerns and was wondering if there was any way to do this operation using just streams?
Anyways, here is my code:
import 'dart:io';
import 'dart:collection';
import 'dart:convert';
final validCharacters = RegExp(r'^[a-zA-Z]+$'); // a-z, A-Z
main() async {
final dict1File = 'american-english';
final dict2File = 'british-english';
final cleanedDictFile = 'Cleansed_English_Dictionary';
SplayTreeSet<String> wordSet = new SplayTreeSet<String>();
await readFile(dict1File, wordSet);
await readFile(dict2File, wordSet);
await writeFile(cleanedDictFile, wordSet);
}
readFile(String fileName, SplayTreeSet<String> wordSet) async {
File file = new File(fileName);
if (await file.exists()) {
file
.openRead()
.transform(Utf8Decoder())
.transform(LineSplitter())
.where((String data) => validCharacters.hasMatch(data))
.listen((String data) => wordSet.add(data),
onDone: () => print('${wordSet.length}'), onError: (e) => print(e));
} else {
print('The desired file $fileName does not exist');
}
}
writeFile(String fileName, SplayTreeSet<String> wordSet) async {
File file = new File(fileName);
if (await file.exists()) {
file.openWrite().writeAll(wordSet, '\n');
} else {
print('The desired file $fileName does not exist');
}
}
Here is me performing a similar operation in Java (my native language) :p
import java.io.*;
import java.util.Set;
import java.util.TreeSet;
public class DictCleaner {
public static void main(String[] args) throws IOException {
System.out.println("Beginning process");
Set<String> words = new TreeSet<>();
long time1 = System.currentTimeMillis();
readFile("american-english", words);
readFile("british-english", words);
long time2 = System.currentTimeMillis();
System.out.println(
"Time to read files: " + (time2 - time1) + " milliseconds"
);
System.out.println("Number of words: " + words.size());
String filename = "Cleansed_English_Dictionary";
System.out.println("Outputting new file, " + filename);
outputFile(filename, words);
long time3 = System.currentTimeMillis();
System.out.println(
"Total execution time: " + (time3 - time1) + " milliseconds"
);
File file = new File(filename);
double fileSize = file.length() >> 10;
System.out.println(
"Output file size of " + filename + "= " + fileSize + " kilobytes"
);
}
public static void readFile(String fileName, Set<String> words)
throws IOException {
BufferedReader br;
try {
br = new BufferedReader(new FileReader(fileName));
String currentLine;
while ((currentLine = br.readLine()) != null) {
if (currentLine.matches("^[a-zA-Z]") && currentLine.length() <= 15) {
words.add(currentLine);
}
}
br.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public static void outputFile(String filename, Set<String> words)
throws FileNotFoundException {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(filename)
);
try {
for (String s : words) {
bos.write(s.getBytes());
bos.write(System.lineSeparator().getBytes());
}
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Anyways, I am basically just cleaning up a dictionary for use with my app. Does anyone have any guidance on how I can make the Dart code work, or perhaps a more generic explanation?
My new code after comments!
import 'dart:io';
import 'dart:collection';
import 'dart:convert';
final validCharacters = RegExp(r'^[a-zA-Z]+$'); // a-z, A-Z
main() async {
Stopwatch stopwatch = new Stopwatch()..start();
final dict1File = 'american-english';
final dict2File = 'british-english';
final cleanedDictFile = 'Cleansed_English_Dictionary';
SplayTreeSet<String> wordSet = new SplayTreeSet<String>();
await readFile(dict1File, wordSet);
await readFile(dict2File, wordSet);
await writeFile(cleanedDictFile, wordSet);
print('Total execution time: ${stopwatch.elapsed}');
}
Future<void> readFile(String fileName, SplayTreeSet<String> wordSet) async {
File file = new File(fileName);
if (await file.exists()) {
await for (final data in file
.openRead()
.transform(Utf8Decoder())
.transform(LineSplitter())
.where((String data) => validCharacters.hasMatch(data))) {
wordSet.add(data);
}
print('${wordSet.length}');
} else {
print('The desired file $fileName does not exist');
}
}
Future<void> writeFile(String fileName, SplayTreeSet<String> wordSet) async {
File file = new File(fileName);
if (await file.exists()) {
IOSink sink = file.openWrite();
sink.writeAll(wordSet, '\n');
sink.close();
} else {
print('The desired file $fileName does not exist');
}
}
The problem is that .listen does not halt the program until all events has been consumed.
I think the most clean way to fix this is to use "await for-each" like this:
Future<void> readFile(String fileName, SplayTreeSet<String> wordSet) async {
File file = new File(fileName);
if (await file.exists()) {
await for (final data in file
.openRead()
.transform(Utf8Decoder())
.transform(LineSplitter())
.where((String data) => validCharacters.hasMatch(data))) {
wordSet.add(data);
}
print('${wordSet.length}');
} else {
print('The desired file $fileName does not exist');
}
}
More optimized solution
As requested, I have tried to make the program run faster. If performance are the main goal, you can often save some time by using the "sync" edition of the IO file operations. In this case, the program are really not doing anything else, so it is fine to let the main thread wait on e.g. reading the file.
One optimization is more about code readability but Dart does already provide readAsLines and readAsLinesSync on File so we don't need to use a Utf8Decoder and LineSplitter if we just want to split the lines. This will potentially take some more memory since we now get a list containing all lines instead of iterating each line. The list are short-lived so it is properly not a problem for this program. But also, the list contains String objects where most of them are going to be used in our Set so most of the used memory is not really something we can avoid.
Another optimization is the writing. Here we generate the final string first in memory (wordSet.join('\n')) and then write the whole string to disk as one operation. This is much faster but does take some additional memory.
import 'dart:collection';
import 'dart:io';
final validCharacters = RegExp(r'^[a-zA-Z]+$'); // a-z, A-Z
void main() {
const dict1File = 'american-english-insane';
const dict2File = 'british-english-insane';
const cleanedDictFile = 'Cleansed_English_Dictionary';
final wordSet = SplayTreeSet<String>();
readFile(dict1File, wordSet);
readFile(dict2File, wordSet);
writeFile(cleanedDictFile, wordSet);
}
void readFile(String fileName, Set<String> wordSet) {
final file = File(fileName);
if (file.existsSync()) {
file
.readAsLinesSync()
.where((data) => validCharacters.hasMatch(data))
.forEach(wordSet.add);
print(wordSet.length);
} else {
print('The desired file $fileName does not exist');
}
}
void writeFile(String fileName, Iterable<String> wordSet) =>
File(fileName).writeAsStringSync(wordSet.join('\n'));

audioplayer plugin in Flutter - Unable to load asset

I'm trying to create an alarm in Flutter where an alarm tone should go off after a certain time. It seems like this is easier said than done in Flutter!
Tried to use the audioplayer plugin to achieve this. Used the playLocal function wherein the asset is loaded from the rootbundle into the app directory and then played
According to an answer in the audioplayer github repo, this is the code that should do the trick:
class SoundManager {
AudioPlayer audioPlayer = new AudioPlayer();
Future playLocal(localFileName) async {
final dir = await getApplicationDocumentsDirectory();
final file = new File("${dir.path}/$localFileName");
if (!(await file.exists())) {
final soundData = await rootBundle.load("assets/$localFileName");
final bytes = soundData.buffer.asUint8List();
await file.writeAsBytes(bytes, flush: true);
}
await audioPlayer.play(file.path, isLocal: true);
}
}
I keep getting an error: "Unable to load asset". The asset (mp3/wav file) is obviously in the folder, and the folder is included in the pubspec.yaml file correctly (other image assets are loading properly from this folder, so specifying the folder itself is not the issue here)
You can use another audio library https://pub.dev/packages/audioplayers
AudioCache documentation.
https://github.com/luanpotter/audioplayers/blob/master/doc/audio_cache.md
Simple example:
import 'package:audioplayers/audio_cache.dart';
AudioCache player = AudioCache();
player.play('sounds/test_sound.m4a');
In this example my assets folder looks like this: assets/sounds/test_sound.m4a
This library cached audio as local file and then play audio
PS: If you want to play music from local files you can use AudioPlayer().
My example with listener on return, onPlayCompletion will be called when music end
AudioPlayer _advancedPlayer = AudioPlayer();
Stream<void> playFromLocal(int unitId, int id) {
var link = '/media/$unitId/words/$id.m4a';
_advancedPlayer.stop();
_advancedPlayer.release();
_advancedPlayer = AudioPlayer();
_advancedPlayer.play(Const.basePath + link, isLocal: true);
return _advancedPlayer.onPlayerCompletion;
}
This works well for both iOS and Android. Note: this downloads from url if not available locally.
AudioProvider audioProvider;
_playSound() async {
audioProvider = AudioProvider("http:...");
var soundToPlay = "myLocalSound";
String localUrl = await audioProvider.load(soundToPlay);
SoundController.play(localUrl);
}
}
audio_provider.dart
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart';
typedef void OnError(Exception exception);
class AudioProvider {
String url;
AudioProvider(String url) {
this.url = url;
}
Future<Uint8List> _loadFileBytes(String url, {OnError onError}) async {
Uint8List bytes;
try {
bytes = await readBytes(url);
} on ClientException {
rethrow;
}
return bytes;
}
Future<String> load(fileName) async {
final dir = await getApplicationDocumentsDirectory();
final file = new File('${dir.path}/$fileName');
if (await file.exists()) {print("file exists");
return file.path;
}
var filePath = url +fileName;
final bytes = await _loadFileBytes(filePath,
onError: (Exception exception) =>
print('audio_provider.load => exception ${exception}'));
await file.writeAsBytes(bytes);
if (await file.exists()) {
return file.path;
}
return '';
}
}
soundController.dart
import 'package:flutter/foundation.dart';
import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';
import 'dart:io' show Platform;
void audioPlayerHandler(AudioPlayerState value) => null;
class SoundController {
static AudioPlayer audioPlayer = AudioPlayer(mode: PlayerMode.LOW_LATENCY);
static AudioCache audioCache = AudioCache(prefix: "assets/audio/", fixedPlayer: audioPlayer);
static void play(String sound) {
if (!kIsWeb && Platform.isIOS) {
audioPlayer.monitorNotificationStateChanges(audioPlayerHandler);
}
audioPlayer.play(sound, isLocal: true);
}
}

Get view count using Google Youtube API

I want to get the view count of set of videos. Following is the relevant part of my code.
SearchResult singleVideo = iteratorSearchResults.next();
ResourceId rId = singleVideo.getId();
// Double checks the kind is video.
if (rId.getKind().equals("youtube#video")) {
Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().get("default");
System.out.println(" Video Id" + rId.getVideoId());
System.out.println(" Title: " + singleVideo.getSnippet().getTitle());
System.out.println(" Thumbnail: " + thumbnail.getUrl());
YouTube.Videos.List list = youtube.videos().list("statistics");
list.setId(rId.getVideoId());
list.setKey("youtube.apikey");
Video v = list.execute().getItems().get(0);
System.out.println("The view count is: "+v.getStatistics().getViewCount());
System.out.println("\n-------------------------------------------------------------\n");
}
This gives the following error in the line "YouTube.Videos.Lists list = youtube.videos().list("statistics");".
error: method list in class YouTube.Videos cannot be applied to given types;
If this is a compilation error then there might be some issue with the library version that you have included. I tried sample code from youtube API docs and it worked for me.
I have removed some extra code from the sample to show how view counts can be retrieved for a single video:
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.services.samples.youtube.cmdline.Auth;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Video;
import com.google.api.services.youtube.model.VideoListResponse;
import java.io.IOException;
import java.math.BigInteger;
public class GeolocationSearch {
public static void main(String[] args) {
try {
YouTube youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("APP_ID").build();
String apiKey = "API_KEY";
YouTube.Videos.List listVideosRequest = youtube.videos().list("statistics");
listVideosRequest.setId("lf_wVfwpfp8"); // add list of video IDs here
listVideosRequest.setKey(apiKey);
VideoListResponse listResponse = listVideosRequest.execute();
Video video = listResponse.getItems().get(0);
BigInteger viewCount = video.getStatistics().getViewCount();
System.out.println(" ViewCount: " + viewCount);
System.out.println("\n-------------------------------------------------------------\n");
} catch (GoogleJsonResponseException e) {
System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
} catch (IOException e) {
System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
}
}

Equivalent function for url.openStream() in Golang

import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
I need to do the same in golang i.e read and print the html source code, but cannot find the relation between two, I am a beginner with Go language, thank you in advance
Hope this will help:
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func Error(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
response, err := http.Get("http://www.oracle.com/")
Error(err)
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
Error(err)
fmt.Printf("%s\n", contents)
}
For more details: https://golang.org/pkg/net/http/

Dart: unhandledExceptionCallback is ignored

Here is a very simple code that I run using command line dart to demonstrate my point:
import 'dart:isolate';
void isolateMain() {
throw new Exception("ouch");
}
bool handleException(IsolateUnhandledException e) {
print("EXCEPTION in isolate: " + e.toString());
return true;
}
void main() {
SendPort sendPort = spawnFunction(isolateMain, handleException);
sendPort.call("Hello").then((e) {
print("Main received " + e);
});
}
and the output:
Exception: ouch
#0 isolateMain (file:///Users/salomon/Workspaces/eclipse/Deployer_Server/bin/deployer_server.dart:7:3)
So, turns out the unhandledExceptionCallback is never called whereas the isolate does throw an exception.
For the record :
> dart --version
Dart VM version: 0.5.20.4_r24275 (Fri Jun 21 05:02:50 2013) on "macos_x64"
So, can someone explain me what did I do wrong ?
Thanks ;)
I don't know if you did wrong, it could be a bug. But it seems exceptions thrown in the isolate's main function aren't caught by the handler. If you change it like this:
import 'dart:isolate';
void isolateMain() {
port.receive((whatever, mahPort) {
throw new Exception("$whatever");
});
}
bool handleException(IsolateUnhandledException e) {
print("EXCEPTION in isolate: ${e.toString()}");
return true;
}
void main() {
SendPort sendPort = spawnFunction(isolateMain, handleException);
sendPort.call("Hello").then((e) {
print("Main received $e");
});
}
... then handleException() will be called.

Resources