Welcome!

Java IoT Authors: Liz McMillan, Yeshim Deniz, Pat Romanski, Elizabeth White, Carmen Gonzalez

Related Topics: Java IoT

Java IoT: Article

Whole House Audio from the Palm of Your Hand

Whole House Audio from the Palm of Your Hand

In this business we often talk about how easy it is to get computers to talk to each other; computers without networks are almost inconceivable. Despite being standardized as little as five years ago, we now expect them all to play nicely together.

Even in the home, a CAT-5 connection isn't too remarkable, but mobile devices still spend most of their time in lonely isolation.

Of course, many technologies exist for connecting handheld devices to networks and other devices, but costs and limitations often cause people to question if it's really necessary: Why should a handheld be talking to the world? Well, I came up with one idea, and this article shows how I implemented it.

It starts with the conversion of my CD collection to MP3 to make it easier to find tracks and automate playback.

Once your collection is on your computer, you need software to organize it and play it back; many freely available applications will do that with varying amounts of control.

Random playback is all very well, but it can lead to some very strange combinations if your collection is broad (jumping from Beethoven to Aerosmith can be something of a shock), and it occurred to me that it should be possible to come up with something better. As the owner of a PDA (actually, several, but for the moment it's a Compaq iPaq) with a Wi-Fi card, I thought it would be nice to control my playback wirelessly.

My requirements were pretty basic; random play does work for me most of the time, but I would like to be able to pause playback and adjust the volume. There are also occasions when I'd like to select the next track to be played - when the mood takes me or when talking to guests about music - so some facility for browsing through the available tracks to select one would be good.

I should also point out that I'm very lazy, and the idea of entering the details of each recorded track doesn't appeal to me; the application must be able to cope with additional tracks being added automatically and notice if any have been removed.

Given this set of requirements, it's obviously important that all my music is stored in a standard format, something that most of the MP3 ripping software is ideally suited to. I had used an application called Audio Catalyst, but this currently has some problems with Windows 2000, so now I use AudioGrabber, which works well for my needs. This application grabs tracks from a CD, converts (rips) them to MP3 format, picks up the track listing information over the Internet, and is able to provide the MP3 file names that correspond to the track names. Because of the way I intend to use the tracks, I decided to organize them into directories by bands, then into subdirectories by album, and finally form the track name from the name of the band and the name of the track separated with a hyphen ("-"). Thus a sample listing looks something like this:

Blur\Park Life\Blur - Badhead.mp3
Blur\Park Life\Blur - Bank Holiday.mp3
Blur\Park Life\Blur - Clover Over Dover.mp3
... etc. ...
Including the name of the band in the title of the file was something I was already doing so I could see who produced a song when using WinAmp or similar applications. I know there are various standards for embedding information about an MP3 file within the file itself, but I decided it would be quicker to simply use the file name, especially as this was all the information I required.

Once I decided on how the music was to be stored and what my requirements were for playing it back, I started working out what my application would look like and how it would work. A formal design process probably would have helped at this point, but since the application was only intended for my use (something that will be obvious if you care to examine the source code, which can be downloaded from the JDJ Web site, www.sys-con.com/java/ sourcec.cfm), I felt that as long as I had the overall structure defined, I could get on with coding, something I came to regret later, as you will see.

Obviously, the application would have two major components: a server and a client. The server would have a minimum GUI, just enough to ensure it was working properly, while the client would have controls for changing the volume, pausing playback, and selecting the next track (see Figure 1).

The inclusion of a GUI on the server side was, strictly speaking, unnecessary, as it should be easy to run up a second client on the server if local control is needed. I also decided that it was important for the server and the client not to be in constant contact for two reasons: first, the battery life on an iPaq using a Wi-Fi link is laughable, measured in minutes not hours (in Part 2 or 3 of this article I'll discuss moving the application over to Bluetooth with its much improved power consumption), so it was important to be able to turn the client off without affecting playback. Second, I wanted to be able to run several clients with the same server.

The motivation for this second requirement is less clear. I have several computers and a wife with her own PDA, so while the thought of being in sole control of our listening choices appealed to me, it would be less popular with others in the house.

This decision has several implications: primarily, it was not possible for the client to constantly display the track playing currently. I decided the easiest solution was to add a button to update the display on request (see Figure 2). It was possible to set up some sort of registration system for clients and establish an outgoing connection from the server to all interested clients whenever a new track started, but I decided this was too complex at the moment; it could always be added later if it seemed important.

It was clear that objects would represent the tracks, and on the server side these objects would exist in some sort of ArrayList (I like ArrayLists).

The intention was that on launch, once fed with a directory to start from, the server would scan this directory and any subdirectories looking for MP3 files that it could use to build the ArrayList. Requests to play a specific track were then indexed by its position in the ArrayList. Clear- ly, this meant that tracks could not be added without stopping and relaunching the server, but this was a minor point and not considered important.

The first stage was to consider the networking model: What kind of communication would take place and what kind of responses would be expected? As all communication was client-initiated, it was obvious that the server would be using a ServerSocket listening on a specific port (1710, for no other reason than it happens to be my birthday). The client would connect to that port and send a request, the server would respond, and the client would break the connection. While it's possible to send several requests and receive several responses in one go, it was not deemed necessary (this is not a very time-critical application).

On connection the server should respond with a message to confirm that it exists ("+OK"), then wait for the client to send a request for it to respond to. I adopted the Internet convention of starting all successful responding messages with a "+", while those that gave an error of any type start with a "-"; this allows the client to simply check the first character of a response to see if the request has been honored. I also decided that all network communications would be case-insensitive. While this can slow things down slightly, it makes testing easier and avoids irritating problems with the use of the wrong case. I set about mapping out all the network communication I'd be using, starting with the ability to display which tracks were being played on the client:

[server] +OK
[client] status
[server] +Last Playing 292#Clannad - Ta Me Mo Shui
[server] +Playing 866#Men Without Hats
- 01 - In the 21st Century
[server] +Next 1057#Steeleye Span - The Victory
Note that the response not only contains the track playing currently, but also the last played and the intended next track. It also occurred to me that while Java Media Framework (JMF, the API from Sun for audio playback) does a good job of playing back MP3 files, there's a distinct lag while the track is loading and preparing to play, leading to unwanted gaps between tracks. I therefore resolved to load each track before it was needed; so while the current track is playing, the server is loading the next one in preparation. Obviously, I'll have to write the server in such a way that a track that's in the process of loading can be played, even if it means a short delay, in case the user swiftly chooses and starts a track.

The response is split with the "#" symbol, the number before it indicates the position of the track in the ArrayList held on the server. This is used to identify the track when requests are sent back to the server from the client. It was possible to use the track name, and then search the ArrayList for a matching track (and, indeed, this proved necessary in another context), but it seemed easier at the time to use numbers. There was no attempt to optimize the protocol to reduce network traffic. Given the short requests and responses this seemed unnecessary, and a human-readable protocol makes for easier testing.

The other commands are displayed in much the same way, allowing the user to pause, resume, adjust the volume, and play the next and last tracks. I did decide that the response to the status request would be useful in many other contexts, so several of the commands respond with the same list.

A request to play the previous track would lead to a lag as this track would not be prepared to play unless it maintained its prepared state, something I'd have to decide later on once I knew how long the lag was and if it was tolerable (as it turned out it's only a couple of seconds, which I can tolerate).

This covered the basic commands, but I also wanted to be able to browse the available tracks and pick one to be played, so I had to add commands to retrieve a track listing and to play a specific track indexed by number.

The track listing returns the file names of the tracks held on the server in the order in which they occur in the ArrayList (so no index number is needed). It also returns the full filename of the track. The client, on receipt of this data, can copy it into a local vector (no ArrayList in PersonalJava) with the knowledge that the index numbers will match those used on the server. The data is terminated with a full-stop (".") alone on a line, the same as the SMTP protocol.

The play request is numerically indexed; the word "play" is followed by a space and the number of the track to be played. This track then replaces the previously considered next track, and the server responds with a status response listing the last, current, and next tracks. If the intention is to start the chosen track immediately, a "next" message will need to be sent.

At this stage it's important to document your network protocol in as much detail as possible. I went to the extent of printing up examples and pinning them to the wall above my desk. Any changes to the protocol should be recorded immediately and extensions added to the written record.

When you're working with a team of programmers this is common sense, but when you're working alone it's easy to think you'll remember all the details, and then promptly come unstuck later when you discover you can't.

Having worked out what the client and the server are going to do, it was time to start writing them. Getting the JMF installed and working was very smooth, and while the API can appear confusing, it's actually easy to get the hang of it. By making the tracks responsible for their own preparation and playback, I was able to encapsulate all the JMF functions into a single class. Probably the most complex part is preparing the track for playing, which is accomplished with the following code:

details = new File(fname);
URL u = new URL("file:///" + fname);
Manager.setHint(Manager.PLUGIN_PLAYER, new Boolean(true));
p = Manager.createPlayer(u);
p.realize();
p.prefetch();
p.addControllerListener(this);

The String variable fname is simply the full path and filename of the MP3 file. The final line indicates that the Track class itself is the one to be informed of playback events (such as when the track finishes or has completed its preparation). Once the track is prepared, the following methods allow control from the main application:

public void start() {
p.start();
}
public void pause() {
p.stop();
}
public void stop() {
p.stop();
p.setMediaTime(new Time(0));
}

It's also important to be able to release the resources being used by a track for playback, which was done with the following code:

public void release() {
loaded = false;
p.stop();
p.deallocate();
p.close();
}

This way a track could exist in the ArrayList using few resources, then when it was known that it would be played soon, it would be prepared to start when the previous track had completed. The Boolean loaded is used to check if a track has been loaded. This is set to true on receipt of a PrefetchCompleteEvent that's passed to the ControllerListener (as specified during track preparation).

I also decided that Track objects should be responsible for deciding if they would play, so I added another method called willYouPlay(), which returns the Boolean "true" every time. This was intended to provide a more complex choice mechanism that I added later and will discuss in Part 2 of this article.

Once I got the server working, I tested it using Hyperterminal (connecting to 127.0.0.1, the TCP/IP loopback address), then set about creating a client. When developing applications such as this it's always best to start with the server, so it can be tested using a terminal application.

On the client side I developed the application using normal Java, being careful to use only constructs that are available in PersonalJava (so no beloved ArrayList).

While PersonalJava is a cutdown version of Java, as long as you're not using Swing and check before using any of the more recent APIs, you can develop in Java and then test in PersonalJava without too many problems. In this respect I did pretty well, falling down only on remembering to use elementAt when accessing a vector. The basic controls were easy enough with a simple GUI and buttons; the only issue was with picking up button click events using Personal- Java on the iPaq (the Sun implementation, though the problem also manifested itself using JEODE). Clicks don't always make themselves heard, and I was eventually forced to switch to MouseDown events to ensure usable interaction.

This had the side effect of making the buttons less responsive (they don't depress when clicked), but functionality won out over appearance.

Getting the track browsing and selection to work was considerably more effort, just working out what the interface should look like was a task in itself. I started thinking that a treeview would work well, but the thought of having to write one held me back, and I wasn't convinced that it would scale well (by this time I was working with several hundred CDs comprising over 1,600 tracks). I eventually went for two lists, both held in a single dialog frame (remember that in PersonalJava you can have only one dialog and one frame visible at a time, so the main application is in a frame and the PickTracks object is a dialog). Album names are held in the top list, while track names are displayed at the bottom (updated when a different album is selected) (see Figure 3). I decided against having any buttons in this part of the GUI as simply clicking (or tapping, as we will be using a pen) will be sufficient to select the next track to be played.

This gave me a working application. I used the PersonalJava emulation environment to make sure it was all compatible (and thus discovered the vector problem, which was easily fixed) and transferred the application to my iPaq. It works; I can now listen to music and control what comes next, but that is only the beginning...

In Part 2 of this article I'll show how I added a profile to each track, enabling me to set my mood and have suitable tracks chosen by preference. I'll also show how Bluetooth is a better network solution for this kind of application, and how it can be made to work with Java. In Part 3 I'll discuss how I added the next stage of control and enabled my mobile device to switch speakers on and off around my house.

Useful Links

More Stories By Bill Ray

Bill Ray, former editor-in-chief (and continuing distinguished contributor to) Wireless Business & Technology magazine, has been developing wireless applications for over 20 ears on just about every platform available. Heavily involved in Java since its release, he developed some of the first cryptography applications for Java and was a founder of JCP Computer Services, a company later sold to Sun Microsystems. At Swisscom he was responsible for the first Java-capable DTV set-top box, and currently holds the position of head of Enabling Software at 02, a UK network operator.

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Robin 06/07/02 01:31:00 PM EDT

Great Article Bill!

Readers interested in this article should check out 2nR-Musiker from Sensate Inc. it is a multi-threaded home network MP3 server and client system that allows PocketPC and other PCs to play MP3s stored a central PC server.

PS. We are looking for some help to make the server a standalone application. Currently it is a plugin for Realjukebox 2.0.

@ThingsExpo Stories
The age of Digital Disruption is evolving into the next era – Digital Cohesion, an age in which applications securely self-assemble and deliver predictive services that continuously adapt to user behavior. Information from devices, sensors and applications around us will drive services seamlessly across mobile and fixed devices/infrastructure. This evolution is happening now in software defined services and secure networking. Four key drivers – Performance, Economics, Interoperability and Trust ...
Data is an unusual currency; it is not restricted by the same transactional limitations as money or people. In fact, the more that you leverage your data across multiple business use cases, the more valuable it becomes to the organization. And the same can be said about the organization’s analytics. In his session at 19th Cloud Expo, Bill Schmarzo, CTO for the Big Data Practice at Dell EMC, introduced a methodology for capturing, enriching and sharing data (and analytics) across the organization...
SYS-CON Events announced today that T-Mobile will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on ...
The explosion of new web/cloud/IoT-based applications and the data they generate are transforming our world right before our eyes. In this rush to adopt these new technologies, organizations are often ignoring fundamental questions concerning who owns the data and failing to ask for permission to conduct invasive surveillance of their customers. Organizations that are not transparent about how their systems gather data telemetry without offering shared data ownership risk product rejection, regu...
Bert Loomis was a visionary. This general session will highlight how Bert Loomis and people like him inspire us to build great things with small inventions. In their general session at 19th Cloud Expo, Harold Hannon, Architect at IBM Bluemix, and Michael O'Neill, Strategic Business Development at Nvidia, discussed the accelerating pace of AI development and how IBM Cloud and NVIDIA are partnering to bring AI capabilities to "every day," on-demand. They also reviewed two "free infrastructure" pr...
New competitors, disruptive technologies, and growing expectations are pushing every business to both adopt and deliver new digital services. This ‘Digital Transformation’ demands rapid delivery and continuous iteration of new competitive services via multiple channels, which in turn demands new service delivery techniques – including DevOps. In this power panel at @DevOpsSummit 20th Cloud Expo, moderated by DevOps Conference Co-Chair Andi Mann, panelists will examine how DevOps helps to meet th...
With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo 2016 in New York. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be! Internet of @ThingsExpo, taking place June 6-8, 2017, at the Javits Center in New York City, New York, is co-located with 20th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry p...
With billions of sensors deployed worldwide, the amount of machine-generated data will soon exceed what our networks can handle. But consumers and businesses will expect seamless experiences and real-time responsiveness. What does this mean for IoT devices and the infrastructure that supports them? More of the data will need to be handled at - or closer to - the devices themselves.
Grape Up is a software company, specialized in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market across the USA and Europe, we work with a variety of customers from emerging startups to Fortune 1000 companies.
Financial Technology has become a topic of intense interest throughout the cloud developer and enterprise IT communities. Accordingly, attendees at the upcoming 20th Cloud Expo at the Javits Center in New York, June 6-8, 2017, will find fresh new content in a new track called FinTech.
Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more business becomes digital the more stakeholders are interested in this data including how it relates to business. Some of these people have never used a monitoring tool before. They have a question on their mind like “How is my application doing” but no id...
SYS-CON Events announced today that Interoute, owner-operator of one of Europe's largest networks and a global cloud services platform, has been named “Bronze Sponsor” of SYS-CON's 20th Cloud Expo, which will take place on June 6-8, 2017 at the Javits Center in New York, New York. Interoute is the owner-operator of one of Europe's largest networks and a global cloud services platform which encompasses 12 data centers, 14 virtual data centers and 31 colocation centers, with connections to 195 add...
DevOps is often described as a combination of technology and culture. Without both, DevOps isn't complete. However, applying the culture to outdated technology is a recipe for disaster; as response times grow and connections between teams are delayed by technology, the culture will die. A Nutanix Enterprise Cloud has many benefits that provide the needed base for a true DevOps paradigm.
SYS-CON Events announced today that Juniper Networks (NYSE: JNPR), an industry leader in automated, scalable and secure networks, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Juniper Networks challenges the status quo with products, solutions and services that transform the economics of networking. The company co-innovates with customers and partners to deliver automated, scalable and secure network...
The age of Digital Disruption is evolving into the next era – Digital Cohesion, an age in which applications securely self-assemble and deliver predictive services that continuously adapt to user behavior. Information from devices, sensors and applications around us will drive services seamlessly across mobile and fixed devices/infrastructure. This evolution is happening now in software defined services and secure networking. Four key drivers – Performance, Economics, Interoperability and Trust ...
In his keynote at @ThingsExpo, Chris Matthieu, Director of IoT Engineering at Citrix and co-founder and CTO of Octoblu, focused on building an IoT platform and company. He provided a behind-the-scenes look at Octoblu’s platform, business, and pivots along the way (including the Citrix acquisition of Octoblu).
SYS-CON Events announced today that Hitachi Data Systems, a wholly owned subsidiary of Hitachi LTD., will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City. Hitachi Data Systems (HDS) will be featuring the Hitachi Content Platform (HCP) portfolio. This is the industry’s only offering that allows organizations to bring together object storage, file sync and share, cloud storage gateways, and sophisticated search an...
@GonzalezCarmen has been ranked the Number One Influencer and @ThingsExpo has been named the Number One Brand in the “M2M 2016: Top 100 Influencers and Brands” by Analytic. Onalytica analyzed tweets over the last 6 months mentioning the keywords M2M OR “Machine to Machine.” They then identified the top 100 most influential brands and individuals leading the discussion on Twitter.
The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids and Smart Cities, the Industrial Internet, and more. Cool platforms like Arduino, Raspberry Pi, Intel's Galileo and Edison, and a diverse world of sensors are making the IoT a great toy box for developers in all these areas. In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists discussed what things are the most important, which will have the most profound e...
@ThingsExpo has been named the Most Influential ‘Smart Cities - IIoT' Account and @BigDataExpo has been named fourteenth by Right Relevance (RR), which provides curated information and intelligence on approximately 50,000 topics. In addition, Right Relevance provides an Insights offering that combines the above Topics and Influencers information with real time conversations to provide actionable intelligence with visualizations to enable decision making. The Insights service is applicable to eve...