Help with My Media Player
Help with My Media Player
Help with My Media Player
Help with My Media Player
Help with My Media Player
Help with My Media Player Help with My Media Player Help with My Media Player Help with My Media Player Help with My Media Player Help with My Media Player Help with My Media Player Help with My Media Player
Help with My Media Player Help with My Media Player
Help with My Media Player
Go Back  Xtreme Visual Basic Talk > > > Help with My Media Player


Reply
 
Thread Tools Display Modes
  #1  
Old 08-16-2010, 11:05 PM
MutatedGamer MutatedGamer is offline
Newcomer
 
Join Date: Aug 2010
Posts: 6
Default Help with My Media Player


So, I wanted to make a Media Player from scratch. Before I started this and effed something up, I wanted to plan out my code, testing each bit before I started it.

I use an old Unix style, since I'm very dumb at .NET. What I need to figure out how to do, is create a text file that contains a new line of code for each file I have added to my "library" and on Form1.Load load that text file, and read each line and add that to the library of music. This is only my first concept I could think of doing ATM, if you have any other ideas how I can do something like this but less buggy and more complex, feel free to say so.
Reply With Quote
  #2  
Old 08-16-2010, 11:40 PM
HQcool22's Avatar
HQcool22 HQcool22 is offline
Regular
 
Join Date: Jun 2009
Location: Oregon
Posts: 94
Default

you can use a for loop to read file names from a text file into a library

Code:
Reader = New System.IO.StreamReader("text.txt")
Dim s() As String
s = Reader.ReadLine.Split(":")
Dim NumberOfITEMs As Integer
NumberOfITEMs = CInt(s(1))

Dim x As Integer 'The Number Of Entrys
'Loop through and add each and every item
For x = 0 To (NumberOfITEMs - 1)
s = Reader.ReadLine.Split(",")
'Code to deal with library here
Next
Reader.Close()

This code would open a txt file that could look like the following,

items:3
1,Some Movie,1h 30m,movie.mp4
2,Some Song,0h 2m,song.mp3
3,Some Video,0h 8m,video.mp4
__________________
I know stuff!
Reply With Quote
  #3  
Old 08-17-2010, 08:05 AM
MutatedGamer MutatedGamer is offline
Newcomer
 
Join Date: Aug 2010
Posts: 6
Default

I.... don't get half that code. :<

Yeah, I think I should learn more before tackling this.

The stuff I don't get is, how would this exactly be WRITING that to the text file? Yes, I COULD see that code READING the file, outputting it to a string, array, whatever it's called, then the program reading it and importing that to the library, but I need it to write the code. I didn't see you Dim a StreamWriter, and that would be where the problem lies.


I was thinking I could go cheap, and have it make a file for EVERY item in the library, and cap it somewhere, but that would take to long to copy pasta, edit one character, and it would again, be capping the items, and that's dumb.

Last edited by MutatedGamer; 08-17-2010 at 08:42 AM.
Reply With Quote
  #4  
Old 08-17-2010, 09:45 AM
AtmaWeapon's Avatar
AtmaWeaponHelp with My Media Player AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

Start with File I/O in VB .NET. It is a pretty good introduction to reading/writing text files.

You would write the text by deciding what you want the text in the file to look like, constructing strings in that format, then writing those lines to the file. Let's say, for the sake of simplicity, you have some array of "MusicFile" objects:
Code:
Class MusicFile
    Public Property Name As String
    Public Property Location As String
End Class
You may decide you want your playlist to be in a format that puts one file per line like this:
Code:
Name||Location
You might choose this because you know to read the file you need a convenient way to separate the name and location, and "||" is a sequence that is unlikely to show up in names and illegal for locations. An example file with two playlist entries might look like this:
Code:
Dream On||D:\Documents\Music\Aerosmith\Aerosmith\03 Dream On.mp3
Way to Fall||D:\Documents\Music\Starsailor\Love Is Here\05 Way to Fall.mp3
So, given a MusicFile object, how do you make a string that represents it?

