如何在我们的应用程序中播放来自soundcloud的音频? [英] How to play an audio from soundcloud in our app.?

查看:114
本文介绍了如何在我们的应用程序中播放来自soundcloud的音频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下程序允许用户将应用程序中的音频上传到SoundCloud,但是如果我需要在我的应用程序中从Soundcloud中的帐户播放音频怎么办?应用程序?

Following program allows user to upload an audio from app to SoundCloud.But what if i need to play an audio from my account in soundcloud in my app?How to play an audio from soundcloud or from particular url of soundclous to in our app ?

public class Record extends Activity {
    public static final String TAG = "soundcloud-intent-sharing-example";

    private boolean mStarted;
    private MediaRecorder mRecorder;
    private File mArtwork;

    private static boolean AAC_SUPPORTED  = Build.VERSION.SDK_INT >= 10;
    private static final int PICK_ARTWORK = 1;
    private static final int SHARE_SOUND  = 2;

    private static final File FILES_PATH = new File(
        Environment.getExternalStorageDirectory(),
        "Android/data/com.soundcloud.android.examples/files");

    private static final File RECORDING = new File(
            FILES_PATH,
            "demo-recording" + (AAC_SUPPORTED ? ".mp4" : "3gp"));

    private static final Uri MARKET_URI = Uri.parse("market://details?id=com.soundcloud.android");
    private static final int DIALOG_NOT_INSTALLED = 0;

    // Replace with the client id of your registered app!
    // see http://soundcloud.com/you/apps/
    private static final String CLIENT_ID = "fecfc092de134a960dc48e53c044ee91";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        if (Environment.MEDIA_MOUNTED.equals(
            Environment.getExternalStorageState())) {
            if (!FILES_PATH.mkdirs()) {
                Log.w(TAG, "Could not create " + FILES_PATH);
            }
        } else {
            Toast.makeText(this, R.string.need_external_storage, Toast.LENGTH_LONG).show();
            finish();
        }

        setContentView(R.layout.record);

        final Button record_btn = (Button) findViewById(R.id.record_btn);
        final Button share_btn = (Button) findViewById(R.id.share_btn);
        final Button play_btn = (Button) findViewById(R.id.play_btn);
        final Button artwork_btn = (Button) findViewById(R.id.artwork_btn);

        Record last = getLastNonConfigurationInstance();
        if (last != null) {
            mStarted  = last.mStarted;
            mRecorder = last.mRecorder;
            mArtwork  = last.mArtwork;
            record_btn.setText(mStarted ? R.string.stop : R.string.record);
        }

        record_btn.setOnClickListener(new View.OnClickListener() {
            public synchronized void onClick(View v) {
                if (!mStarted) {
                    Toast.makeText(Record.this, R.string.recording, Toast.LENGTH_SHORT).show();

                    mStarted = true;
                    mRecorder = getRecorder(RECORDING, AAC_SUPPORTED);
                    mRecorder.start();
                    record_btn.setText(R.string.stop);
                } else {
                    Toast.makeText(Record.this, R.string.recording_stopped, Toast.LENGTH_SHORT).show();

                    mRecorder.stop();
                    mRecorder.release();
                    mRecorder = null;
                    mStarted = false;

                    record_btn.setText(R.string.record);
                    share_btn.setEnabled(true);
                    play_btn.setEnabled(true);
                    artwork_btn.setEnabled(true);
                }
            }
        });


