Xcode C++ play sound file

How does one play a sound file using Xcode on a Mac OS X.
For example if I want to play the file test.mp3 on xcode how would I go about doing this?
Try this:
NSSound *sound = [NSSound soundNamed:@“test.mp3"];
[sound play];
That doesn't seem to work do I have to include something?
Make sure that you drag and drop 'test.mp3' into 'Supporting Files'. I've tested the code and it works.
Cocoa's response is using Objective-C (with the Cocoa API), btw... I don't know what the equivalent would be in C++. I assume there are bindings.

If you want to try out a multi-media, multi-platform library, SFML can play files quite easily.
https://www.sfml-dev.org/tutorials/2.4/audio-sounds.php
https://www.sfml-dev.org/tutorials/2.4/ (see the SFML and Xcode section).

The library you prefer is up to you, but either way you'll have to install something, because C++ by itself has no built-in audio library.
Last edited on
There is no standard way to play a sound file directly.
Try system("test.mp3");
This will open the default player, you might need to supply the absolute path.
How would you use system on a Mac?
system() is included via #include <cstdlib>

Thomas1965's post is from a Windows perspective. I could be mistaken, but I believe you can't just type the filename in *nix environments for it to open with a default program.

Mac OS X should have a built-in command-line tool call afplay.

call it by:
afplay audiofile.mp3

ex:
1
2
3
4
5
6
7
8
#include <cstdlib>
#include <string>
int main()
{
    std::string file = "test.mp3";
    std::string command = "afplay " + file;
    system(command.c_str());
}


Also, a less convenient alternative is the command
open /path/to/mp3file.mp3
Will open the .mp3 with your default music player, which is most likely iTunes on a Mac OS X.
cocaplus, I have moved the mp3 file into a group I created: Supporting Files and it doesn't seem to work, it is giving errors on the code you've given me.
Ganado, idd exactly what you have presented and doesn't seem to work...
>it doesn't seem to work
You need to post the code which 'doesn't work' so that we can see what you are attempting to do.

>giving errors
Please post the error messages.
Please see if you can run the following. Name the file snd.mm and use Terminal to type in lines 3,4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//
//  snd.mm
//$ clang snd.mm -framework AppKit -o snd
//$ ./snd
//  

#import <AppKit/AppKit.h>

class MySound {
public:
    void playSound();
};

void MySound:: playSound(){
 NSSound *sound = [NSSound soundNamed:@"Sosumi"];
 [sound play];
}

int main()
{
 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
 [NSApplication sharedApplication];
 MySound snd;
 snd.playSound();
 [NSApp run];
 [pool drain];
 return 0;
}
Topic archived. No new replies allowed.