Most people start by learning the concatenation operator "&". The syntax is easier to illustrate than explain with words:
Code:
"Hello" & "world" -> "Helloworld"
So it "glues" the pieces of the string together. Keep in mind that the objects on both sides of the & operator must be strings; if you have a TimeSpan for duration, you'll want to call ToString() or something else that converts it to a string. So one way to make the appropriate string for a MusicFile would be like this:
Code:
Dim playlistFormat As String = file.Name & "||" & file.Location
I actually prefer the String.Format() method when I'm building relatively complicated strings. I feel like it makes it easier to visualize what the result will look like, and it has some advanced formatting capabilities that would be difficult to do otherwise. The basic syntax is again easier to illustrate than explain:
Code:
String.Format("{0} two {1}", "one", "three") ->
"one two three"
The first parameter is the "format string". It can contain arguments, which consist of a number surrounded by curly braces. Arguments must start with 0 and increase incrementally. The remaining parameters are one per argument in the format string; it's OK to provide more than needed but will throw an exception if you provide less.

Given a MusicFile like above, here's how you'd construct the string to represent it in the playlist format:
Code:
Dim playlistFormat As String = String.Format("{0}||{1}", file.Name, file.Location)
There's actually one other way to build a string like this: the String.Join() method. I'm not going to detail it because:
  1. The documentation does a good job
  2. It has no flexibility, it only builds one kind of string
  3. It has a bug I stumbled upon that MS is fine with considering by design; irrelevant to your problem but makes me avoid it.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #5  
Old 08-17-2010, 09:53 AM
MutatedGamer MutatedGamer is offline
Newcomer
 
Join Date: Aug 2010
Posts: 6
Default

Okay, I see what you're saying there, or, sort of. I pretty much GET how to do that already, I'm trying to figure out:
How to make a new line for each song added;
AND read EACH LINE and add EACH DIR to the library. I need it to add EACH line to the library, since I cannot manually make it check each line with a code that read lines 1, lines 2, lines 3, etc, because the user might have more files added then I made it read.
Reply With Quote
  #6  
Old 08-17-2010, 11:46 AM
AtmaWeapon's Avatar
AtmaWeaponHelp with My Media Player AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

The first sentence in my last post contains a link to an article, and explains that it covers both reading and writing to text files. There's no need for me to retype what's already written.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #7  
Old 08-17-2010, 01:29 PM
MutatedGamer MutatedGamer is offline
Newcomer
 
Join Date: Aug 2010
Posts: 6
Default

Quote:
Originally Posted by AtmaWeapon View Post
The first sentence in my last post contains a link to an article, and explains that it covers both reading and writing to text files. There's no need for me to retype what's already written.
Oh, sorry, I'll read that now, thx xD
Reply With Quote
  #8  
Old 08-17-2010, 05:08 PM
MutatedGamer MutatedGamer is offline
Newcomer
 
Join Date: Aug 2010
Posts: 6
Default

Arrggg. Okay, this is what I have so far. It adds a new line of text to the text file showing the EXACT directory / file location of the music file, when you select it in OpenFileDialog, and if it exists in there only a message box will come up. However, I need to find a way to insert a NEW item into the listbox for every line of text in the text file, as a seperate item. Here's my code.

Code:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        OpenFileDialog1.ShowDialog()
    End Sub
    Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
    Friend WithEvents Button2 As System.Windows.Forms.Button

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim check As New System.IO.StreamReader("C:\MediaPlayer\Settings\Library\library.txt")
        Dim checkstring As String = check.ReadToEnd
        check.Close()
        ListBox1.Items.Add(checkstring)
    End Sub
    Friend WithEvents OpenFileDialog1 As System.Windows.Forms.OpenFileDialog

    Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
        Dim CheckDir As New System.IO.DirectoryInfo("C:\MediaPlayer\Settings\Library")
        If CheckDir.Exists = False Then
            MkDir("C:\MediaPlayer\Settings\Library")
        End If
        If My.Computer.FileSystem.ReadAllText("C:\MediaPlayer\Settings\Library\library.txt").Contains(OpenFileDialog1.FileName) Then
            MsgBox("This file is already in your library!")
        Else
            Dim save As New System.IO.StreamWriter("C:\MediaPlayer\Settings\Library\library.txt", True)
            save.AutoFlush = True
            save.WriteLine(OpenFileDialog1.FileName)

            save.Close()
        End If
    End Sub