        play_btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                play_btn.setEnabled(false);
                record_btn.setEnabled(false);
                share_btn.setEnabled(false);
                play(new MediaPlayer.OnCompletionListener() {
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        play_btn.setEnabled(true);
                        record_btn.setEnabled(true);
                        share_btn.setEnabled(true);
                    }
                });
            }
        });

        share_btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                shareSound();
            }
        });

        artwork_btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"), PICK_ARTWORK);
            }
        });

        if (!isCompatibleSoundCloudInstalled(this)) {
            showDialog(DIALOG_NOT_INSTALLED);
        }
    }

    private void play(MediaPlayer.OnCompletionListener onCompletion) {
        MediaPlayer player = new MediaPlayer();
        try {
            player.setDataSource(RECORDING.getAbsolutePath());
            player.prepare();
            player.setOnCompletionListener(onCompletion);
            player.start();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    // the actual sharing happens here
    private void shareSound() {
        Intent intent = new Intent("com.soundcloud.android.SHARE")
                .putExtra(Intent.EXTRA_STREAM, Uri.fromFile(RECORDING))
                // here you can set metadata for the track to be uploaded
                .putExtra("com.soundcloud.android.extra.title", "SoundCloud Android Intent Demo upload")
                .putExtra("com.soundcloud.android.extra.where", "Somewhere")
                .putExtra("com.soundcloud.android.extra.description", "This is a demo track.")
                .putExtra("com.soundcloud.android.extra.public", true)
                .putExtra("com.soundcloud.android.extra.tags", new String[] {
                    "demo",
                    "post lolcat bluez",
                    "soundcloud:created-with-client-id="+CLIENT_ID
                 })
                .putExtra("com.soundcloud.android.extra.genre", "Easy Listening")
                .putExtra("com.soundcloud.android.extra.location", getLocation());

        // attach artwork if user has picked one
        if (mArtwork != null) {
            intent.putExtra("com.soundcloud.android.extra.artwork", Uri.fromFile(mArtwork));
        }

        try {
            startActivityForResult(intent, SHARE_SOUND);
        } catch (ActivityNotFoundException notFound) {
            // use doesn't have SoundCloud app installed, show a dialog box
            showDialog(DIALOG_NOT_INSTALLED);
        }
    }


    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case SHARE_SOUND:
                // callback gets executed when the SoundCloud app returns
                if (resultCode == RESULT_OK) {
                    Toast.makeText(this, R.string.shared_ok, Toast.LENGTH_SHORT).show();
                } else {
                    // canceled
                    Toast.makeText(this, R.string.shared_canceled, Toast.LENGTH_SHORT).show();
                }
                break;

            case PICK_ARTWORK:
                if (resultCode == RESULT_OK) {
                    mArtwork = getFromMediaUri(getContentResolver(), data.getData());
                }
                break;
        }
    }

    private MediaRecorder getRecorder(File path, boolean useAAC) {
        MediaRecorder recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);

         if (useAAC) {
             recorder.setAudioSamplingRate(44100);
             recorder.setAudioEncodingBitRate(96000);
             recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
             recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
         } else {
             // older version of Android, use crappy sounding voice codec
             recorder.setAudioSamplingRate(8000);
             recorder.setAudioEncodingBitRate(12200);
             recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
             recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
         }

        recorder.setOutputFile(path.getAbsolutePath());

        try {
            recorder.prepare();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return recorder;
    }

    // just get the last known location from the passive provider - not terribly
    // accurate but it's a demo app.
    private Location getLocation() {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        return locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
    }

    @Override public Record getLastNonConfigurationInstance() {
        return (Record) super.getLastNonConfigurationInstance();
    }

    @Override public Record onRetainNonConfigurationInstance() {
        return this;
    }

    // Helper method to get file from a content uri
    private static File getFromMediaUri(ContentResolver resolver, Uri uri) {
        if ("file".equals(uri.getScheme())) {
            return new File(uri.getPath());
        } else if ("content".equals(uri.getScheme())) {
            String[] filePathColumn = {MediaStore.MediaColumns.DATA};
            Cursor cursor = resolver.query(uri, filePathColumn, null, null, null);
            if (cursor != null) {
                try {
                    if (cursor.moveToFirst()) {
                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        String filePath = cursor.getString(columnIndex);
                        return new File(filePath);
                    }
                } finally {
                    cursor.close();
                }
            }
        }
        return null;
    }


    private static boolean isCompatibleSoundCloudInstalled(Context context) {
        try {
            PackageInfo info = context.getPackageManager()
                                      .getPackageInfo("com.soundcloud.android",
                    PackageManager.GET_META_DATA);

            // intent sharing only got introduced with version 22
            return info != null && info.versionCode >= 22;
        } catch (PackageManager.NameNotFoundException e) {
            // not installed at all
            return false;
        }
    }

    @Override
    protected Dialog onCreateDialog(int id, Bundle data) {
        if (DIALOG_NOT_INSTALLED == id) {
            return new AlertDialog.Builder(this)
                    .setTitle(R.string.sc_app_not_found)
                    .setMessage(R.string.sc_app_not_found_message)
                    .setPositiveButton(android.R.string.yes, new Dialog.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            Intent market = new Intent(Intent.ACTION_VIEW, MARKET_URI);
                            startActivity(market);
                        }
                    })
                    .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    }).create();
        } else {
            return null;
        }
    }
}

推荐答案

了解声音的网址,您需要执行以下操作:

knowing the url of the sound, you need to do the following:

  • resolve the URL in order to get the soundcloud API URL using Resolve endpoint

加载轨道API URL以获取json或xml中的轨道表示形式

load the tracks API URL to get track representation in json or xml

初始化音频对象并将音频源设置为轨道表示形式的stream_url属性值

initialise audio object and set the audio source to the value of stream_url property of track representation

具体的实现方式取决于所使用的库等.但是,您肯定需要使用HTTP请求,JSON解析器和音频对象.

The particular implementation varies depending on the libraries you use etc. But you'll definitely need to use HTTP requests, JSON parser and an audio object.

这篇关于如何在我们的应用程序中播放来自soundcloud的音频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