Reply With Quote
  #9  
Old 08-18-2010, 09:27 AM
AtmaWeapon's Avatar
AtmaWeaponHelp with My Media Player AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

So what happens when you read the playlist?
Button2_Click()
Code:
Read the entire contents of the file into one string.
Put that string into a ListBox.
Oh. Not cool. Let's say your file looks like this:
Code:
C:\Music\test.mp3
C:\Music\test2.mp3
Your algorithm will read that into a single string:
Code:
"C:\Music\test.mp3\r\nC:\Music\test2.mp3"
"\r\n" represents the newline. Clearly that's just one ListBox object. What to do?

The first step is to read the articles to which I link, especially when I ask you to read them twice.. Demonstrating failure to follow my advice definitely makes me less likely to dispense advice. Why do I think you haven't read the article? Well, it talks about FileStream, StreamReader, and StreamWriter, yet here you are using My.Computer.FileSystem.ReadAllText(). It's an easy trap to fall into.

Remember in school when your math teacher would teach you how to do something, only to teach you a shortcut a few weeks later? The teacher wasn't being cruel: the long way to solve a problem usually teaches you some low-level concepts on which the shortcut is based. In short, you can do math with a calculator but your life is all-around easier if you can perform at least simple math without it. Anything in the My namespace is a shortcut to other .NET functionality. These functions are generally easy to get to and easy to use, but have very little power. ReadAllText() reads everything from the file into one big string. It is likely implemented in terms of System.IO.FileStream; here's an example implementation:
Code:
Public Shared Function ReadAllText(ByVal fileName As String) As String
    Dim result As New System.Text.StringBuilder()
    Using fs As New FileStream(fileName, FileMode.Open)
        Using reader As New StreamReader(fs)
            While Not reader.EndOfStream
                result.AppendLine(reader.ReadLine())
            End While            
        End Using
    End Using

    Return result
End Function
See? All it's doing is wrapping something you could have wrote yourself. In fact, this is so common it's implemented as StreamReader.ReadToEnd() and File.ReadAllText() as well, and there may be a few other shortcuts I don't know about. But what if you want to do something more complicated, like get each individual line? ReadAllText() isn't going to do that for you, is it?

Well, it could, but I'm going to ignore that for now.

What you really need to do is learn how file I/O works in VB .NET. I don't know why you don't want to read the article I linked, but I'll try to explain it a different way.

File I/O starts with the FileStream class. You will most commonly create this using the constructor that takes a String (the file path) and a FileMode enumeration. The FileMode determines how the file is opened; the most common are Open if you intend to read the file, Create if you want to write to a file and replace its current contents, and Append if you want to write to a file but keep its current contents. FileStream itself is optimized for binary I/O. While you can certainly write text to the file using binary I/O, it's not worth it.

StreamWriter is .NET's text output class. You can create one by passing a Stream to the constructor to tell it where it should write. You'll most commonly be using Write(), which writes text to the file, and WriteLine(), which writes text to the file and automatically adds a newline at the end.

StreamReader is .NET's text input class. You can create one by passing a Stream to the constructor to tell it what it should read from. You'll most commonly use ReadLine(), which reads a single line from the file, but ReadToEnd() is often used as well (it reads the entire file from the current point to the end as one string.)

Study the approach I'm about to take; it's a basic problem solving technique that is so useful it cannot be overstated.

Let's look at the problem statement:
Quote:
I have a playlist file that consists of one file path per line. I would like to read each line of the playlist file and create a list box entry for each one.
We can decompose this into a series of steps:
Code:
Open the playlist file for text reading.
For each line of the playlist file:
    Create a listbox item
Close the playlist file.
Each of these lines of code can translate directly to a line of code:
Code:
' Open the playlist file for text reading
Using fs As New FileStream("playlist.txt", FileMode.Open)
    Using reader As New StreamReader(fs)
        ' For each line of the playlist file
        While Not reader.EndOfStream
            ' Create a listbox item
            lstPlaylist.Items.Add(reader.ReadLine())
        End While
    End Using
End Using
What's the "Using" junk in there do? It's a bit of .NET sugar that automatically closes the file when it's done, even if there's an error. I'll talk more about it later to stay on topic.

The code reads lines from the file one at a time, then adds each line to the listbox. Just like you wanted.

Now it's time for me to be mean and show you the shortcut.

The documentation is an invaluable tool. It contains information about how every member of every type in the .NET framework should be used. That is literally thousands of pages of information in answer to millions of pages of questions. When you have a question, your first thought should be to dig around MSDN for answers. You can search MSDN easily from its main page (http://msdn.microsoft.com). For example, here is the System.IO namespace, where anything that does I/O is located. File sounds interesting, doesn't it? If you click it, you'll get a page that explains a lot about how to use it. Let's look at its members; click "File Members" in the navigation area. This is every method and property that File implements. Skip down to the "Read" methods. See anything interesting? ReadAllLines() sure looks good, doesn't it? It opens a file, reads all of the lines, and returns an array in which each element is a line of the file.

Why do both exist? Well, the simple answer is that if the method that uses StreamReader didn't exist, you couldn't write ReadAllLines() easily. But that's a silly reason. Here's the real reason. Imagine your playlist gets really big. I've got 1,365 files at work, and probably more than 10,000 songs at home. ReadAllLines() works by reading the file, building an array, then returning that array. A method you write yourself using StreamReader reads the file line-by-line, and can do other things while it's at it. So if you use ReadAllLines() on a big file, you're going to make a huge array that takes lots of memory *and* you won't be able to do anything while the file is loading. The best you can do is display a dialog that says "I'm busy" and push the playlist loading onto a worker thread. If you write your own using StreamReader, you're still going to have to use a worker thread, but you'll have the ability to say, "Loading playlist files, 10,000 currently loaded..." and update that display.

The methods on the My object tend to be the easiest way to do a specific thing but are also inflexible. For this reason, I usually avoid them in a serious application because I almost always end up needing flexibility. Learn only the shortcuts and you'll have to write hacky workarounds to get extra functionality. Learn to use the low-level classes, and you'll never find a problem you can't solve.

The "later" where I talk about Using is "when you ask" at this point; this post is too long and I've spent too much time on it.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #10  
Old 08-18-2010, 10:55 AM
MutatedGamer MutatedGamer is offline
Newcomer
 
Join Date: Aug 2010
Posts: 6
Default

Please stop saying I didn't read the article, I did. Twice. And as I was following along, I didn't understand the FileStream part, and how it would differ from StreamReader/Writer. I'll try that code you gave me for it, and tell you the results.

EDIT EDIT well, it seems to be working.

Last edited by MutatedGamer; 08-18-2010 at 11:02 AM.
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump

Advertisement:





Free Publications
The ASP.NET 2.0 Anthology
101 Essential Tips, Tricks & Hacks - Free 156 Page Preview. Learn the most practical features and best approaches for ASP.NET.
subscribe
Programmers Heaven C# School Book -Free 338 Page eBook
The Programmers Heaven C# School book covers the .NET framework and the C# language.
subscribe
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition - Free 219 Page Preview!
This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time..
subscribe
Help with My Media Player
Help with My Media Player
Help with My Media Player Help with My Media Player
Help with My Media Player
Help with My Media Player
Help with My Media Player Help with My Media Player Help with My Media Player Help with My Media Player Help with My Media Player Help with My Media Player Help with My Media Player
Help with My Media Player
Help with My Media Player
 
Help with My Media Player
Help with My Media Player
 
-->